<?php
declare(strict_types=1);

namespace App\Services;

use App\Core\Database;
use PDO;

final class MailQueueService
{
    private PDO $db;

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

    public function queue(string $toEmail, string $subject, string $bodyHtml, string $templateKey = '', string $toName = '', string $bodyText = ''): int
    {
        $stmt = $this->db->prepare("
            INSERT INTO email_queue (
                to_email, to_name, template_key, subject_line, body_html, body_text, status
            ) VALUES (
                :to_email, :to_name, :template_key, :subject_line, :body_html, :body_text, 'queued'
            )
        ");
        $stmt->execute([
            ':to_email' => $toEmail,
            ':to_name' => $toName ?: null,
            ':template_key' => $templateKey ?: null,
            ':subject_line' => $subject,
            ':body_html' => $bodyHtml ?: null,
            ':body_text' => $bodyText ?: null,
        ]);
        return (int) $this->db->lastInsertId();
    }

    public function rows(int $limit = 100): array
    {
        $stmt = $this->db->prepare("SELECT * FROM email_queue ORDER BY id DESC LIMIT :lim");
        $stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function queued(int $limit = 25): array
    {
        $stmt = $this->db->prepare("SELECT * FROM email_queue WHERE status = 'queued' ORDER BY id ASC LIMIT :lim");
        $stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function markSent(int $id): void
    {
        $stmt = $this->db->prepare("UPDATE email_queue SET status = 'sent', sent_at = NOW(), error_message = NULL WHERE id = :id");
        $stmt->execute([':id' => $id]);
    }

    public function markFailed(int $id, string $error): void
    {
        $stmt = $this->db->prepare("UPDATE email_queue SET status = 'failed', error_message = :error WHERE id = :id");
        $stmt->execute([
            ':id' => $id,
            ':error' => $error,
        ]);
    }

    public function renderTemplate(array $template, array $vars, string $lang = 'en'): array
    {
        $subject = $lang === 'ar' ? (string) ($template['subject_ar'] ?? '') : (string) ($template['subject_en'] ?? '');
        $body = $lang === 'ar' ? (string) ($template['body_ar'] ?? '') : (string) ($template['body_en'] ?? '');

        foreach ($vars as $k => $v) {
            $subject = str_replace('{{' . $k . '}}', (string) $v, $subject);
            $body = str_replace('{{' . $k . '}}', (string) $v, $body);
        }

        return ['subject' => $subject, 'body' => $body];
    }

    public function templateByKey(string $key): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM email_templates WHERE template_key = :k AND is_active = 1 LIMIT 1");
        $stmt->execute([':k' => $key]);
        $row = $stmt->fetch();
        return $row ?: null;
    }
}
