<?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 AdminReviewerAssignmentsController extends Controller
{
    private function cid($db): int
{
    $orgId = (int) current_org_id();

    $cid = function_exists('default_conference_id')
        ? (int) default_conference_id()
        : 0;

    if ($cid > 0) {
        return $cid;
    }

    return (int)(
        $db->query("
            SELECT id
            FROM conferences
            WHERE
                (
                    is_active = 1
                    OR is_active IS NULL
                )
                AND org_id = " . (int)$orgId . "
            ORDER BY id DESC
            LIMIT 1
        ")->fetchColumn()
        ?: 0
    );
}
    public function index(): void
    {
        require_admin_area();
        $orgId = (int) current_org_id();

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

        $subs=$db->prepare("SELECT id,title_en,title_ar,status FROM submissions WHERE conference_id=:c AND conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId.")  ORDER BY id DESC LIMIT 300");
        $subs->execute([':c'=>$cid]);
        $submissions=$subs->fetchAll()?:[];

        //$revs=$db->query("SELECT id,email FROM users WHERE role_id=4 AND is_active=1 ORDER BY id DESC LIMIT 1000")->fetchAll()?:[];

$revsStmt = $db->prepare("
    SELECT DISTINCT
        u.id,
        u.email,
        u.first_name,
        u.last_name
    FROM conference_user_roles cur

    INNER JOIN users u
        ON u.id = cur.user_id

    WHERE cur.role_code = 'reviewer'

    AND cur.conference_id = :c

    AND (
        cur.org_id = :o
        OR cur.org_id IS NULL
    )

    AND u.is_active = 1

    ORDER BY
        u.first_name ASC,
        u.last_name ASC,
        u.id DESC

    LIMIT 1000
");

$revsStmt->execute([
    ':c' => $cid,
    ':o' => $orgId
]);

$revs = $revsStmt->fetchAll() ?: [];

        $ra=$db->prepare("
          SELECT ra.*, u.email, s.title_en, s.title_ar
          FROM review_assignments ra
          JOIN users u ON u.id=ra.reviewer_id
          JOIN submissions s ON s.id=ra.submission_id
          WHERE s.conference_id=:c
          AND submission_id IN (SELECT id FROM submissions WHERE conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId."))  ORDER BY ra.id DESC
        ");
        $ra->execute([':c'=>$cid]);
        $assignments=$ra->fetchAll()?:[];

        $this->view('admin/reviewer_assignments/index',[
          'submissions'=>$submissions,'reviewers'=>$revs,'assignments'=>$assignments
        ]);
    }

    public function assign(): void
    {
        require_admin_area();
        csrf_check();

        $db=Database::getInstance();
        $sid=(int)($_POST['submission_id']??0);
        $rid=(int)($_POST['reviewer_id']??0);
        $round=(int)($_POST['round_no']??1); if($round<1)$round=1;

        $db->prepare("INSERT IGNORE INTO review_assignments(submission_id,reviewer_id,round_no,status) VALUES(:s,:r,:n,'pending')")
           ->execute([':s'=>$sid,':r'=>$rid,':n'=>$round]);

        header('Location: '.base_path('admin/review-assignments')); exit;
    }
}
