<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/conference_scope.php';

use App\Core\Controller;
use App\Core\Database;

final class AdminCertificateEmailController extends Controller
{
    private function ensureQueue($db): void
    {
        $db->query("SELECT 1 FROM email_queue LIMIT 1");
    }

    private function baseUrl(): string
    {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host = (string)($_SERVER['HTTP_HOST'] ?? 'localhost');
        $uri = (string)($_SERVER['SCRIPT_NAME'] ?? '/easychair/public/index.php');
        $base = rtrim(str_replace('/index.php', '', $uri), '/');
        return $scheme . '://' . $host . $base;
    }

    private function getCert($db, int $certId): array
    {
        $st = $db->prepare("
          SELECT cert.*, u.first_name,u.last_name,u.email,u.preferred_lang,
                 c.title_en,c.title_ar
          FROM certificates cert
          INNER JOIN users u ON u.id=cert.user_id
          INNER JOIN conferences c ON c.id=cert.conference_id
          WHERE cert.id=:id
          LIMIT 1
        ");
        $st->execute([':id'=>$certId]);
        $row = $st->fetch();
        if (!$row) throw new \RuntimeException("Certificate not found");
        return $row;
    }

    private function queue($db, string $to, ?string $name, string $subject, ?string $html, ?string $text, string $templateKey='certificate'): void
    {
        $db->prepare("
          INSERT INTO email_queue (to_email, to_name, template_key, subject_line, body_html, body_text, status, created_at)
          VALUES (:to,:name,:tkey,:subj,:html,:txt,'queued',NOW())
        ")->execute([
            ':to'=>$to,
            ':name'=>$name,
            ':tkey'=>$templateKey,
            ':subj'=>$subject,
            ':html'=>$html,
            ':txt'=>$text,
        ]);
    }

    public function sendOne(): void
    {
        require_permission('admin.access');
        if (!$this->isPost()) redirect('admin/certificates');
        csrf_check();

        $db = Database::getInstance();
        $this->ensureQueue($db);

        $certId = (int)($_POST['cert_id'] ?? 0);
        $conferenceId = (int)($_POST['conference_id'] ?? 0);
        $certType = trim((string)($_POST['cert_type'] ?? 'reviewer'));

        $row = $this->getCert($db, $certId);

        $to = (string)$row['email'];
        if ($to === '') { flash('danger','No email for user'); redirect('admin/certificates?conference_id='.$conferenceId.'&type='.$certType); }

        $name = trim((string)$row['first_name'].' '.(string)$row['last_name']);
        $lang = (string)($row['preferred_lang'] ?? 'en');

        $confTitle = ($lang==='ar') ? (string)($row['title_ar'] ?? '') : (string)($row['title_en'] ?? '');
        $code = (string)$row['cert_code'];
        $type = (string)$row['cert_type'];

        $base = $this->baseUrl();
        $verifyUrl = $base . '/cert?code=' . rawurlencode($code);
        $pdfUrl = $base . '/cert/pdf?code=' . rawurlencode($code);

        $subject = ($lang==='ar') ? "شهادة {$type} - {$confTitle}" : "{$type} Certificate - {$confTitle}";

        $text = ($lang==='ar')
            ? "السلام عليكم {$name},\n\nشهادة {$type} ضمن {$confTitle}\n\nرابط التحقق:\n{$verifyUrl}\n\nرابط PDF:\n{$pdfUrl}\n"
            : "Dear {$name},\n\nYour {$type} certificate for {$confTitle}\n\nVerify:\n{$verifyUrl}\n\nPDF:\n{$pdfUrl}\n";

        $html = nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8'));

        $this->queue($db, $to, $name ?: null, $subject, $html, $text, 'certificate');

        flash('success', 'Queued certificate email.');
        redirect('admin/certificates?conference_id='.$conferenceId.'&type='.$certType);
    }

    public function sendBatch(): void
    {
        require_permission('admin.access');
        if (!$this->isPost()) redirect('admin/certificates');
        csrf_check();

        $db = Database::getInstance();
        $this->ensureQueue($db);

        $conferenceId = (int)($_POST['conference_id'] ?? 0);
        $certType = trim((string)($_POST['cert_type'] ?? 'reviewer'));
        if ($conferenceId<=0) { flash('danger', trans('required_fields')); redirect('admin/certificates'); }

        $st = $db->prepare("SELECT id FROM certificates WHERE conference_id=:cid AND cert_type=:ct ORDER BY id DESC LIMIT 2000");
        $st->execute([':cid'=>$conferenceId, ':ct'=>$certType]);
        $ids = array_map('intval', $st->fetchAll(\PDO::FETCH_COLUMN));

        $queued = 0;
        foreach ($ids as $id) {
            try {
                $row = $this->getCert($db, $id);
                $to = (string)$row['email'];
                if ($to === '') continue;

                $name = trim((string)$row['first_name'].' '.(string)$row['last_name']);
                $lang = (string)($row['preferred_lang'] ?? 'en');
                $confTitle = ($lang==='ar') ? (string)($row['title_ar'] ?? '') : (string)($row['title_en'] ?? '');
                $code = (string)$row['cert_code'];
                $type = (string)$row['cert_type'];

                $base = $this->baseUrl();
                $verifyUrl = $base . '/cert?code=' . rawurlencode($code);
                $pdfUrl = $base . '/cert/pdf?code=' . rawurlencode($code);

                $subject = ($lang==='ar') ? "شهادة {$type} - {$confTitle}" : "{$type} Certificate - {$confTitle}";
                $text = ($lang==='ar')
                    ? "السلام عليكم {$name},\n\nشهادة {$type} ضمن {$confTitle}\n\nرابط التحقق:\n{$verifyUrl}\n\nرابط PDF:\n{$pdfUrl}\n"
                    : "Dear {$name},\n\nYour {$type} certificate for {$confTitle}\n\nVerify:\n{$verifyUrl}\n\nPDF:\n{$pdfUrl}\n";
                $html = nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8'));

                $this->queue($db, $to, $name ?: null, $subject, $html, $text, 'certificate');
                $queued++;
            } catch (\Throwable $e) {}
        }

        flash('success', "Queued certificate emails: {$queued}");
        redirect('admin/certificates?conference_id='.$conferenceId.'&type='.$certType);
    }
}
