<?php declare(strict_types=1);

class EmailQueue {
    private Database $db;

    public function __construct() {
        $this->db = new Database();
    }

    public function getQueueStats(): array {
        $this->db->query('
            SELECT 
                SUM(CASE WHEN status = "pending" THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN status = "sent" THEN 1 ELSE 0 END) as sent,
                SUM(CASE WHEN status = "failed" THEN 1 ELSE 0 END) as failed
            FROM email_queue
        ');
        $result = $this->db->single();
        
        return [
            'pending' => $result->pending ?? 0,
            'sent'    => $result->sent ?? 0,
            'failed'  => $result->failed ?? 0
        ];
    }

    public function getRecentEmails(int $limit = 20): array {
        $this->db->query('SELECT * FROM email_queue ORDER BY created_at DESC LIMIT :limit');
        $this->db->bind(':limit', $limit);
        return $this->db->resultSet();
    }

    // --- NEW: FETCH SINGLE EMAIL FOR PREVIEW ---
    public function getEmailById(int $id): object|bool {
        $this->db->query('SELECT * FROM email_queue WHERE id = :id');
        $this->db->bind(':id', $id);
        return $this->db->single();
    }
}