<?php
require_once __DIR__ . '/../includes/bootstrap.php';

if (is_logged_in()) {
    redirect('admin/dashboard.php');
}

$appName = config('app.name', 'QR Attendance');
$supportEmail = config('app.support_email', 'support@campus.local');
$supportLink = 'mailto:' . $supportEmail;

$errors = [];

if (is_post()) {
    if (!validate_csrf_token($_POST['csrf_token'] ?? null)) {
        $errors[] = 'Invalid session token. Please refresh.';
    } else {
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');

        if ($username === '' || $password === '') {
            $errors[] = 'Username and password are required.';
        } elseif (!attempt_login($username, $password)) {
            $errors[] = 'Invalid credentials.';
        } else {
            add_flash('success', 'Welcome back!');
            redirect('admin/dashboard.php');
        }
    }
}

render_header('Sign in', ['hide_nav' => true]);
?>
<section class="google-auth-shell d-flex flex-column align-items-center justify-content-center gap-4 w-100">
    <div class="text-center">
        <span class="badge text-bg-light px-3 py-2 text-uppercase fw-semibold">Admin Portal</span>
        <p class="text-muted mb-0">Use your institution-issued credentials to continue.</p>
    </div>
    <div class="google-auth-card card shadow-sm border-0">
        <div class="text-center mb-4 google-auth-head">
            <div class="google-logo" aria-label="<?= sanitize($appName) ?>">
                <span class="qr-logo-icon" aria-hidden="true">
                    <svg viewBox="0 0 64 64" role="presentation" focusable="false">
                        <rect x="2" y="2" width="20" height="20" rx="4" fill="#0f5132"></rect>
                        <rect x="42" y="2" width="20" height="20" rx="4" fill="#1b7f5c"></rect>
                        <rect x="2" y="42" width="20" height="20" rx="4" fill="#146946"></rect>
                        <rect x="26" y="26" width="12" height="12" rx="2" fill="#0f5132"></rect>
                        <rect x="44" y="36" width="12" height="12" rx="2" fill="#1b7f5c"></rect>
                        <rect x="32" y="48" width="8" height="8" rx="2" fill="#146946"></rect>
                        <rect x="24" y="8" width="8" height="8" rx="2" fill="#1b7f5c"></rect>
                        <rect x="8" y="32" width="8" height="8" rx="2" fill="#0f5132"></rect>
                    </svg>
                </span>
                <span class="google-logo-text"><?= sanitize($appName) ?></span>
            </div>
            <h1 class="google-title mb-1">Sign in</h1>
            <p class="google-subtitle">Use your administrator account</p>
        </div>
        <?php if ($errors): ?>
            <div class="alert alert-danger mb-4">
                <?php foreach ($errors as $error): ?>
                    <div><?= sanitize($error) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <form method="post" novalidate class="google-form">
            <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
            <div class="google-field">
                <input type="text"
                       name="username"
                       id="username"
                       class="google-input"
                       placeholder=" "
                       value="<?= sanitize($_POST['username'] ?? '') ?>"
                       autocomplete="username"
                       required>
                <label for="username" class="google-label">Email or username</label>
            </div>
            <div class="google-field">
                <input type="password"
                       name="password"
                       id="password"
                       class="google-input"
                       placeholder=" "
                       autocomplete="current-password"
                       required
                       data-password-input>
                <label for="password" class="google-label">Password</label>
                <button type="button" class="google-toggle" data-password-toggle>Show</button>
            </div>
            <div class="google-links">
                <a href="<?= sanitize($supportLink) ?>">Need help?</a>
            </div>
            <div class="google-actions">
                <button type="button" class="btn btn-link google-alt-action px-0">Create account</button>
                <button type="submit" class="btn btn-primary google-primary-action">
                    Next
                </button>
            </div>
        </form>
        <p class="google-footnote text-muted text-center">
            This console is managed by <?= sanitize($appName) ?> IT. By continuing, you agree to internal security policies.
        </p>
    </div>
</section>
<?php
?>
<script>
document.addEventListener('DOMContentLoaded', () => {
    const input = document.querySelector('[data-password-input]');
    const toggle = document.querySelector('[data-password-toggle]');
    if (!input || !toggle) return;

    toggle.addEventListener('click', () => {
        const isHidden = input.type === 'password';
        input.type = isHidden ? 'text' : 'password';
        toggle.textContent = isHidden ? 'Hide' : 'Show';
    });
});
</script>
<?php
render_footer(['extra_js' => []]);
