<?php
ob_start();
require_once '../auth.php';
require_once '../config.php';

checkApiLogin();
header('Content-Type: application/json; charset=utf-8');

// Helper to check permission
function checkPermission($shipId)
{
    // hasShipAccess already checks $_SESSION['assigned_ships'] via auth.php update
    if (!hasShipAccess($shipId) || !canManageUsers()) {
        echo json_encode(['success' => false, 'message' => 'No autorizado']);
        exit;
    }
}

try {
    $pdo = getDBConnection();
    $method = $_SERVER['REQUEST_METHOD'];

    if ($method === 'GET') {
        // List users for a ship
        $shipId = $_GET['ship_id'] ?? '';
        if (!$shipId)
            throw new Exception("Falta ID de buque");

        checkPermission($shipId);

        // Obtener todos los usuarios del buque (incluyendo sub-adm y users) con información de creador
        $stmt = $pdo->prepare("SELECT u.id, u.username, u.role, u.created_at, u.status, u.created_by, 
                              creator.username as created_by_username 
                              FROM users u 
                              JOIN user_ships us ON u.id = us.user_id
                              LEFT JOIN users creator ON u.created_by = creator.id 
                              WHERE us.ship_id = :ship AND u.role != 'admin' 
                              ORDER BY u.role DESC, u.username ASC");
        $stmt->execute([':ship' => $shipId]);
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode(['success' => true, 'users' => $users]);
    } elseif ($method === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        $action = $input['action'] ?? '';

        if ($action === 'create') {
            $shipId = $input['ship_id'] ?? '';
            $user = $input['username'] ?? '';
            $pass = $input['password'] ?? '';

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

            checkPermission($shipId);

            // Validation
            if (strlen($user) < 3)
                throw new Exception("Usuario muy corto");
            if (strlen($pass) < 4)
                throw new Exception("Contraseña muy corta");

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

            // Obtener el ID del usuario actual (sub-adm)
            $currentUserId = $_SESSION['user_id'] ?? null;
            if (!$currentUserId) {
                // Si no hay user_id en sesión, obtenerlo por username
                $stmt = $pdo->prepare("SELECT id FROM users WHERE username = :username");
                $stmt->execute([':username' => $_SESSION['username'] ?? '']);
                $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
                $currentUserId = $currentUser['id'] ?? null;
            }

            $hash = password_hash($pass, PASSWORD_DEFAULT);

            // Verificar si la columna created_by existe
            $stmt = $pdo->query("SHOW COLUMNS FROM users LIKE 'created_by'");
            $hasCreatedBy = $stmt->rowCount() > 0;

            $pdo->beginTransaction();
            try {
                if ($hasCreatedBy) {
                    $stmt = $pdo->prepare("INSERT INTO users (username, password, role, ship_id, created_by, status) VALUES (:user, :pass, 'user', :ship, :created_by, 'active')");
                    $stmt->execute([
                        ':user' => $user,
                        ':pass' => $hash,
                        ':ship' => $shipId,
                        ':created_by' => $currentUserId
                    ]);
                } else {
                    $stmt = $pdo->prepare("INSERT INTO users (username, password, role, ship_id, status) VALUES (:user, :pass, 'user', :ship, 'active')");
                    $stmt->execute([
                        ':user' => $user,
                        ':pass' => $hash,
                        ':ship' => $shipId
                    ]);
                }

                $newUserId = $pdo->lastInsertId();

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

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

            echo json_encode(['success' => true]);
        } elseif ($action === 'delete') {
            $userId = $input['user_id'] ?? '';
            if (!$userId)
                throw new Exception("Falta ID de usuario");

            // Get user's ship and created_by to verify permission
            $stmt = $pdo->prepare("SELECT ship_id, created_by, role FROM users WHERE id = :id");
            $stmt->execute([':id' => $userId]);
            $targetUser = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$targetUser)
                throw new Exception("Usuario no encontrado");

            checkPermission($targetUser['ship_id']);

            // Verificar que el usuario fue creado por el sub-adm actual
            $currentUserId = $_SESSION['user_id'] ?? null;
            if (!$currentUserId) {
                $stmt = $pdo->prepare("SELECT id FROM users WHERE username = :username");
                $stmt->execute([':username' => $_SESSION['username'] ?? '']);
                $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
                $currentUserId = $currentUser['id'] ?? null;
            }

            // Verificar si la columna created_by existe
            $stmt = $pdo->query("SHOW COLUMNS FROM users LIKE 'created_by'");
            $hasCreatedBy = $stmt->rowCount() > 0;

            if ($hasCreatedBy && $targetUser['created_by'] !== null) {
                // Solo permitir eliminar si fue creado por el sub-adm actual
                if ($targetUser['created_by'] != $currentUserId) {
                    throw new Exception("Solo puedes eliminar usuarios que creaste");
                }
            }

            // Solo permitir eliminar usuarios comunes
            if ($targetUser['role'] !== 'user') {
                throw new Exception("Solo se pueden eliminar usuarios comunes");
            }

            $pdo->beginTransaction();
            try {
                // Delete user_ships mappings
                $stmt = $pdo->prepare("DELETE FROM user_ships WHERE user_id = :id");
                $stmt->execute([':id' => $userId]);

                // Delete user
                $stmt = $pdo->prepare("DELETE FROM users WHERE id = :id AND role = 'user'");
                $stmt->execute([':id' => $userId]);

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

            echo json_encode(['success' => true]);
        } elseif ($action === 'change_password') {
            $userId = $input['user_id'] ?? '';
            $newPassword = $input['new_password'] ?? '';

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

            if (strlen($newPassword) < 4)
                throw new Exception("Contraseña muy corta");

            // Get user's ship and created_by to verify permission
            $stmt = $pdo->prepare("SELECT id, ship_id, created_by, role FROM users WHERE id = :id");
            $stmt->execute([':id' => $userId]);
            $targetUser = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$targetUser)
                throw new Exception("Usuario no encontrado");

            // Obtener el ID del usuario actual de la sesión
            $currentUserId = $_SESSION['user_id'] ?? null;
            if (!$currentUserId) {
                $stmt = $pdo->prepare("SELECT id FROM users WHERE username = :username");
                $stmt->execute([':username' => $_SESSION['username'] ?? '']);
                $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
                $currentUserId = $currentUser['id'] ?? null;
            }

            // --- LÓGICA DE PERMISOS REFORZADA ---
            $isSelfUpdate = (intval($userId) === intval($currentUserId));

            if (!$isSelfUpdate) {
                // Si no es un autocambio, aplicar reglas normales de administración
                checkPermission($targetUser['ship_id']);

                // Verificar si la columna created_by existe
                $stmt = $pdo->query("SHOW COLUMNS FROM users LIKE 'created_by'");
                $hasCreatedBy = $stmt->rowCount() > 0;

                if ($hasCreatedBy && $targetUser['created_by'] !== null) {
                    if ($targetUser['created_by'] != $currentUserId) {
                        throw new Exception("Solo puedes cambiar la contraseña de usuarios que creaste");
                    }
                }

                if ($targetUser['role'] !== 'user') {
                    throw new Exception("Solo se puede cambiar la contraseña de usuarios comunes");
                }
            } else {
                // Si es un autocambio, solo necesitamos asegurar que tiene acceso al buque (para seguridad extra)
                // aunque técnicamente si está logueado ya tiene sesión.
                if (!hasShipAccess($targetUser['ship_id'])) {
                    throw new Exception("No tienes acceso a este buque");
                }
            }

            $hash = password_hash($newPassword, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = :pass WHERE id = :id");
            $stmt->execute([':pass' => $hash, ':id' => $userId]);

            echo json_encode(['success' => true]);
        } else {
            throw new Exception("Acción inválida");
        }
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
exit;
?>