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

class DeliverabilityDomain extends Model
{
    public function all(): array
    {
        $sql = 'SELECT dd.*, u.name AS created_by_name,
            (SELECT COUNT(*) FROM domain_dns_checks c WHERE c.deliverability_domain_id = dd.id AND c.status = "pass") AS passed_checks,
            (SELECT COUNT(*) FROM domain_dns_checks c WHERE c.deliverability_domain_id = dd.id) AS total_checks
            FROM deliverability_domains dd
            LEFT JOIN users u ON u.id = dd.created_by
            ORDER BY dd.is_active DESC, dd.domain_name ASC';
        return $this->db->query($sql)->fetchAll();
    }

    public function active(): array
    {
        $stmt = $this->db->query('SELECT * FROM deliverability_domains WHERE is_active = 1 ORDER BY domain_name ASC');
        return $stmt->fetchAll();
    }

    public function find(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM deliverability_domains WHERE id = ? LIMIT 1');
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public function save(array $data): int
    {
        $id = (int)($data['id'] ?? 0);
        $domain = strtolower(trim((string)($data['domain_name'] ?? '')));
        if ($domain === '') {
            throw new RuntimeException('Domain name is required.');
        }
        $payload = [
            $domain,
            trim((string)($data['provider_hint'] ?? 'sendgrid')) ?: 'sendgrid',
            trim((string)($data['postmaster_status'] ?? 'planned')) ?: 'planned',
            trim((string)($data['dkim_selector'] ?? 's1')) ?: 's1',
            trim((string)($data['spf_include'] ?? 'include:sendgrid.net')) ?: 'include:sendgrid.net',
            trim((string)($data['dmarc_policy'] ?? 'quarantine')) ?: 'quarantine',
            trim((string)($data['return_path_domain'] ?? '')) ?: null,
            trim((string)($data['tracking_domain'] ?? '')) ?: null,
            trim((string)($data['bimi_svg_url'] ?? '')) ?: null,
            !empty($data['one_click_unsubscribe_enabled']) ? 1 : 0,
            trim((string)($data['warmup_profile'] ?? '')) ?: null,
            (float)($data['complaint_threshold'] ?? 0.1),
            (float)($data['bounce_threshold'] ?? 3.0),
            (int)($data['daily_volume_target'] ?? 5000),
            trim((string)($data['dns_summary_json'] ?? '')) ?: json_encode(['source' => 'manual'], JSON_UNESCAPED_SLASHES),
            !empty($data['is_active']) ? 1 : 0,
        ];
        if ($id > 0) {
            $stmt = $this->db->prepare('UPDATE deliverability_domains SET domain_name = ?, provider_hint = ?, postmaster_status = ?, dkim_selector = ?, spf_include = ?, dmarc_policy = ?, return_path_domain = ?, tracking_domain = ?, bimi_svg_url = ?, one_click_unsubscribe_enabled = ?, warmup_profile = ?, complaint_threshold = ?, bounce_threshold = ?, daily_volume_target = ?, dns_summary_json = ?, is_active = ?, updated_at = NOW() WHERE id = ?');
            $payload[] = $id;
            $stmt->execute($payload);
            return $id;
        }
        $stmt = $this->db->prepare('INSERT INTO deliverability_domains (domain_name, provider_hint, postmaster_status, dkim_selector, spf_include, dmarc_policy, return_path_domain, tracking_domain, bimi_svg_url, one_click_unsubscribe_enabled, warmup_profile, complaint_threshold, bounce_threshold, daily_volume_target, dns_summary_json, is_active, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
        $payload[] = (int)(current_user()['id'] ?? 0) ?: null;
        $stmt->execute($payload);
        return (int)$this->db->lastInsertId();
    }

    public function stats(): array
    {
        $row = $this->db->query('SELECT COUNT(*) total_count,
            SUM(is_active = 1) active_count,
            SUM(postmaster_status IN ("connected","healthy")) healthy_count,
            AVG(daily_volume_target) avg_daily_volume,
            MAX(last_checked_at) last_checked_at
            FROM deliverability_domains')->fetch();
        return $row ?: ['total_count' => 0, 'active_count' => 0, 'healthy_count' => 0, 'avg_daily_volume' => 0, 'last_checked_at' => null];
    }
}
