<?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, 'companies', 'view', $pdo);

/* INPUT */
$rsp_filter = isset($_GET['rsp_id']) ? (int)$_GET['rsp_id'] : null;

/* BASE QUERY */
$sql = "
SELECT 
    c.id,
    c.company_name,
    c.type,
    c.status,
    c.rsp_id,
    r.name AS rsp_name
FROM companies c
JOIN rsps r ON r.id = c.rsp_id
";

$where = [];
$params = [];

/* TENANT ISOLATION */
if (!empty($user['rsp_id'])) {

    // RSP admin can only see their own companies
    $where[] = "c.rsp_id = ?";
    $params[] = (int)$user['rsp_id'];

} elseif ($rsp_filter) {

    // super_admin may filter
    $where[] = "c.rsp_id = ?";
    $params[] = $rsp_filter;
}

/* APPLY WHERE */
if (!empty($where)) {
    $sql .= " WHERE " . implode(' AND ', $where);
}

/* HARD LIMIT */
$sql .= " ORDER BY c.created_at DESC LIMIT 500";

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

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

/* RESPONSE */
json_response(true, 'Companies fetched.', [
    'count' => count($companies),
    'companies' => $companies
]);