<?php
declare(strict_types=1);

namespace App\Services;

use App\Core\Database;

final class MailTemplateService
{
    public static function templateByKey(string $templateKey): ?array
    {
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT * FROM email_templates WHERE template_key = :template_key AND is_active = 1 LIMIT 1");
        $stmt->execute([':template_key' => $templateKey]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public static function renderString(string $text, array $data): string
    {
        foreach ($data as $k => $v) {
            $text = str_replace('{{' . $k . '}}', (string) $v, $text);
        }
        return $text;
    }

    public static function queue(string $templateKey, string $email, string $name = '', array $payload = []): void
    {
        $template = self::templateByKey($templateKey);
        if (!$template) {
            return;
        }

        $lang = ($payload['lang'] ?? 'en') === 'ar' ? 'ar' : 'en';
        $subject = $lang === 'ar' ? (string) ($template['subject_ar'] ?? '') : (string) ($template['subject_en'] ?? '');
        $body = $lang === 'ar' ? (string) ($template['body_ar'] ?? '') : (string) ($template['body_en'] ?? '');

        $subjectRendered = self::renderString($subject, $payload);
        $bodyRendered = self::renderString($body, $payload);

        $db = Database::getInstance();
        $stmt = $db->prepare("
            INSERT INTO email_queue (
                template_key, recipient_email, recipient_name,
                subject_rendered, body_rendered, payload_json, send_status
            ) VALUES (
                :template_key, :recipient_email, :recipient_name,
                :subject_rendered, :body_rendered, :payload_json, 'pending'
            )
        ");
        $stmt->execute([
            ':template_key' => $templateKey,
            ':recipient_email' => $email,
            ':recipient_name' => $name ?: null,
            ':subject_rendered' => $subjectRendered,
            ':body_rendered' => $bodyRendered,
            ':payload_json' => json_encode($payload, JSON_UNESCAPED_UNICODE),
        ]);
    }

    public static function sendPending(int $limit = 20): int
    {
        $db = Database::getInstance();
        $stmt = $db->prepare("
            SELECT *
            FROM email_queue
            WHERE send_status = 'pending'
            ORDER BY id ASC
            LIMIT :lim
        ");
        $stmt->bindValue(':lim', $limit, \PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll();

        $sent = 0;

        foreach ($rows as $row) {
            $ok = MailerService::send(
                (string) $row['recipient_email'],
                (string) ($row['subject_rendered'] ?? ''),
                (string) ($row['body_rendered'] ?? ''),
                (string) ($row['recipient_name'] ?? '')
            );

            $up = $db->prepare("
                UPDATE email_queue
                SET send_status = :send_status,
                    attempts = attempts + 1,
                    sent_at = CASE WHEN :send_status2 = 'sent' THEN NOW() ELSE sent_at END,
                    last_error = :last_error
                WHERE id = :id
            ");
            $up->execute([
                ':send_status' => $ok ? 'sent' : 'failed',
                ':send_status2' => $ok ? 'sent' : 'failed',
                ':last_error' => $ok ? null : 'send failed',
                ':id' => (int) $row['id'],
            ]);

            if ($ok) {
                $sent++;
            }
        }

        return $sent;
    }
}
