<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

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

final class AdminReviewersStableController 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 latestAssignmentId($db, int $reviewerId): int
    {
        if(!$this->tableExists($db,'review_assignments')) return 0;
        $st = $db->prepare("SELECT id FROM review_assignments WHERE reviewer_id=:rid AND org_id = :org_id  ORDER BY id DESC LIMIT 1");
        $st->execute([':rid'=>$reviewerId, ':org_id' => $orgId]);
        return (int)($st->fetchColumn() ?: 0);
    }

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

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

        $reviewerId   = (int)($_POST['reviewer_id'] ?? $_POST['id'] ?? 0);
        $assignmentId = (int)($_POST['review_assignment_id'] ?? $_POST['assignment_id'] ?? 0);

        $ratingRaw = trim((string)($_POST['rating'] ?? $_POST['rating_score'] ?? $_POST['score'] ?? '3'));
        $notes     = trim((string)($_POST['notes'] ?? $_POST['rating_notes'] ?? $_POST['comment'] ?? ''));

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

        // FK requires real review_assignment_id -> derive if missing
        if ($assignmentId <= 0) {
            $assignmentId = $this->latestAssignmentId($db, $reviewerId);
        }

        // still missing -> no assignment => no rating possible
        if ($assignmentId <= 0) {
            if (function_exists('flash_set')) {
                flash_set('danger', 'No review assignment found for this reviewer. Please rate via Review Assignments.');
            }
            header('Location: ' . base_path('admin/reviewers'));
            exit;
        }

        $rating = (float)$ratingRaw;
        if ($rating < 0.0) $rating = 0.0;
        if ($rating > 5.0) $rating = 5.0;

        $ratedBy = function_exists('auth_id') ? (int)auth_id() : 0;
        if ($ratedBy <= 0) $ratedBy = 1;

        // Upsert by UNIQUE review_assignment_id
        $sql = "
          INSERT INTO reviewer_ratings
            (review_assignment_id, reviewer_id, rated_by, rating_score, rating_notes)
          VALUES
            (:raid, :rid, :rb, :rs, :rn)
          ON DUPLICATE KEY UPDATE
            reviewer_id=VALUES(reviewer_id),
            rated_by=VALUES(rated_by),
            rating_score=VALUES(rating_score),
            rating_notes=VALUES(rating_notes),
            updated_at=CURRENT_TIMESTAMP
        ";

        $db->prepare($sql)->execute([
          ':raid' => $assignmentId,
          ':rid'  => $reviewerId,
          ':rb'   => $ratedBy,
          ':rs'   => number_format($rating, 1, '.', ''),
          ':rn'   => ($notes !== '' ? $notes : null),
        ]);

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