<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AdminReviewRoundsController extends Controller
{
    public function index(): void
    {
        $orgId = (int) current_org_id();
        require_permission('admin.access');
        $db = Database::getInstance();

        $confs = $db->query("SELECT id,title_en,title_ar FROM conferences WHERE (is_active=1 OR is_active IS NULL) AND org_id=".(int)$orgId."  ORDER BY id DESC")->fetchAll();
        $conferenceId = (int)($_GET['conference_id'] ?? ($confs[0]['id'] ?? 0));

        $rows = [];
        if ($conferenceId > 0) {
            $st = $db->prepare("SELECT * FROM review_rounds WHERE conference_id=:cid ORDER BY round_no ASC");
            $st->execute([':cid'=>$conferenceId, ':org_id' => $orgId]);
            $rows = $st->fetchAll();
        }

        $this->view('admin/review_rounds/index', [
            'conferences'=>$confs,
            'conference_id'=>$conferenceId,
            'rows'=>$rows,
        ]);
    }

    public function save(): void
    {
        require_permission('admin.access');
        if (!$this->isPost()) redirect('admin/review-rounds');

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

        $conferenceId = (int)($_POST['conference_id'] ?? 0);
        $roundNo = (int)($_POST['round_no'] ?? 1);
        $titleEn = trim((string)($_POST['title_en'] ?? ''));
        $titleAr = trim((string)($_POST['title_ar'] ?? ''));
        $insEn = trim((string)($_POST['instructions_en'] ?? ''));
        $insAr = trim((string)($_POST['instructions_ar'] ?? ''));
        $dueDays = (int)($_POST['default_due_days'] ?? 14);
        $active = isset($_POST['is_active']) ? 1 : 0;

        if ($conferenceId<=0 || $roundNo<=0) {
            flash('danger', trans('required_fields'));
            redirect('admin/review-rounds');
        }

        $st = $db->prepare("
            INSERT INTO review_rounds (conference_id, round_no, title_en, title_ar, instructions_en, instructions_ar, default_due_days, is_active)
            VALUES (:cid,:rn,:te,:ta,:ie,:ia,:dd,:ac)
            ON DUPLICATE KEY UPDATE title_en=VALUES(title_en), title_ar=VALUES(title_ar),
              instructions_en=VALUES(instructions_en), instructions_ar=VALUES(instructions_ar),
              default_due_days=VALUES(default_due_days), is_active=VALUES(is_active)
        ");
        $st->execute([
            ':cid'=>$conferenceId, ':rn'=>$roundNo,
            ':te'=>$titleEn?:null, ':ta'=>$titleAr?:null,
            ':ie'=>$insEn?:null, ':ia'=>$insAr?:null,
            ':dd'=>$dueDays, ':ac'=>$active
        , ':org_id' => $orgId]);

        flash('success', trans('save'));
        redirect('admin/review-rounds?conference_id='.$conferenceId);
    }
}
