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

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

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

    if (!$data || !isset($data['user']) || !isset($data['pass'])) {
        echo json_encode(['success' => false, 'message' => 'Datos incompletos']);
        exit;
    }

    $username = trim($data['user']);
    $password = trim($data['pass']);

    $pdo = getDBConnection();
    if (!$pdo) {
        echo json_encode(['success' => false, 'message' => 'Error de conexi??n']);
        exit;
    }

    $stmt = $pdo->prepare("SELECT id, username, password, role, status, ship_id FROM users WHERE username = :user");
    $stmt->execute([':user' => $username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['password'])) {
        if ($user['status'] !== 'active') {
            echo json_encode(['success' => false, 'message' => 'Cuenta pendiente de aprobaci??n o inactiva']);
            exit;
        }

        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role'] = $user['role'];
        $_SESSION['ship_id'] = $user['ship_id'] ?? null; // Store ship scope

        ob_clean(); echo json_encode(['success' => true, 'role' => $user['role'], 'ship_id' => $user['ship_id']]);
    } else {
        ob_clean(); echo json_encode(['success' => false, 'message' => 'Credenciales inv??lidas']);
    }

} catch (Exception $e) {
    error_log("Login Error: " . $e->getMessage());
    ob_clean(); echo json_encode(['success' => false, 'message' => 'Error del sistema']);
}
ob_end_flush();
?>
