<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'clients' => [], 'message' => 'ERROR DESCONOCIDO'];

try {
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    $service_id = isset($_GET['service_id']) ? filter_var($_GET['service_id'], FILTER_VALIDATE_INT) : null;

    if ($service_id === false || is_null($service_id)) {
        throw new Exception('ID SERVICIO INVALIDO');
    }

    $stmt = $pdo->prepare("
        SELECT c.id, c.first_name, c.last_name
        FROM clients c
        JOIN client_services cs ON c.id = cs.client_id
        WHERE cs.service_id = :service_id
        ORDER BY c.first_name, c.last_name
    ");
    $stmt->bindParam(':service_id', $service_id, PDO::PARAM_INT);
    $stmt->execute();
    
    $clients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $response['success'] = true;
    $response['clients'] = $clients;
    // Se omite mensaje UX de éxito

} catch (PDOException $e) {
    error_log("Error PDO en service-clients-read.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    $response['message'] = strtoupper($e->getMessage());
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>