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

try {
    require_once('../files/guardiankey.php');
    require_once('db_connection.php');
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('MÉTODO NO PERMITIDO');
    }

    $clientId = $_POST['client_id'] ?? null;
    $routeId = $_POST['route_id'] ?? null;
    $frequency = $_POST['frequency'] ?? 'Semanal';
    $visitWeek = $_POST['visit_week'] ?? null;
    $startWeek = $_POST['start_week'] ?? null;

    if (empty($clientId)) {
        throw new Exception('ID DE CLIENTE NO PROPORCIONADO');
    }

    $finalRouteId = ($routeId == '0' || $routeId == 0) ? NULL : $routeId;

    $stmt = $pdo->prepare("
        UPDATE clients
        SET route_id = ?, frequency = ?, visit_week = ?, start_week = ?
        WHERE id = ?
    ");

    $stmt->execute([
        $finalRouteId,
        $frequency,
        in_array($frequency, ['Mensual', 'Unica']) ? $visitWeek : NULL,
        $frequency === 'Quincenal' ? $startWeek : NULL,
        $clientId
    ]);

    $response = ['status' => 'success', 'message' => 'GUARDADO'];

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

ob_end_clean();
echo json_encode($response);
exit;
?>