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

try {
    session_start();
    require_once '../core/api.php'; 

    $userId = $_SESSION['user_id'] ?? null;
    $clientId = filter_var($_POST['client_id'] ?? null, FILTER_VALIDATE_INT);
    $serviceTime = filter_var($_POST['service_time'] ?? null, FILTER_VALIDATE_INT);

    if (empty($userId)) {
        throw new Exception('ERROR DE SESION');
    }

    if ($clientId === false || $serviceTime === false || $serviceTime < 0) {
        throw new Exception('DATOS DE SERVICIO INVALIDOS');
    }

    // Seguridad IDOR: Se actualiza solo si el cliente pertenece al user_id
    $stmt = $pdo->prepare("
        UPDATE clients 
        SET service_time = ? 
        WHERE id = ? AND user_id = ?
    ");
    $stmt->execute([$serviceTime, $clientId, $userId]);

    if ($stmt->rowCount() > 0) {
        $response = ['status' => 'success', 'message' => 'TIEMPO ACTUALIZADO'];
    } else {
        $response = ['status' => 'success', 'message' => 'SIN CAMBIOS'];
    }

} catch (PDOException $e) {
    error_log("Error PDO en routes-update-client-time.php: " . $e->getMessage());
    $response = ['status' => 'error', 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    $response = ['status' => 'error', 'message' => strtoupper($e->getMessage())];
}

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