<?php
// admin/login.php
session_start();

// Only generate a new CSRF token if one doesn't already exist in the session.
// This prevents the token from changing on every refresh, which was causing errors.
if (empty($_SESSION['admin_csrf_token'])) {
    $_SESSION['admin_csrf_token'] = bin2hex(random_bytes(32));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login - First National Bank Incorporated</title>
    
    <!-- CSS Dependencies -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/boxicons@2.0.7/css/boxicons.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">

    <style>
        :root {
            --primary-color: #4f46e5; /* Indigo for admin */
            --secondary-color: #4338ca;
            --background-color: #f1f5f9; /* Lighter gray */
        }
        body {
            font-family: 'Poppins', sans-serif;
            background: var(--background-color);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 1rem;
        }
        .login-card {
            width: 100%;
            max-width: 450px;
            background: white;
            border-radius: 1rem;
            overflow: hidden;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
            animation: fadeIn 0.5s ease-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .login-header {
            background: var(--primary-color);
            padding: 2rem;
            color: white;
            text-align: center;
        }
        .login-header h3 {
            font-weight: 600;
            margin: 0;
        }
        .login-body {
            padding: 2rem;
        }
        .form-control {
            padding: 0.75rem 1rem;
            border-radius: 10px;
            border: 2px solid #e2e8f0;
            font-size: 0.95rem;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(79, 70, 229, 0.15);
        }
        .form-label {
            font-weight: 500;
            color: #4b5563;
        }
        .btn-primary {
            background: var(--primary-color);
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        .btn-primary:hover {
            background: var(--secondary-color);
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }
        .input-group-text {
            background-color: #fff;
            border-left: 0;
        }
        .auth-links {
            margin-top: 1.5rem;
            text-align: center;
            font-size: 0.9rem;
        }
        .auth-links a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
        }
    </style>
</head>
<body>

<div class="login-card">
    <div class="login-header">
        <h3><i class='bx bxs-user-shield' style="vertical-align: middle;"></i> Admin Panel</h3>
        <p class="mb-0 opacity-75">Secure Login</p>
    </div>
    <div class="login-body">
        <!-- The onsubmit attribute has been REMOVED. We will attach the event in JavaScript. -->
        <form id="adminLoginForm">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['admin_csrf_token']); ?>">
            
            <div class="mb-3">
                <label for="username" class="form-label">Admin Username</label>
                <input type="text" class="form-control" id="username" name="username" required autocomplete="username">
            </div>

            <div class="mb-4">
                <label for="password" class="form-label">Password</label>
                <div class="input-group">
                    <input type="password" class="form-control" id="password" name="password" required autocomplete="current-password">
                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword(this)">
                        <i class='bx bx-show'></i>
                    </button>
                </div>
            </div>

            <button type="submit" class="btn btn-primary w-100 mt-3">Login</button>
            
            <div class="auth-links">
                <a href="../login.php">Return to User Login</a>
            </div>
        </form>
    </div>
</div>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    // This ensures the script runs after the HTML is fully loaded
    document.addEventListener('DOMContentLoaded', function() {
        
        // Find the form and attach the submit event listener
        const adminForm = document.getElementById('adminLoginForm');
        if (adminForm) {
            adminForm.addEventListener('submit', handleAdminLogin);
        }

        // The login handler function
        async function handleAdminLogin(event) {
            event.preventDefault(); // This is the most important line to prevent the refresh
            
            const form = event.target;
            const formData = new FormData(form);
            const csrfToken = formData.get('csrf_token');

            Swal.fire({
                title: 'Authenticating...',
                text: 'Please wait',
                allowOutsideClick: false,
                didOpen: () => { Swal.showLoading(); }
            });

            try {
                const response = await fetch('verify_admin_login.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        username: formData.get('username'),
                        password: formData.get('password'),
                        csrf_token: csrfToken
                    })
                });

                const data = await response.json();

                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Login Successful!',
                        text: 'Redirecting to the dashboard...',
                        timer: 1500,
                        showConfirmButton: false,
                        timerProgressBar: true
                    }).then(() => {
                        window.location.href = data.redirect;
                    });
                } else {
                    // If login fails, update the CSRF token on the page with the new one from the server
                    if (data.new_csrf_token) {
                        document.querySelector('input[name="csrf_token"]').value = data.new_csrf_token;
                    }
                    Swal.fire({
                        icon: 'error',
                        title: 'Login Failed',
                        text: data.message
                    });
                }
            } catch (error) {
                console.error('Login Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'A communication error occurred. Please check the console for details.'
                });
            }
        }
    });

    // This function is now defined in the global scope and works correctly
    function togglePassword(button) {
        const passwordInput = button.previousElementSibling;
        const icon = button.querySelector('i');

        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.replace('bx-show', 'bx-hide');
        } else {
            passwordInput.type = 'password';
            icon.classList.replace('bx-hide', 'bx-show');
        }
    }
</script>

<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
