<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AdminDecisionBatchEmailController extends Controller
{
    private function colExists(string $table, string $col): bool
    {
        $db = Database::getInstance();
        $st = $db->prepare("
          SELECT COUNT(*) FROM information_schema.COLUMNS
          WHERE TABLE_SCHEMA=DATABASE()
            AND TABLE_NAME=:t AND COLUMN_NAME=:c
        ");
        $st->execute([':t'=>$table, ':c'=>$col]);
        return ((int)$st->fetchColumn() > 0);
    }

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

        $db = Database::getInstance();
        $db->query("SELECT 1 FROM email_queue LIMIT 1");

        $conferenceId = (int)($_POST['conference_id'] ?? 0);
        $roundNo = (int)($_POST['round_no'] ?? 1);

        $hasRound = $this->colExists('submission_decisions', 'round_no');

        $sql = "
          SELECT s.id, s.submission_no, s.title, s.title_ar, s.author_id,
                 u.email AS author_email, u.first_name, u.last_name, u.preferred_lang,
                 c.title_en AS conf_en, c.title_ar AS conf_ar,
                 d.decision, d.chair_note
          FROM submissions s
          INNER JOIN users u ON u.id=s.author_id
          INNER JOIN conferences c ON c.id=s.conference_id
          INNER JOIN submission_decisions d ON d.submission_id=s.id
          WHERE s.conference_id=:cid
        ";
        $params = [':cid'=>$conferenceId];
        if ($hasRound) { $sql .= " AND d.round_no=:rn"; $params[':rn']=$roundNo; }

        $st = $db->prepare($sql);
        $st->execute($params);
        $list = $st->fetchAll();

        $queued = 0;
        foreach ($list as $r) {
            $to = (string)($r['author_email'] ?? '');
            if ($to==='') continue;

            $lang = (string)($r['preferred_lang'] ?? 'en');
            $confTitle = ($lang==='ar') ? (string)($r['conf_ar'] ?? '') : (string)($r['conf_en'] ?? '');
            $subNo = (string)($r['submission_no'] ?? ('#'.$r['id']));
            $paperTitle = ($lang==='ar' && !empty($r['title_ar'])) ? (string)$r['title_ar'] : (string)($r['title'] ?? '');
            $decision = (string)($r['decision'] ?? '');
            $note = (string)($r['chair_note'] ?? '');

            $subject = ($lang==='ar') ? "قرار التحكيم - {$subNo}" : "Review Decision - {$subNo}";
            $text = ($lang==='ar')
                ? "عزيزي/عزيزتي،\n\nتم إصدار قرار التحكيم ضمن {$confTitle}.\nرقم التقديم: {$subNo}\nالعنوان: {$paperTitle}\nالقرار: {$decision}\n\nملاحظة:\n{$note}\n"
                : "Dear Author,\n\nA decision has been issued in {$confTitle}.\nSubmission: {$subNo}\nTitle: {$paperTitle}\nDecision: {$decision}\n\nChair note:\n{$note}\n";
            $html = nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8'));

            $db->prepare("
              INSERT INTO email_queue (to_email,to_name,template_key,subject_line,body_html,body_text,status,created_at)
              VALUES (:to,:name,'decision',:subj,:html,:txt,'queued',NOW())
            ")->execute([
                ':to'=>$to,
                ':name'=>trim((string)($r['first_name'] ?? '').' '.(string)($r['last_name'] ?? '')) ?: null,
                ':subj'=>$subject,
                ':html'=>$html,
                ':txt'=>$text
            ]);

            $queued++;
        }

        flash('success', "Queued decision emails: {$queued}");
        redirect('admin/decision-board?conference_id='.$conferenceId.'&round_no='.$roundNo);
    }
}
