<?php
ob_start();
require_once '../auth.php';
checkLogin();
require_once '../config.php';
ob_clean();
header('Content-Type: application/json; charset=utf-8');

// Verify Admin Role
if (($_SESSION['role'] ?? '') !== 'admin') {
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    $pdo = getDBConnection();

    // Determine action
    $action = $input['action'] ?? null;

    // Legacy support for direct user status update (if no 'action' provided but 'userId' exists)
    if (!$action && isset($input['userId']) && isset($input['status'])) {
        $action = 'update_status';
    }

    if (!$action) {
        throw new Exception("Acción no especificada");
    }

    switch ($action) {
        case 'update_status':
            $userId = $input['userId'] ?? null;
            $status = $input['status'] ?? null;

            if (!$userId || !$status) {
                throw new Exception("Datos incompletos");
            }

            if (!in_array($status, ['active', 'rejected'])) {
                throw new Exception("Estado inválido");
            }

            $stmt = $pdo->prepare("UPDATE users SET status = :status WHERE id = :id AND role != 'admin'");
            $stmt->execute([':status' => $status, ':id' => $userId]);
            break;

        case 'add_sensor_config':
            $shipId = $input['ship_id'] ?? '';
            if (!$shipId)
                throw new Exception("Falta ID de buque");

            $pdo->beginTransaction();
            try {
                // Determine next sensor ID
                $stmt = $pdo->prepare("SELECT MAX(sensor_id) as max_id FROM sensor_positions WHERE buque_id = :sid");
                $stmt->execute([':sid' => $shipId]);
                $row = $stmt->fetch(PDO::FETCH_ASSOC);
                $nextId = ($row['max_id'] ?? 0) + 1;

                // Insert into sensor_positions
                $stmtPos = $pdo->prepare("INSERT INTO sensor_positions (sensor_id, buque_id, label, x, y_top, y_side) VALUES (:sid, :bid, :label, '50%', '23%', '76%')");
                $stmtPos->execute([
                    ':sid' => $nextId,
                    ':bid' => $shipId,
                    ':label' => "SENSOR #$nextId"
                ]);

                // Also insert default config into sensor_temperature_config so it appears immediately
                $stmtConf = $pdo->prepare("INSERT INTO sensor_temperature_config (buque_id, sensor_id, sensor_label, max_temp, min_temp) VALUES (:bid, :sid, :label, 27.00, -40.00)");
                $stmtConf->execute([
                    ':bid' => $shipId,
                    ':sid' => $nextId,
                    ':label' => "SENSOR #$nextId"
                ]);

                $pdo->commit();
                echo json_encode(['success' => true, 'new_sensor_id' => $nextId]);
                exit;
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'delete_sensor_config':
            $shipId = $input['ship_id'] ?? '';
            $sensorId = $input['sensor_id'] ?? null;
            if (!$shipId || $sensorId === null)
                throw new Exception("Faltan datos");

            $pdo->beginTransaction();
            try {
                // Delete from all related tables
                $stmt1 = $pdo->prepare("DELETE FROM sensor_temperature_config WHERE buque_id = :bid AND sensor_id = :sid");
                $stmt1->execute([':bid' => $shipId, ':sid' => $sensorId]);

                $stmt2 = $pdo->prepare("DELETE FROM sensor_positions WHERE buque_id = :bid AND sensor_id = :sid");
                $stmt2->execute([':bid' => $shipId, ':sid' => $sensorId]);

                error_log("Sensor borrado exitosamente: Buque $shipId, Sensor $sensorId. Afectados: stc=" . $stmt1->rowCount() . ", sp=" . $stmt2->rowCount());

                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'create_ship':
            $shipId = $input['ship_id'] ?? '';
            $name = $input['name'] ?? '';
            $type = $input['type'] ?? 'buque';
            $icon = $input['icon'] ?? '🚢';
            $sensorsCount = isset($input['sensors']) ? (int) $input['sensors'] : 16;

            if (!$shipId || !$name)
                throw new Exception("Datos incompletos");

            $pdo->beginTransaction();
            try {
                $stmt = $pdo->prepare("INSERT INTO ships (ship_id, name, type, icon) VALUES (:id, :name, :type, :icon)");
                $stmt->execute([':id' => $shipId, ':name' => $name, ':type' => $type, ':icon' => $icon]);

                // Crear los sensores por defecto
                $sensorsCount = max(1, min(16, $sensorsCount)); // Limitar entre 1 y 16
                $stmtSensor = $pdo->prepare("INSERT INTO sensor_positions (sensor_id, buque_id, label, x, y_top, y_side) VALUES (:sid, :bid, :label, '50%', '23%', '76%')");

                for ($i = 1; $i <= $sensorsCount; $i++) {
                    $label = "SENSOR #$i";
                    $stmtSensor->execute([
                        ':sid' => $i,
                        ':bid' => $shipId,
                        ':label' => $label
                    ]);

                    // Also add to temperature config for immediate consistency
                    $pdo->prepare("INSERT INTO sensor_temperature_config (buque_id, sensor_id, sensor_label, max_temp, min_temp) 
                                 VALUES (:bid, :sid, :label, 27.00, -40.00)")
                        ->execute([':bid' => $shipId, ':sid' => $i, ':label' => $label]);
                }

                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'create_ship_admin':
            $shipId = trim($input['ship_id'] ?? '');
            $user = trim($input['username'] ?? '');
            $pass = $input['password'] ?? '';

            // New company fields
            $legalName = trim($input['legal_name'] ?? '');
            $address = trim($input['address'] ?? '');
            $responsible = trim($input['responsible_name'] ?? '');
            $cuit = trim($input['cuit'] ?? '');

            if (!$shipId || !$user || !$pass)
                throw new Exception("Datos incompletos");

            // Check if user exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = :user");
            $stmt->execute([':user' => $user]);
            if ($stmt->fetch())
                throw new Exception("El usuario ya existe");

            $pdo->beginTransaction();
            try {
                $hash = password_hash($pass, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (username, password, role, status, legal_name, address, responsible_name, cuit) 
                                     VALUES (:user, :pass, 'sub-adm', 'active', :legal, :address, :responsible, :cuit)");
                $stmt->execute([
                    ':user' => $user,
                    ':pass' => $hash,
                    ':legal' => $legalName,
                    ':address' => $address,
                    ':responsible' => $responsible,
                    ':cuit' => $cuit
                ]);

                $userId = $pdo->lastInsertId();

                // Map user to ship in user_ships table
                $stmt = $pdo->prepare("INSERT INTO user_ships (user_id, ship_id) VALUES (:uid, :sid)");
                $stmt->execute([':uid' => $userId, ':sid' => $shipId]);

                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'add_ship_to_admin':
            $userId = $_SESSION['user_id'];
            $shipId = $input['ship_id'] ?? '';
            $name = $input['name'] ?? '';
            $type = $input['type'] ?? 'buque';
            $icon = $input['icon'] ?? '🚢';

            if (!$shipId || !$name)
                throw new Exception("Datos incompletos");

            $pdo->beginTransaction();
            try {
                // 1. Create the ship
                $stmt = $pdo->prepare("INSERT INTO ships (ship_id, name, type, icon) VALUES (:id, :name, :type, :icon)");
                $stmt->execute([':id' => $shipId, ':name' => $name, ':type' => $type, ':icon' => $icon]);

                // 2. Link to current user
                $stmt = $pdo->prepare("INSERT INTO user_ships (user_id, ship_id) VALUES (:uid, :sid)");
                $stmt->execute([':uid' => $userId, ':sid' => $shipId]);

                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'assign_ship_user':
            $userId = $input['user_id'] ?? '';
            $shipId = $input['ship_id'] ?? '';

            if (!$userId || !$shipId)
                throw new Exception("Faltan datos");

            // Verify ship exists
            $stmt = $pdo->prepare("SELECT ship_id FROM ships WHERE ship_id = :id");
            $stmt->execute([':id' => $shipId]);
            if (!$stmt->fetch())
                throw new Exception("Buque no existe");

            // Update user_ships mapping
            $stmt = $pdo->prepare("INSERT IGNORE INTO user_ships (user_id, ship_id) VALUES (:uid, :sid)");
            $stmt->execute([':uid' => $userId, ':sid' => $shipId]);
            break;

        case 'sync_user_ships':
            $userId = $input['user_id'] ?? '';
            $shipIds = $input['ship_ids'] ?? [];

            if (!$userId)
                throw new Exception("Falta ID de usuario");

            $pdo->beginTransaction();
            try {
                // 1. Remove all current assignments
                $stmt = $pdo->prepare("DELETE FROM user_ships WHERE user_id = :uid");
                $stmt->execute([':uid' => $userId]);

                // 2. Add new assignments
                if (!empty($shipIds)) {
                    $stmt = $pdo->prepare("INSERT INTO user_ships (user_id, ship_id) VALUES (:uid, :sid)");
                    foreach ($shipIds as $sid) {
                        $stmt->execute([':uid' => $userId, ':sid' => $sid]);
                    }

                    // 3. Update legacy ship_id in users to the first assigned one
                    $stmt = $pdo->prepare("UPDATE users SET ship_id = :sid WHERE id = :uid");
                    $stmt->execute([':uid' => $userId, ':sid' => $shipIds[0]]);
                } else {
                    // Update legacy ship_id to NULL if no ships
                    $stmt = $pdo->prepare("UPDATE users SET ship_id = NULL WHERE id = :uid");
                    $stmt->execute([':uid' => $userId]);
                }

                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'change_user_ship':
            $userId = $input['user_id'] ?? '';
            $shipId = $input['ship_id'] ?? '';

            if (!$userId || !$shipId)
                throw new Exception("Faltan datos");

            // Verify ship exists
            $stmt = $pdo->prepare("SELECT ship_id FROM ships WHERE ship_id = :id");
            $stmt->execute([':id' => $shipId]);
            if (!$stmt->fetch())
                throw new Exception("Buque no existe");

            // Update user's ship mapping (delete old, add new for 'user' role)
            $pdo->beginTransaction();
            try {
                $stmt = $pdo->prepare("DELETE FROM user_ships WHERE user_id = :uid");
                $stmt->execute([':uid' => $userId]);

                $stmt = $pdo->prepare("INSERT INTO user_ships (user_id, ship_id) VALUES (:uid, :sid)");
                $stmt->execute([':uid' => $userId, ':sid' => $shipId]);

                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'delete_ship':
            // Solo el admin staff puede eliminar buques
            if (($_SESSION['username'] ?? '') !== 'admin') {
                throw new Exception("Solo el administrador principal puede eliminar buques");
            }

            $shipId = $input['ship_id'] ?? '';
            $password = $input['password'] ?? '';

            if (!$shipId || !$password)
                throw new Exception("Datos incompletos");

            // Verificar contraseña del admin
            $stmt = $pdo->prepare("SELECT password FROM users WHERE username = 'admin' AND role = 'admin'");
            $stmt->execute();
            $admin = $stmt->fetch();

            if (!$admin || !password_verify($password, $admin['password'])) {
                throw new Exception("Contraseña incorrecta");
            }

            // Verificar que el buque existe
            $stmt = $pdo->prepare("SELECT ship_id FROM ships WHERE ship_id = :id");
            $stmt->execute([':id' => $shipId]);
            if (!$stmt->fetch())
                throw new Exception("Buque no existe");

            $pdo->beginTransaction();
            try {
                // Find users that ONLY belong to this ship to potentially cleanup or handle logic
                $stmt = $pdo->prepare("SELECT user_id FROM user_ships WHERE ship_id = :ship");
                $stmt->execute([':ship' => $shipId]);
                $affectedUsers = $stmt->fetchAll(PDO::FETCH_COLUMN);

                // Remove mappings in user_ships for admins/assigned users
                $stmt = $pdo->prepare("DELETE FROM user_ships WHERE ship_id = :ship");
                $stmt->execute([':ship' => $shipId]);

                // Clear ship_id for viewers and admins
                $stmt = $pdo->prepare("UPDATE users SET ship_id = NULL WHERE ship_id = :ship");
                $stmt->execute([':ship' => $shipId]);

                // For users that were affected, we should ensure their primary ship_id is updated if they have other ships
                if (!empty($affectedUsers)) {
                    foreach ($affectedUsers as $uid) {
                        // Check if they still have other ships
                        $stmt = $pdo->prepare("SELECT ship_id FROM user_ships WHERE user_id = :uid LIMIT 1");
                        $stmt->execute([':uid' => $uid]);
                        $otherShip = $stmt->fetchColumn();

                        // If they have another ship, set it as primary. If not, set to NULL (already handled above but good for safety)
                        $newPrimary = $otherShip ? $otherShip : null;
                        $updateStmt = $pdo->prepare("UPDATE users SET ship_id = :sid WHERE id = :uid");
                        $updateStmt->execute([':sid' => $newPrimary, ':uid' => $uid]);
                    }
                }

                // Delete the ship
                $stmt = $pdo->prepare("DELETE FROM ships WHERE ship_id = :id");
                $stmt->execute([':id' => $shipId]);

                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'change_user_password':
            $userId = $input['user_id'] ?? '';
            $adminPassword = $input['admin_password'] ?? '';
            $newPassword = $input['new_password'] ?? '';

            if (!$userId || !$adminPassword || !$newPassword) {
                throw new Exception("Datos incompletos");
            }

            // Verificar contraseña del admin
            $stmt = $pdo->prepare("SELECT password FROM users WHERE username = 'admin' AND role = 'admin'");
            $stmt->execute();
            $admin = $stmt->fetch();

            if (!$admin || !password_verify($adminPassword, $admin['password'])) {
                throw new Exception("Contraseña de administrador incorrecta");
            }

            // Verificar que el usuario existe
            $stmt = $pdo->prepare("SELECT id FROM users WHERE id = :id");
            $stmt->execute([':id' => $userId]);
            if (!$stmt->fetch()) {
                throw new Exception("Usuario no encontrado");
            }

            // Cambiar contraseña del usuario
            $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = :password WHERE id = :id");
            $stmt->execute([':password' => $newHash, ':id' => $userId]);
            break;

        case 'delete_user_from_ship':
            $userId = $input['user_id'] ?? '';
            $password = $input['password'] ?? '';
            $shipId = $input['ship_id'] ?? '';

            if (!$userId || !$password || !$shipId) {
                throw new Exception("Datos incompletos");
            }

            // Verificar contraseña del admin
            $stmt = $pdo->prepare("SELECT password FROM users WHERE username = 'admin' AND role = 'admin'");
            $stmt->execute();
            $admin = $stmt->fetch();

            if (!$admin || !password_verify($password, $admin['password'])) {
                throw new Exception("Contraseña de administrador incorrecta");
            }

            // Eliminar relación con el buque
            $stmt = $pdo->prepare("DELETE FROM user_ships WHERE user_id = :uid AND ship_id = :sid");
            $stmt->execute([':uid' => $userId, ':sid' => $shipId]);

            // Fix the user's primary ship_id if the removed ship was their current primary ship
            $stmt = $pdo->prepare("SELECT ship_id FROM users WHERE id = :uid LIMIT 1");
            $stmt->execute([':uid' => $userId]);
            $currentPrimary = $stmt->fetchColumn();

            if ($currentPrimary === $shipId) {
                // Determine new primary ship if any
                $stmt = $pdo->prepare("SELECT ship_id FROM user_ships WHERE user_id = :uid LIMIT 1");
                $stmt->execute([':uid' => $userId]);
                $otherShip = $stmt->fetchColumn();

                $newPrimary = $otherShip ? $otherShip : null;
                $updateStmt = $pdo->prepare("UPDATE users SET ship_id = :sid WHERE id = :uid");
                $updateStmt->execute([':sid' => $newPrimary, ':uid' => $userId]);
            }
            break;

        case 'remove_admin_role':
            $userId = $input['user_id'] ?? '';
            $adminPassword = $input['admin_password'] ?? '';

            if (!$userId || !$adminPassword) {
                throw new Exception("Datos incompletos");
            }

            // Verificar contraseña del admin
            $stmt = $pdo->prepare("SELECT password FROM users WHERE username = 'admin' AND role = 'admin'");
            $stmt->execute();
            $admin = $stmt->fetch();

            if (!$admin || !password_verify($adminPassword, $admin['password'])) {
                throw new Exception("Contraseña de administrador incorrecta");
            }

            // Convertir el admin en usuario común
            $stmt = $pdo->prepare("UPDATE users SET role = 'user' WHERE id = :id");
            $stmt->execute([':id' => $userId]);

            error_log("Admin removido - Usuario ID: $userId convertido a usuario común");
            break;

        case 'update_ship':
            $oldId = $input['old_id'] ?? '';
            $newId = $input['new_id'] ?? '';
            $name = $input['name'] ?? '';
            $type = $input['type'] ?? 'buque';
            $icon = $input['icon'] ?? '🚢';

            error_log("Attempting update ship: $oldId -> $newId (Name: $name)");

            if (!$oldId || !$newId || !$name) {
                throw new Exception("Datos incompletos");
            }

            $pdo->beginTransaction();
            try {
                // If ID changed, we need to handle potential FK constraints
                if ($oldId !== $newId) {
                    // Check if new ID already exists
                    $stmtCheck = $pdo->prepare("SELECT ship_id FROM ships WHERE ship_id = :id");
                    $stmtCheck->execute([':id' => $newId]);
                    if ($stmtCheck->fetch()) {
                        throw new Exception("El nuevo ID ($newId) ya está en uso por otro buque");
                    }

                    // 1. Create the new ship entry copying current row data if needed, or just using input
                    $stmtNew = $pdo->prepare("INSERT INTO ships (ship_id, name, type, icon) VALUES (:new, :name, :type, :icon)");
                    $stmtNew->execute([':new' => $newId, ':name' => $name, ':type' => $type, ':icon' => $icon]);

                    // 2. Update child tables to point to the NEW ID
                    $pdo->prepare("UPDATE user_ships SET ship_id = :new WHERE ship_id = :old")->execute([':new' => $newId, ':old' => $oldId]);
                    $pdo->prepare("UPDATE sensor_temperature_config SET buque_id = :new WHERE buque_id = :old")->execute([':new' => $newId, ':old' => $oldId]);
                    $pdo->prepare("UPDATE mediciones SET buque_id = :new WHERE buque_id = :old")->execute([':new' => $newId, ':old' => $oldId]);
                    $pdo->prepare("UPDATE sensor_positions SET buque_id = :new WHERE buque_id = :old")->execute([':new' => $newId, ':old' => $oldId]);
                    $pdo->prepare("UPDATE users SET ship_id = :new WHERE ship_id = :old")->execute([':new' => $newId, ':old' => $oldId]);

                    // 3. Delete the OLD ship entry
                    $stmtDel = $pdo->prepare("DELETE FROM ships WHERE ship_id = :old");
                    $stmtDel->execute([':old' => $oldId]);

                    error_log("Ship ID changed successfully from $oldId to $newId");

                    // Force session refresh for current user if they are affected (since they are admin, they likely are)
                    $_SESSION['user_ships_updated'] = true;
                } else {
                    // Normal update (no ID change)
                    $stmt = $pdo->prepare("UPDATE ships SET name = :name, type = :type, icon = :icon WHERE ship_id = :old");
                    $stmt->execute([':name' => $name, ':type' => $type, ':icon' => $icon, ':old' => $oldId]);
                    error_log("Ship $oldId updated (metadata only)");
                }

                // SELF-HEALING: Ensure all 16 sensors exist for the current ship ID
                $finalId = ($oldId !== $newId) ? $newId : $oldId;

                for ($i = 1; $i <= 16; $i++) {
                    // Check if sensor exists in positions
                    $stmt = $pdo->prepare("SELECT id FROM sensor_positions WHERE buque_id = :bid AND sensor_id = :sid");
                    $stmt->execute([':bid' => $finalId, ':sid' => $i]);
                    if (!$stmt->fetch()) {
                        // Create missing position entry
                        $label = ($i == 16) ? "Extra" : "SENSOR #$i";
                        $stmtIns = $pdo->prepare("INSERT INTO sensor_positions (sensor_id, buque_id, label, x, y_top, y_side) VALUES (:sid, :bid, :label, '50%', '23%', '76%')");
                        $stmtIns->execute([':sid' => $i, ':bid' => $finalId, ':label' => $label]);
                    }

                    // Check if sensor exists in temp config
                    $stmt = $pdo->prepare("SELECT id FROM sensor_temperature_config WHERE buque_id = :bid AND sensor_id = :sid");
                    $stmt->execute([':bid' => $finalId, ':sid' => $i]);
                    if (!$stmt->fetch()) {
                        // Create missing config entry
                        $label = ($i == 16) ? "Extra" : "SENSOR #$i";
                        $stmtIns = $pdo->prepare("INSERT INTO sensor_temperature_config (buque_id, sensor_id, sensor_label, max_temp, min_temp) VALUES (:bid, :sid, :label, 27.00, -40.00)");
                        $stmtIns->execute([':bid' => $finalId, ':sid' => $i, ':label' => $label]);
                    }
                }

                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                error_log("Error in update_ship: " . $e->getMessage());
                throw $e;
            }
            break;

        case 'delete_user_completely':
            $userId = $input['user_id'] ?? '';
            $password = $input['password'] ?? '';

            if (!$userId || !$password) {
                throw new Exception("Datos incompletos");
            }

            // Verify admin password
            $stmt = $pdo->prepare("SELECT password FROM users WHERE username = 'admin' AND role = 'admin'");
            $stmt->execute();
            $admin = $stmt->fetch();

            if (!$admin || !password_verify($password, $admin['password'])) {
                throw new Exception("Contraseña de administrador incorrecta");
            }

            $pdo->beginTransaction();
            try {
                // Remove ship mappings
                $pdo->prepare("DELETE FROM user_ships WHERE user_id = :id")->execute([':id' => $userId]);
                // Delete user
                $pdo->prepare("DELETE FROM users WHERE id = :id AND role != 'admin'")->execute([':id' => $userId]);

                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        case 'search_users':
            $term = $input['search_term'] ?? '';
            if (strlen($term) < 2)
                throw new Exception("Término de búsqueda muy corto");

            $stmt = $pdo->prepare("SELECT id, username, role, ship_id FROM users WHERE username LIKE :term AND role != 'admin' LIMIT 10");
            $stmt->execute([':term' => "%$term%"]);
            echo json_encode(['success' => true, 'users' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
            exit;

        case 'assign_existing_user_as_admin':
            $userId = $input['user_id'] ?? '';
            $shipId = $input['ship_id'] ?? '';

            if (!$userId || !$shipId)
                throw new Exception("Datos incompletos");

            $pdo->beginTransaction();
            try {
                // 1. Ensure role is sub-adm
                $stmt = $pdo->prepare("UPDATE users SET role = 'sub-adm' WHERE id = :uid");
                $stmt->execute([':uid' => $userId]);

                // 2. Link to ship
                $stmt = $pdo->prepare("INSERT IGNORE INTO user_ships (user_id, ship_id) VALUES (:uid, :sid)");
                $stmt->execute([':uid' => $userId, ':sid' => $shipId]);

                // 3. Update legacy ship_id if it was null
                $stmt = $pdo->prepare("UPDATE users SET ship_id = :sid WHERE id = :uid AND ship_id IS NULL");
                $stmt->execute([':uid' => $userId, ':sid' => $shipId]);

                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            break;

        default:
            throw new Exception("Acción no válida");
    }

    echo json_encode(['success' => true]);

} catch (Exception $e) {
    // Catch duplicate entry error
    if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
        echo json_encode(['success' => false, 'message' => 'El buque o usuario ya existe']);
    } else {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
exit;
?>