<?php
declare(strict_types=1);

require_once __DIR__ . '/partials/main.php';

session_name(SESSION_NAME);
session_start();

/**
 * CSRF token generation
 */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];
?>

<head>
    <?php includeFileWithVariables(__DIR__ . '/partials/title-meta.php', ['title' => 'Sign In']); ?>
    <?php include __DIR__ . '/partials/head-css.php'; ?>
    <meta name="csrf-token" content="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
</head>

<?php include __DIR__ . '/partials/body.php'; ?>

<div>
    <img src="<?= ADMIN_BASE_URL ?>assets/images/auth/login_bg.jpg"
         class="auth-bg light w-full h-full opacity-60 position-absolute top-0"
         alt="Background">

    <img src="<?= ADMIN_BASE_URL ?>assets/images/auth/auth_bg_dark.jpg"
         class="auth-bg d-none dark"
         alt="Background dark">

    <div class="container">
        <div class="row justify-content-center align-items-center min-vh-100 py-10">
            <div class="col-12 col-md-8 col-lg-6 col-xl-5">
                <div class="card">
                    <div class="card-body py-12 px-8">

                        <img src="<?= ADMIN_BASE_URL ?>assets/images/logo-dark.png"
                             height="30"
                             class="mb-4 mx-auto d-block"
                             alt="Logo">

                        <h6 class="mb-3 fw-medium text-center">Admin Login</h6>

                        <div id="loginError" class="alert alert-danger d-none" role="alert"></div>

                        <form id="loginForm" novalidate>
                            <div class="row g-4">

                                <div class="col-12">
                                    <label for="email" class="form-label">Email</label>
                                    <input
                                        type="email"
                                        id="email"
                                        name="email"
                                        class="form-control"
                                        required
                                        autocomplete="email"
                                        maxlength="255">
                                </div>

                                <div class="col-12">
                                    <label for="password" class="form-label">Password</label>
                                    <input
                                        type="password"
                                        id="password"
                                        name="password"
                                        class="form-control"
                                        required
                                        autocomplete="current-password"
                                        minlength="8">
                                </div>

                                <div class="col-12 mt-4">
                                    <button
                                        type="submit"
                                        id="loginBtn"
                                        class="btn btn-primary w-100">
                                        Sign In
                                    </button>
                                </div>

                            </div>
                        </form>

                    </div>
                </div>

                <p class="text-center fs-12 mt-3">© 2025 India</p>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/partials/vendor-scripts.php'; ?>

<script>
(() => {
    const form = document.getElementById('loginForm');
    const errorBox = document.getElementById('loginError');
    const loginBtn = document.getElementById('loginBtn');
    const csrfToken = document.querySelector('meta[name="csrf-token"]').content;

    form.addEventListener('submit', async (e) => {
        e.preventDefault();

        errorBox.classList.add('d-none');
        loginBtn.disabled = true;

        const email = document.getElementById('email').value.trim();
        const password = document.getElementById('password').value;

        if (!email || !password) {
            showError('Email and password are required');
            return;
        }

        try {
            const res = await fetch('<?= ADMIN_BASE_URL ?>api/auth/login.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({ email, password })
            });

            const contentType = res.headers.get('content-type');
            let data = {};

            if (contentType && contentType.includes('application/json')) {
                data = await res.json();
            }

            if (!res.ok || data.status !== 'success') {
                showError(data.message || 'Invalid credentials');
                return;
            }

            window.location.replace('<?= ADMIN_BASE_URL ?>dashboard.php');

        } catch (err) {
            showError('Server unavailable. Please try again.');
        }
    });

    function showError(message) {
        errorBox.textContent = message;
        errorBox.classList.remove('d-none');
        loginBtn.disabled = false;
    }
})();
</script>

</body>
</html>
