<?php
ob_start();

require_once __DIR__ . '/../core/api.php';
global $pdo;

ini_set('display_errors', 0); 
ini_set('log_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');

$response = ['status' => 'error', 'message' => 'ERROR POR DEFECTO'];

try {

    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;
    
    // NOTA: Se ha ajustado la lógica de NULL para los campos visit_week y start_week para mantener consistencia.
    $stmt = $pdo->prepare("
        UPDATE clients
        SET route_id = ?, frequency = ?, visit_week = ?, start_week = ?
        WHERE id = ?
    ");

    $stmt->execute([
        $finalRouteId,
        $frequency,
        // visit_week solo se guarda si la frecuencia es Semanal, Quincenal o Mensual
        in_array($frequency, ['Weekly', 'Biweekly', 'Monthly']) ? $visitWeek : NULL,
        // start_week solo se guarda si la frecuencia es Quincenal
        ($frequency === 'Biweekly') ? $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;