<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/csrf.php";
require_once "../includes/rbac.php";

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

$userId = (int)($_SESSION["user"]["id"] ?? 0);
$roleId = (int)($_SESSION["user"]["role_id"] ?? 0);

if ($_SERVER["REQUEST_METHOD"] === "GET") {
    $agencyId = (int)($_GET["agency_id"] ?? 0);
    if ($agencyId <= 0) {
        echo json_encode(["success" => false, "error" => "invalid_agency"]);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT ar.*, u.email as company_email 
        FROM agency_ratings ar 
        JOIN users u ON ar.company_id = u.id 
        WHERE ar.agency_id = ?
        ORDER BY ar.created_at DESC
    ");
    $stmt->execute([$agencyId]);
    echo json_encode(["success" => true, "data" => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

if (!hasPermission("manage_users")) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "forbidden"]);
    exit;
}

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode(["success" => false, "error" => "method_not_allowed"]);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true) ?: [];
if (!requireCsrfFromPayload($data)) {
    http_response_code(419);
    echo json_encode(["success" => false, "error" => "csrf_failed"]);
    exit;
}

$agencyId = (int)($data["agency_id"] ?? 0);
$rating = (int)($data["rating"] ?? 0);
$comment = trim((string)($data["comment"] ?? ""));

if ($agencyId <= 0 || $rating < 1 || $rating > 5) {
    echo json_encode(["success" => false, "error" => "invalid_params"]);
    exit;
}

$stmt = $pdo->prepare("INSERT INTO agency_ratings (agency_id, company_id, rating, comment) VALUES (?, ?, ?, ?)");
$stmt->execute([$agencyId, $userId, $rating, $comment]);

echo json_encode(["success" => true]);
?>

