<?php
declare(strict_types=1);

namespace App\Services;

use App\Core\Database;

final class EmailTemplateService
{
    private static function hasColumn($db, string $col): bool
    {
        $st = $db->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='email_templates' AND column_name=:c");
        $st->execute([':c'=>$col]);
        return ((int)$st->fetchColumn()) === 1;
    }

    public static function render(string $templateKey, string $lang, array $vars): array
    {
        $db = Database::getInstance();
        $st = $db->prepare("SELECT * FROM email_templates WHERE template_key=:k AND is_active=1 LIMIT 1");
        $st->execute([':k'=>$templateKey]);
        $t = $st->fetch();

        if (!$t) return [$templateKey, '', ''];

        $isAr = ($lang === 'ar');

        $subject = (string)($isAr ? ($t['subject_ar'] ?? '') : ($t['subject_en'] ?? ''));

        // Prefer new columns if exist, else fallback to body_en/body_ar
        $hasHtmlEn = self::hasColumn($db, 'body_html_en');
        $hasTextEn = self::hasColumn($db, 'body_text_en');

        if ($hasHtmlEn) {
            $html = (string)($isAr ? ($t['body_html_ar'] ?? '') : ($t['body_html_en'] ?? ''));
        } else {
            $html = (string)($isAr ? ($t['body_ar'] ?? '') : ($t['body_en'] ?? ''));
        }

        if ($hasTextEn) {
            $text = (string)($isAr ? ($t['body_text_ar'] ?? '') : ($t['body_text_en'] ?? ''));
        } else {
            // fallback text = stripped html/body
            $text = strip_tags($html);
        }

        foreach ($vars as $k => $v) {
            $val = (string)$v;
            $subject = str_replace('{{'.$k.'}}', $val, $subject);
            $html    = str_replace('{{'.$k.'}}', htmlspecialchars($val, ENT_QUOTES, 'UTF-8'), $html);
            $text    = str_replace('{{'.$k.'}}', $val, $text);
        }

        return [$subject, $html, $text];
    }

    public static function queue(string $toEmail, ?string $toName, string $templateKey, string $lang, array $vars): void
    {
        $db = Database::getInstance();
        [$subject, $html, $text] = self::render($templateKey, $lang, $vars);

        $db->prepare("INSERT INTO email_queue(to_email,to_name,template_key,subject_line,body_html,body_text,status)
                      VALUES(:to,:name,:k,:subj,:html,:txt,'queued')")
           ->execute([
             ':to'=>$toEmail,
             ':name'=>$toName,
             ':k'=>$templateKey,
             ':subj'=>$subject,
             ':html'=>$html,
             ':txt'=>$text,
           ]);

        $db->prepare("INSERT INTO jobs(job_type,status,run_after) VALUES('email_queue_send','queued',NOW())")->execute();
    }
}
