<?php
/**
 * ============================================================
 * ADMIN LOGIN PAGE
 * ============================================================
 */

define('BASE_PATH', dirname(dirname(__DIR__)));
require_once BASE_PATH . '/app/config/config.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Redirect if already logged in
if (isAdminLoggedIn()) {
    redirect(adminUrl());
}

// Generate CSRF token
CSRF::generateToken();

$pageTitle = 'Admin Login';
$error = '';
$expired = isset($_GET['expired']);

// Handle form submission (non-AJAX fallback)
if (isPost()) {
    if (!csrf_validate()) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $email = sanitize(post('email'));
        $password = post('password');
        
        $admin = Database::fetchOne(
            "SELECT id, full_name, email, password_hash, is_active FROM admins WHERE email = ?",
            [$email]
        );
        
        if (!$admin) {
            $error = 'Invalid email or password.';
        } elseif (!$admin['is_active']) {
            $error = 'Your account is deactivated.';
        } elseif (!password_verify($password, $admin['password_hash'])) {
            $error = 'Invalid email or password.';
        } else {
            // Set session
            $_SESSION['admin_id'] = $admin['id'];
            $_SESSION['admin_name'] = $admin['full_name'];
            $_SESSION['admin_email'] = $admin['email'];
            $_SESSION['admin_last_activity'] = time();
            
            // Update last login
            Database::execute(
                "UPDATE admins SET last_login_at = NOW() WHERE id = ?",
                [$admin['id']]
            );
            
            // Redirect
            $redirect = $_SESSION['admin_intended_url'] ?? adminUrl();
            unset($_SESSION['admin_intended_url']);
            redirect($redirect);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?> | <?= SITE_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-card {
            background: white;
            border-radius: 1rem;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            padding: 2rem;
            width: 100%;
            max-width: 400px;
        }
        .login-logo {
            text-align: center;
            margin-bottom: 1.5rem;
        }
        .login-logo i {
            font-size: 3rem;
            color: #764ba2;
        }
    </style>
</head>
<body>
    <div class="login-card">
        <div class="login-logo">
            <i class="bi bi-shield-lock"></i>
            <h4 class="mt-2">Admin Panel</h4>
            <p class="text-muted small"><?= SITE_NAME ?></p>
        </div>
        
        <?php if ($expired): ?>
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
            <i class="bi bi-clock me-2"></i>Your session has expired. Please login again.
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="bi bi-exclamation-circle me-2"></i><?= sanitize($error) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <form method="POST" action="">
            <?= csrf_field() ?>
            
            <div class="mb-3">
                <label for="email" class="form-label">Email Address</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-envelope"></i></span>
                    <input type="email" class="form-control" id="email" name="email" 
                           value="<?= sanitize(post('email', '')) ?>" required autofocus>
                </div>
            </div>
            
            <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-key"></i></span>
                    <input type="password" class="form-control" id="password" name="password" required>
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary w-100">
                <i class="bi bi-box-arrow-in-right me-2"></i>Login
            </button>
        </form>
        
        <div class="text-center mt-3">
            <a href="<?= url('public/') ?>" class="text-muted small">
                <i class="bi bi-arrow-left me-1"></i>Back to Website
            </a>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
