<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD */
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* RBAC */
require_permission($user, 'rsps', 'view', $pdo);

/* LIMIT CAP */
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 500;
if ($limit <= 0 || $limit > 1000) {
    $limit = 500;
}

/* WHERE BUILDER */
$where = [];
$params = [];

/* Tenant Isolation */
if (!empty($user['rsp_id'])) {
    $where[] = "r.id = ?";
    $params[] = (int)$user['rsp_id'];
}

$where_sql = '';
if ($where) {
    $where_sql = 'WHERE ' . implode(' AND ', $where);
}

/* QUERY */
$sql = "
SELECT 
    r.id,
    r.name,
    r.status,
    COUNT(c.id) AS companies
FROM rsps r
LEFT JOIN companies c ON c.rsp_id = r.id
{$where_sql}
GROUP BY r.id, r.name, r.status
ORDER BY r.created_at DESC
LIMIT ?
";

$params[] = $limit;

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$rsps = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* RESPONSE */
json_response(true, 'RSP list fetched securely.', [
    'count' => count($rsps),
    'rsps'  => $rsps
]);