<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, '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);

    if (empty($userId) || empty($clientId)) {
        throw new Exception('DATOS FALTANTES');
    }

    $stmt = $pdo->prepare("INSERT IGNORE INTO route_workspace (user_id, client_id) VALUES (?, ?)");
    $stmt->execute([$userId, $clientId]);
    
    if ($stmt->rowCount() > 0) {
        $response = ['success' => true, 'message' => 'CLIENTE AGREGADO'];
    } else {
        $response = ['success' => true, 'message' => 'YA AGREGADO'];
    }

} catch (PDOException $e) {
    error_log("Error PDO en routes-workspace-create.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

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