<?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 AdminReviewersController extends Controller
{
    private function tableExists($db, string $t): bool {
        $st=$db->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $st->execute([':t'=>$t, ':org_id' => $orgId]);
        return (int)$st->fetchColumn()>0;
    }
    private function cols($db, string $t): array {
        $st=$db->prepare("SELECT column_name FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t");
        $st->execute([':t'=>$t, ':org_id' => $orgId]);
        $rows=$st->fetchAll()?:[];
        return array_map(fn($r)=>(string)$r['column_name'], $rows);
    }

    public function index(): void
    {
        require_admin_area();
        $orgId = (int) current_org_id();

        // keep your existing index if exists
        $this->view('admin/reviewers/index', []);
    }

    public function rate(): void
    {
        require_admin_area();
        $db = Database::getInstance();

        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { http_response_code(405); echo "Method Not Allowed"; return; }

        $reviewerId = (int)($_POST['reviewer_id'] ?? $_POST['id'] ?? 0);
        $score = (int)($_POST['score'] ?? $_POST['rating'] ?? 0);
        $notes = trim((string)($_POST['notes'] ?? ''));

        if ($reviewerId <= 0) {
            if (function_exists('flash_set')) flash_set('danger', 'Missing reviewer_id');
            header('Location: ' . base_path('admin/reviewers'));
            exit;
        }
        if ($score < 1) $score = 1;
        if ($score > 5) $score = 5;

        // Ensure table exists
        if (!$this->tableExists($db,'reviewer_ratings')) {
            $db->exec("
              CREATE TABLE IF NOT EXISTS reviewer_ratings (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                reviewer_id BIGINT UNSIGNED NOT NULL,
                rated_by BIGINT UNSIGNED NULL,
                rating TINYINT NOT NULL DEFAULT 3,
                notes LONGTEXT NULL,
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY(id),
                KEY idx_reviewer (reviewer_id)
              ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
            ");
        }

        $cols = $this->cols($db,'reviewer_ratings');
        $ratedBy = function_exists('auth_id') ? (int)auth_id() : null;

        // Insert (no conference_id assumptions)
        $sqlCols=[]; $sqlVals=[]; $params=[];
        if (in_array('reviewer_id',$cols,true)) { $sqlCols[]='reviewer_id'; $sqlVals[]=':rid'; $params[':rid']=$reviewerId; }
        if (in_array('rated_by',$cols,true)) { $sqlCols[]='rated_by'; $sqlVals[]=':rb'; $params[':rb']=$ratedBy; }
        if (in_array('rating',$cols,true)) { $sqlCols[]='rating'; $sqlVals[]=':r'; $params[':r']=$score; }
        if (in_array('notes',$cols,true)) { $sqlCols[]='notes'; $sqlVals[]=':n'; $params[':n']=($notes!==''?$notes:null); }

        $sql="INSERT INTO reviewer_ratings (".implode(',',$sqlCols).") VALUES (".implode(',',$sqlVals).")";
        $db->prepare($sql)->execute($params);

        if (function_exists('flash_set')) flash_set('success','Reviewer rated');
        header('Location: ' . base_path('admin/reviewers'));
        exit;
    }
}
