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

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

        $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);

        $q = trim((string)($_GET['q'] ?? ''));
        $params = [':o'=>$orgId];
        $where = "WHERE c.org_id=:o";
        if($confId>0){ $where.=" AND s.conference_id=:c"; $params[':c']=$confId; }
        if($q!==''){
            $where.=" AND (s.title_en LIKE :q OR s.title_ar LIKE :q OR s.abstract_en LIKE :q OR s.abstract_ar LIKE :q)";
            $params[':q'] = '%'.$q.'%';
        }

        $sql = "
          SELECT s.*, c.title_en AS conf_title_en, c.title_ar AS conf_title_ar
          FROM submissions s
          JOIN conferences c ON c.id=s.conference_id
          $where
          ORDER BY s.id DESC
          LIMIT 400
        ";
        $st = $db->prepare($sql);
        $st->execute($params);
        $rows = $st->fetchAll() ?: [];

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

    // IMPORTANT: do NOT name this method "view" because Controller already has view($view,$data)
    public function show(): void
    {
        require_admin_or_chair();
        require_org_context();

        $db = Database::getInstance();
        $orgId=(int)current_org_id();
        $id=(int)($_GET['id']??0);

        $st=$db->prepare("
          SELECT s.*, c.title_en AS conf_title_en, c.title_ar AS conf_title_ar
          FROM submissions s
          JOIN conferences c ON c.id=s.conference_id
          WHERE s.id=:id AND c.org_id=:o
          LIMIT 1
        ");
        $st->execute([':id'=>$id, ':o'=>$orgId]);
        $row=$st->fetch() ?: null;
        if(!$row){ http_response_code(404); echo "Not found"; exit; }

        $st=$db->prepare("
          SELECT ra.*, u.email, u.first_name, u.last_name
          FROM review_assignments ra
          JOIN users u ON u.id=ra.reviewer_id
          WHERE ra.submission_id=:sid
          ORDER BY ra.id DESC
        ");
        $st->execute([':sid'=>$id]);
        $assignments=$st->fetchAll() ?: [];

        $this->view('admin/submissions_tenant/view', [
          'row'=>$row,'assignments'=>$assignments
        ]);
    }
}
