<?php
namespace App\Services;

use App\Core\Database;

class ConferenceEmailTemplateService
{
    public static function render(int $conferenceId, string $key, array $vars = [], string $lang = 'en'): array
    {
        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT *
            FROM conference_email_templates
            WHERE conference_id = ?
              AND (template_key = ? OR event_key = ?)
              AND is_active = 1
            LIMIT 1
        ");
        $stmt->execute([$conferenceId, $key, $key]);
        $tpl = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$tpl) {
            return [
                'subject' => '',
                'body' => '',
            ];
        }

        $subject = $lang === 'ar'
            ? (($tpl['subject_ar'] ?? '') ?: ($tpl['subject_en'] ?? ''))
            : (($tpl['subject_en'] ?? '') ?: ($tpl['subject_ar'] ?? ''));

        $body = $lang === 'ar'
            ? (($tpl['body_ar'] ?? '') ?: ($tpl['body_en'] ?? ''))
            : (($tpl['body_en'] ?? '') ?: ($tpl['body_ar'] ?? ''));

        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 static function availableKeys(): array
    {
        return [
            'submission_received',
            'review_assigned',
            'review_submitted',
            'decision_notification',
            'revision_required',
        ];
    }
}
