<?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 AdminReviewMatrixController extends Controller
{
    public function index(): void
    {
        require_admin_or_chair();
        require_org_context();

        $db = Database::getInstance();
        $orgId = (int) current_org_id();

        // Best-effort: show assignments matrix per conference in org
        $st = $db->prepare("SELECT id,title_en,title_ar FROM conferences WHERE org_id=:o ORDER BY id DESC");
        $st->execute([':o'=>$orgId]);
        $confs = $st->fetchAll() ?: [];
        $confId = (int)($_GET['conference_id'] ?? ($confs[0]['id'] ?? 0));
        if($confId>0) require_conference_of_org($confId);

        // Pull submissions + assignments counts
        $st = $db->prepare("
          SELECT s.id, s.title_en, s.title_ar,
                 COUNT(ra.id) AS assignments_count
          FROM submissions s
          JOIN conferences c ON c.id=s.conference_id
          LEFT JOIN review_assignments ra ON ra.submission_id=s.id
          WHERE c.org_id=:o AND s.conference_id=:c
          GROUP BY s.id
          ORDER BY s.id DESC
          LIMIT 300
        ");
        $st->execute([':o'=>$orgId,':c'=>$confId]);
        $rows = $st->fetchAll() ?: [];

        $this->view('admin/review_matrix/index', [
          'confs'=>$confs,
          'confId'=>$confId,
          'rows'=>$rows
        ]);
    }
}
