<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AdminReviewAssignmentsSuggestController extends Controller
{
    public function index(): void
    {
        $orgId = (int) current_org_id();
        require_permission('admin.access');
        $db = Database::getInstance();

        $submissionId = (int)($_GET['submission_id'] ?? 0);
        $roundNo = (int)($_GET['round_no'] ?? 1);

        $st = $db->prepare("SELECT id, conference_id, submission_no, title, keywords, keywords_ar FROM submissions WHERE id=:id AND conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId.")  LIMIT 1");
        $st->execute([':id'=>$submissionId, ':org_id' => $orgId]);
        $sub = $st->fetch();
        if (!$sub) { http_response_code(404); exit('Not found'); }

        $kw = trim((string)($sub['keywords'] ?? ''));
        $kwAr = trim((string)($sub['keywords_ar'] ?? ''));
        $all = trim($kw . ' ' . $kwAr);

        // reviewers role_id=4 (adjust later if needed)
        $roleId = 4;

        // Score = count of matched tokens (simple and stable)
        $tokens = array_values(array_filter(preg_split('/[,\s;]+/u', mb_strtolower($all))));
        $tokens = array_slice(array_unique($tokens), 0, 12);

        $where = [];
        $params = [':rid'=>$roleId];
        $i=0;
        foreach ($tokens as $t) {
            $i++;
            $where[] = "(LOWER(COALESCE(rp.expertise_keywords,'')) LIKE :t$i)";
            $params[":t$i"] = '%'.$t.'%';
        }
        $cond = $where ? (" AND (" . implode(" OR ", $where) . ")") : "";

        $sql = "
          SELECT u.id, u.first_name, u.last_name, u.email,
                 COALESCE(rp.admin_rating,0) AS admin_rating,
                 COALESCE(rp.expertise_keywords,'') AS expertise_keywords
          FROM users u
          LEFT JOIN reviewer_profiles rp ON rp.user_id = u.id
          WHERE u.role_id = :rid AND u.is_active=1
          $cond
          ORDER BY COALESCE(rp.admin_rating,0) DESC, u.id DESC
          LIMIT 20
        ";
        $q = $db->prepare($sql);
        $q->execute($params);
        $rows = $q->fetchAll();

        // existing assignments in this round
        $as = $db->prepare("SELECT reviewer_id FROM review_assignments WHERE submission_id=:sid AND round_no=:rn AND submission_id IN (SELECT id FROM submissions WHERE conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId.")) ");
        $as->execute([':sid'=>$submissionId, ':rn'=>$roundNo]);
        $assigned = array_map('intval', $as->fetchAll(\PDO::FETCH_COLUMN));

        $this->view('admin/review_assignments/suggest', [
            'sub'=>$sub,
            'round_no'=>$roundNo,
            'rows'=>$rows,
            'assigned'=>$assigned
        ]);
    }
}
