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

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

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

$where[] = "c.type = 'sp'";

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

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

/* QUERY */
$sql = "
SELECT 
    c.id AS company_id,
    c.company_name,
    c.status,
    r.name AS rsp_name,
    sp.base_lat,
    sp.base_lng,
    sp.coverage_radius_km,
    sp.penalty_count
FROM companies c
JOIN rsps r ON r.id = c.rsp_id
LEFT JOIN service_profiles sp ON sp.company_id = c.id
{$where_sql}
ORDER BY c.company_name ASC
LIMIT ?
";

$params[] = $limit;

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

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

json_response(true, 'SP profiles fetched securely.', [
    'count' => count($profiles),
    'profiles' => $profiles
]);