<?php
declare(strict_types=1);

namespace App\Controllers;

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

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

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

final class AdminReviewAssignmentsCloneController extends Controller
{
    public function cloneRound(): void
    {
        require_permission('admin.access');
        if (!$this->isPost()) redirect('admin/review-assignments');
        csrf_check();

        $db = Database::getInstance();
        $conferenceId = (int)($_POST['conference_id'] ?? 0);
        $fromRound = (int)($_POST['from_round'] ?? 1);
        $toRound = (int)($_POST['to_round'] ?? 2);

        if ($conferenceId<=0 || $fromRound<=0 || $toRound<=0) {
            flash('danger', trans('required_fields'));
            redirect('admin/review-assignments?conference_id='.$conferenceId.'&round_no='.$fromRound);
        }

        // Ensure round exists
        $db->prepare("INSERT IGNORE INTO review_rounds (conference_id, round_no, title_en, title_ar, default_due_days, is_active)
                      VALUES (:cid,:rn, CONCAT('Round ',:rn), CONCAT('الجولة ',:rn), 10, 1)")
           ->execute([':cid'=>$conferenceId, ':rn'=>$toRound]);

        // Clone assignments (same submission+reviewer pairs)
        $st = $db->prepare("
          INSERT IGNORE INTO review_assignments (submission_id, reviewer_id, assigned_by, round_no, due_date, status)
          SELECT ra.submission_id, ra.reviewer_id, :by, :toRound, NULL, 'assigned'
          FROM review_assignments ra
          INNER JOIN submissions s ON s.id=ra.submission_id
          WHERE s.conference_id=:cid AND ra.round_no=:fromRound
         AND submission_id IN (SELECT id FROM submissions WHERE conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId.")) ");
        $st->execute([':by'=>(int)auth_id(), ':toRound'=>$toRound, ':cid'=>$conferenceId, ':fromRound'=>$fromRound]);

        flash('success', 'Cloned assignments');
        redirect('admin/review-assignments?conference_id='.$conferenceId.'&round_no='.$toRound);
    }
}
