<?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 AdminDecisionBoardEmailController extends Controller
{
    public function sendDecisionEmail(): void
    {
        require_permission('admin.access');
        if (!$this->isPost()) redirect('admin/decision-board');

        csrf_check();
        $db = Database::getInstance();

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

        $st = $db->prepare("
          SELECT s.*, u.email AS author_email, u.first_name, u.last_name,
                 c.title_en AS conf_en, c.title_ar AS conf_ar,
                 d.decision, d.chair_note
          FROM submissions s
          LEFT JOIN users u ON u.id = s.author_id
          LEFT JOIN conferences c ON c.id = s.conference_id
          LEFT JOIN submission_decisions d ON d.submission_id=s.id AND d.round_no=:rn
          WHERE s.id=:sid LIMIT 1
        ");
        $st->execute([':sid'=>$submissionId, ':rn'=>$roundNo]);
        $row = $st->fetch();
        if (!$row) { flash('danger','Submission not found'); redirect('admin/decision-board?conference_id='.$conferenceId.'&round_no='.$roundNo); }

        $to = (string)($row['author_email'] ?? '');
        if ($to === '') { flash('danger','Author email missing'); redirect('admin/decision-board?conference_id='.$conferenceId.'&round_no='.$roundNo); }

        $decision = (string)($row['decision'] ?? '');
        if ($decision === '') { flash('danger','Decision not set'); redirect('admin/decision-board?conference_id='.$conferenceId.'&round_no='.$roundNo); }

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

        $subject = ($lang === 'ar')
          ? "قرار التحكيم - {$subNo}"
          : "Review Decision - {$subNo}";

        $body = ($lang === 'ar')
          ? "عزيزي/عزيزتي،\n\nتم إصدار قرار التحكيم لبحثكم ضمن {$confTitle}.\nرقم التقديم: {$subNo}\nعنوان البحث: {$paperTitle}\nالقرار: {$decision}\n\nملاحظة اللجنة:\n{$note}\n\nمع التحية."
          : "Dear Author,\n\nA review decision has been issued for your submission in {$confTitle}.\nSubmission: {$subNo}\nTitle: {$paperTitle}\nDecision: {$decision}\n\nChair note:\n{$note}\n\nRegards.";

        // 1) In-app notification
        try {
            $db->prepare("INSERT INTO notifications (user_id, message, type, is_read, created_at)
                          VALUES (:uid,:msg,'decision_email',0,NOW())")
               ->execute([':uid'=>(int)$row['author_id'], ':msg'=>$subject]);
        } catch (\Throwable $e) {}

        // 2) Email queue if exists
        try {
            $db->query("SELECT 1 FROM email_queue LIMIT 1");
            $db->prepare("INSERT INTO email_queue (recipient_email, recipient_name, subject, body, send_status, created_at)
                          VALUES (:to,:name,:subj,:body,'pending',NOW())")
               ->execute([
                   ':to'=>$to,
                   ':name'=>trim((string)($row['first_name'] ?? '').' '.(string)($row['last_name'] ?? '')),
                   ':subj'=>$subject,
                   ':body'=>$body
               ]);
            flash('success','Queued email');
        } catch (\Throwable $e) {
            // If no queue table, still succeed without crashing
            flash('success','Notification saved (email queue not available)');
        }

        redirect('admin/decision-board?conference_id='.$conferenceId.'&round_no='.$roundNo);
    }
}
