<?php
require_once __DIR__ . '/../Core.php';

class DomainDnsCheck extends Model
{
    public function replaceForDomain(int $domainId, array $records): void
    {
        $delete = $this->db->prepare('DELETE FROM domain_dns_checks WHERE deliverability_domain_id = ?');
        $delete->execute([$domainId]);
        $stmt = $this->db->prepare('INSERT INTO domain_dns_checks (deliverability_domain_id, record_type, host_name, expected_value, observed_value, status, details_json, checked_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())');
        foreach ($records as $record) {
            $stmt->execute([
                $domainId,
                trim((string)($record['type'] ?? 'TXT')),
                trim((string)($record['host'] ?? '@')),
                trim((string)($record['value'] ?? '')),
                trim((string)($record['observed_value'] ?? '')) ?: null,
                trim((string)($record['status'] ?? 'planned')) ?: 'planned',
                json_encode(['purpose' => $record['purpose'] ?? 'Planned record'], JSON_UNESCAPED_SLASHES),
            ]);
        }
        $update = $this->db->prepare('UPDATE deliverability_domains SET last_checked_at = NOW(), updated_at = NOW() WHERE id = ?');
        $update->execute([$domainId]);
    }

    public function byDomain(int $domainId): array
    {
        $stmt = $this->db->prepare('SELECT * FROM domain_dns_checks WHERE deliverability_domain_id = ? ORDER BY checked_at DESC, id ASC');
        $stmt->execute([$domainId]);
        return $stmt->fetchAll();
    }

    public function summaryByDomain(): array
    {
        $sql = 'SELECT deliverability_domain_id,
            SUM(status = "pass") pass_count,
            SUM(status = "warn") warn_count,
            SUM(status = "planned") planned_count,
            COUNT(*) total_count,
            MAX(checked_at) last_checked_at
            FROM domain_dns_checks
            GROUP BY deliverability_domain_id';
        $rows = $this->db->query($sql)->fetchAll();
        $summary = [];
        foreach ($rows as $row) {
            $summary[(int)$row['deliverability_domain_id']] = $row;
        }
        return $summary;
    }
}
