<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AdminReviewAssignmentsTenantController 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);

        // reviewers in org (org_users)
        $st=$db->prepare("
          SELECT u.id,u.email,u.first_name,u.last_name
          FROM org_users ou
          JOIN users u ON u.id=ou.user_id
          WHERE ou.org_id=:o AND ou.is_active=1 AND ou.role_code='reviewer'
          ORDER BY u.id DESC
        ");
        $st->execute([':o'=>$orgId]);
        $reviewers=$st->fetchAll()?:[];

        // submissions in conference
        $st=$db->prepare("
          SELECT s.id, s.title_en, s.title_ar, s.status
          FROM submissions s
          JOIN conferences c ON c.id=s.conference_id
          WHERE c.org_id=:o AND s.conference_id=:c
          ORDER BY s.id DESC
          LIMIT 400
        ");
        $st->execute([':o'=>$orgId,':c'=>$confId]);
        $subs=$st->fetchAll()?:[];

        // existing assignments (for this conf)
        $st=$db->prepare("
          SELECT ra.*, u.email
          FROM review_assignments ra
          JOIN submissions s ON s.id=ra.submission_id
          JOIN conferences c ON c.id=s.conference_id
          JOIN users u ON u.id=ra.reviewer_id
          WHERE c.org_id=:o AND s.conference_id=:c
          ORDER BY ra.id DESC
          LIMIT 600
        ");
        $st->execute([':o'=>$orgId,':c'=>$confId]);
        $rows=$st->fetchAll()?:[];

        $this->view('admin/review_assignments_tenant/index', compact('rows','confs','confId','subs','reviewers'));
    }

    public function assign(): void
    {
        require_admin_or_chair();
        require_org_context();
        if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); return; }

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

        $confId=(int)($_POST['conference_id']??0);
        $subId=(int)($_POST['submission_id']??0);
        $revId=(int)($_POST['reviewer_id']??0);
        $round=(int)($_POST['round_no']??1);

        require_conference_of_org($confId);

        // Ensure submission belongs to this org+conf
        $st=$db->prepare("
          SELECT s.id
          FROM submissions s JOIN conferences c ON c.id=s.conference_id
          WHERE s.id=:sid AND s.conference_id=:cid AND c.org_id=:o
          LIMIT 1
        ");
        $st->execute([':sid'=>$subId,':cid'=>$confId,':o'=>$orgId]);
        if(!(int)$st->fetchColumn()){
          http_response_code(400); echo "Invalid submission"; exit;
        }

        // Ensure reviewer is org member (reviewer)
        $st=$db->prepare("SELECT COUNT(*) FROM org_users WHERE org_id=:o AND user_id=:u AND role_code='reviewer' AND is_active=1");
        $st->execute([':o'=>$orgId,':u'=>$revId]);
        if((int)$st->fetchColumn()<=0){
          http_response_code(400); echo "Reviewer not in this org"; exit;
        }

        // Avoid duplicates
        $st=$db->prepare("SELECT COUNT(*) FROM review_assignments WHERE submission_id=:s AND reviewer_id=:r AND round_no=:n");
        $st->execute([':s'=>$subId,':r'=>$revId,':n'=>$round]);
        if((int)$st->fetchColumn()>0){
          if(function_exists('flash_set')) flash_set('warning','Already assigned');
          header('Location: '.base_path('admin/review-assignments?conference_id='.$confId)); exit;
        }

        $assignedBy=(int)(function_exists('auth_id')?auth_id():0);

        $db->prepare("
          INSERT INTO review_assignments(submission_id,reviewer_id,assigned_by,status,round_no)
          VALUES(:s,:r,:a,'assigned',:n)
        ")->execute([':s'=>$subId,':r'=>$revId,':a'=>$assignedBy?:null,':n'=>$round]);

        if(function_exists('flash_set')) flash_set('success','Assigned');
        header('Location: '.base_path('admin/review-assignments?conference_id='.$confId)); exit;
    }

    public function unassign(): void
    {
        require_admin_or_chair();
        require_org_context();

        $db=Database::getInstance();
        $orgId=(int)current_org_id();
        $id=(int)($_GET['id']??0);
        $confId=(int)($_GET['conference_id']??0);
        if($confId>0) require_conference_of_org($confId);

        if($id>0){
          // delete only if belongs to org (via join)
          $st=$db->prepare("
            DELETE ra FROM review_assignments ra
            JOIN submissions s ON s.id=ra.submission_id
            JOIN conferences c ON c.id=s.conference_id
            WHERE ra.id=:id AND c.org_id=:o
          ");
          $st->execute([':id'=>$id,':o'=>$orgId]);
        }

        header('Location: '.base_path('admin/review-assignments?conference_id='.$confId)); exit;
    }
}
