<?php
/**
 * 🚀 SISTEMA IBO XC - LOGIN RECRIAÇÃO V4.0 (AUTO-UPGRADE EDITION)
 * Tema: Clean Horizon (White & Indigo)
 */

// 1. Configurações de Sessão e Segurança Avançada
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.use_strict_mode', 1);
    ini_set('session.cookie_samesite', 'Lax');
    ini_set('session.cookie_secure', isset($_SERVER['HTTPS']));
    session_start();
}

// 2. Proteção CSRF
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Headers de Proteção Global
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");
header_remove("X-Powered-By");

// 3. Conexão e Dependências
$functions_path = "includes/functions.php";
if (file_exists($functions_path)) {
    require_once $functions_path;
} else {
    if (!isset($db)) {
         $db = new class { public function select() { return []; } public function update() {} };
    }
}

if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true) {
    header("Location: dashboard.php");
    exit;
}

// 4. Lógica de Autenticação
$loginError = false;
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["login"])) {
    
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("Ação não autorizada.");
    }

    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $password = $_POST["password"] ?? '';
    
    if (empty($username) || empty($password)) {
        $loginError = "Por favor, preencha todos os campos.";
    } else {
        if(method_exists($db, 'select')){
             $userData = $db->select("users", "*", "username = :username", "", [":username" => $username]);
        } else {
             $userData = []; 
        }
        
        if ($userData && count($userData) > 0) {
            $user = $userData[0];
            $password_in_db = $user["password"];
            
            $is_hash = (strpos($password_in_db, '$2y$') === 0);
            $authenticated = false;

            if ($is_hash && password_verify($password, $password_in_db)) {
                $authenticated = true;
            } 
            elseif (!$is_hash && $password === $password_in_db) {
                $authenticated = true;
                $newSecureHash = password_hash($password, PASSWORD_DEFAULT);
                $db->update("users", ["password" => $newSecureHash], "id = :id", [":id" => $user['id']]);
            }
            
            if ($authenticated) {
                session_regenerate_id(true);
                $_SESSION["loggedin"] = true;
                $_SESSION["name"]       = $user["username"];
                $_SESSION["user_id"]   = $user["id"] ?? null;
                $_SESSION["last_login"] = time();
                
                header("Location: dashboard.php");
                exit;
            }
        }
        $loginError = "Usuário ou senha incorretos.";
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>IBO XC</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        :root { 
            --primary: #4f46e5; 
            --primary-hover: #4338ca;
            --bg-body: #f3f4f6; 
            --bg-card: #ffffff;
            --text-main: #111827;
            --text-muted: #6b7280;
            --border-color: #e5e7eb;
            --shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }

        body { 
            background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
            background-size: 400% 400%;
            animation: gradientBG 15s ease infinite;
            font-family: 'Inter', sans-serif; 
            min-height: 100vh;
            display: flex; 
            align-items: center; 
            justify-content: center; 
            margin: 0; 
        }

        @keyframes gradientBG {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        /* TELA DE CARREGAMENTO "C" CENTRALIZADA */
        #loader-overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(255, 255, 255, 0.95);
            display: none; /* Escondido por padrão */
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 9999;
        }

        .loader-letter {
            font-size: 80px;
            font-weight: 900;
            color: var(--primary);
            animation: pulseC 1.5s ease-in-out infinite;
        }

        @keyframes pulseC {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.2); opacity: 0.5; }
            100% { transform: scale(1); opacity: 1; }
        }

        .login-card { 
            background: var(--bg-card); 
            border: 1px solid var(--border-color); 
            border-radius: 20px; 
            padding: 40px; 
            width: 90%; 
            max-width: 400px; 
            box-shadow: var(--shadow); 
            z-index: 10;
            position: relative;
            transform: scale(0.9);
            opacity: 0;
            transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
        }

        .login-card.active { transform: scale(1); opacity: 1; }

        .brand-logo { text-align: center; margin-bottom: 30px; }
        .brand-logo i {
            font-size: 2.5rem;
            color: var(--primary);
            background: #eef2ff;
            padding: 20px;
            border-radius: 20px;
            margin-bottom: 15px;
        }

        .input-wrapper { position: relative; margin-bottom: 15px; }
        .input-wrapper i:not(.toggle-password) { 
            position: absolute; left: 16px; top: 50%; transform: translateY(-50%); 
            color: #9ca3af; 
        }

        .form-input { 
            background: #f9fafb !important; 
            border: 1px solid var(--border-color) !important; 
            border-radius: 12px !important; 
            padding: 14px 16px 14px 45px !important; 
            height: 55px !important; 
            width: 100%; 
            font-size: 1rem;
        }

        .form-input:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1) !important; outline: none; }

        .btn-premium { 
            background: var(--primary);
            border: none; border-radius: 12px; 
            height: 55px; width: 100%; 
            font-weight: 700; color: white; 
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .btn-premium:hover { transform: translateY(-2px); box-shadow: 0 10px 20px -10px var(--primary); }

        .toggle-password { position: absolute; right: 16px; top: 50%; transform: translateY(-50%); cursor: pointer; color: #9ca3af; }

        .error-toast {
            background: #fff1f2; color: #e11d48; padding: 12px; border-radius: 10px; margin-bottom: 20px; font-size: 0.9rem; text-align: center; font-weight: 600;
        }
    </style>
</head>
<body>

    <div id="loader-overlay">
        <div class="loader-letter">C</div>
        <p class="mt-3 fw-bold text-muted">Autenticando...</p>
    </div>

    <div class="login-card" id="loginCard">
        <div class="brand-logo">
            <i class="fas fa-shield-halved"></i>
            <h3 class="fw-bold">IBO XC</h3>
            <p class="text-muted small">Gerencie sua operação em 2026</p>
        </div>

        <?php if ($loginError): ?>
            <div class="error-toast">
                <i class="fas fa-circle-xmark me-2"></i> <?= htmlspecialchars($loginError) ?>
            </div>
        <?php endif; ?>

        <form method="POST" id="formLogin">
            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
            
            <div class="input-wrapper">
                <i class="fa-regular fa-user"></i>
                <input type="text" name="username" class="form-input" placeholder="Usuário" required autofocus>
            </div>
            
            <div class="input-wrapper">
                <i class="fa-solid fa-lock"></i>
                <input type="password" name="password" id="password" class="form-input" placeholder="Senha" required>
                <i class="fa-regular fa-eye toggle-password" id="btnToggle"></i>
            </div>

            <button type="submit" name="login" class="btn-premium" id="btnSubmit">
                <i class="fas fa-sign-in-alt"></i> ACESSAR PAINEL
            </button>
        </form>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const card = document.getElementById('loginCard');
            setTimeout(() => card.classList.add('active'), 100);

            const btnToggle = document.getElementById('btnToggle');
            const pwdInput = document.getElementById('password');
            
            btnToggle.onclick = () => {
                const isPwd = pwdInput.type === 'password';
                pwdInput.type = isPwd ? 'text' : 'password';
                btnToggle.classList.toggle('fa-eye', !isPwd);
                btnToggle.classList.toggle('fa-eye-slash', isPwd);
            };

            // Lógica para mostrar o loader "C" no submit
            document.getElementById('formLogin').onsubmit = function() {
                const loader = document.getElementById('loader-overlay');
                loader.style.display = 'flex'; // Mostra a tela de carregamento
                const card = document.getElementById('loginCard');
                card.style.opacity = '0.3'; // Esmaece o card ao fundo
            };
        });
    </script>
</body>
</html>