<?php
namespace App\Core;

use App\Core\Database;
use App\Core\SmtpMailer;

class ConferenceMailer
{
    private \PDO $db;

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

    private function template(int $conferenceId, int $orgId, string $key): ?array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM conference_email_templates
            WHERE conference_id = ?
              AND org_id = ?
              AND is_active = 1
              AND (template_key = ? OR event_key = ?)
            ORDER BY id DESC
            LIMIT 1
        ");
        $stmt->execute([$conferenceId, $orgId, $key, $key]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);

        return $row ?: null;
    }

    private function renderText(string $text, array $vars): string
    {
        foreach ($vars as $k => $v) {
            $text = str_replace('{' . $k . '}', (string)$v, $text);
        }

        return $text;
    }

    public function queueAndSend(
        int $conferenceId,
        int $orgId,
        ?int $submissionId,
        ?int $userId,
        string $templateKey,
        string $recipientEmail,
        string $recipientName,
        array $vars,
        ?int $createdBy = null,
        string $lang = 'en'
    ): array {
        $tpl = $this->template($conferenceId, $orgId, $templateKey);

        if (!$tpl) {
            return [
                'ok' => false,
                'error' => "Active template not found: {$templateKey}",
                'outbox_id' => null,
            ];
        }

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

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

        $subject = $this->renderText($subjectRaw, $vars);
        $body = $this->renderText($bodyRaw, $vars);

        $stmt = $this->db->prepare("
            INSERT INTO conference_mail_outbox
            (org_id, conference_id, submission_id, user_id, template_key, event_key,
             recipient_email, recipient_name, subject, body, status, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?)
        ");
        $stmt->execute([
            $orgId,
            $conferenceId,
            $submissionId,
            $userId,
            $tpl['template_key'] ?: $templateKey,
            $tpl['event_key'] ?: $templateKey,
            $recipientEmail,
            $recipientName,
            $subject,
            $body,
            $createdBy
        ]);

        $outboxId = (int)$this->db->lastInsertId();

        $smtp = new SmtpMailer();
        $result = $smtp->send($recipientEmail, $subject, $body, $recipientName);

        if (!empty($result['ok'])) {
            $stmt = $this->db->prepare("
                UPDATE conference_mail_outbox
                SET status='sent',
                    sent_at=NOW(),
                    error_message=NULL
                WHERE id=?
            ");
            $stmt->execute([$outboxId]);

            return [
                'ok' => true,
                'error' => null,
                'outbox_id' => $outboxId,
            ];
        }

        $error = trim(($result['error'] ?? 'SMTP failed') . "\n\n" . ($result['debug'] ?? ''));

        $stmt = $this->db->prepare("
            UPDATE conference_mail_outbox
            SET status='failed',
                error_message=?
            WHERE id=?
        ");
        $stmt->execute([$error, $outboxId]);

        return [
            'ok' => false,
            'error' => $error,
            'outbox_id' => $outboxId,
        ];
    }
}
