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

class Suppression extends Model
{
    public function all(): array
    {
        return $this->db->query('SELECT * FROM suppression_list ORDER BY created_at DESC, id DESC')->fetchAll();
    }

    public function summary(int $days = 30): array
    {
        $days = max(1, (int)$days);
        $sql = "SELECT
            COUNT(*) AS total,
            SUM(channel = 'email') AS email_total,
            SUM(channel = 'sms') AS sms_total,
            SUM(reason LIKE 'bounce%') AS bounce_total,
            SUM(reason LIKE 'complaint%') AS complaint_total,
            SUM(reason LIKE 'blocked%') AS blocked_total,
            SUM(created_at >= DATE_SUB(NOW(), INTERVAL {$days} DAY)) AS recent_total
            FROM suppression_list";
        return $this->db->query($sql)->fetch() ?: [];
    }

    public function recent(int $limit = 12): array
    {
        $stmt = $this->db->prepare('SELECT * FROM suppression_list ORDER BY updated_at DESC, id DESC LIMIT ?');
        $stmt->bindValue(1, $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function isSuppressed(string $channel, string $address): bool
    {
        $stmt = $this->db->prepare('SELECT id FROM suppression_list WHERE channel = ? AND normalized_address = ? LIMIT 1');
        $stmt->execute([$channel, normalize_address($address)]);
        return (bool)$stmt->fetch();
    }

    public function add(string $channel, string $address, string $reason = 'manual', ?int $contactId = null, ?int $messageId = null): int
    {
        $normalized = normalize_address($address);
        if ($normalized === '') {
            throw new RuntimeException('A valid address is required for suppression.');
        }
        $stmt = $this->db->prepare('INSERT INTO suppression_list (contact_id, message_id, channel, address, normalized_address, reason) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE reason = VALUES(reason), contact_id = COALESCE(VALUES(contact_id), contact_id), message_id = COALESCE(VALUES(message_id), message_id), updated_at = NOW()');
        $stmt->execute([$contactId, $messageId, $channel, $address, $normalized, $reason]);
        return (int)$this->db->lastInsertId();
    }

    public function delete(int $id): void
    {
        $stmt = $this->db->prepare('DELETE FROM suppression_list WHERE id = ?');
        $stmt->execute([$id]);
    }
}
