<?php
/**
 * Admin Portal Login Page
 * Strictly handles authentication for administrators only.
 */

// Include core files (using relative paths to reach the includes directory)
require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
require_once '../includes/admin-auth.php';
require_once '../includes/csrf.php';

// -----------------------------------------------------------------------------
// 1. ACCESS CONTROL CHECKS
// -----------------------------------------------------------------------------
// If already logged in as an admin, send them straight to the dashboard
redirect_if_admin($pdo);

// If logged in as a normal user, boot them out of the admin area completely
if (is_logged_in() && !is_admin($pdo)) {
    // Log this unauthorized access attempt
    error_log("SECURITY ALERT: Standard user ID " . $_SESSION['user_id'] . " attempted to access admin login page.");
    set_flash_message('error', 'Access denied. Administrative privileges are strictly required.');
    redirect(SITE_URL . '/account.php');
}

$email = '';
$errors = [];

// -----------------------------------------------------------------------------
// 2. HANDLE ADMIN LOGIN FORM SUBMISSION
// -----------------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token strictly
    enforce_csrf();

    // Sanitize and collect input
    $email = sanitize_input($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    // Basic Validation
    if (empty($email)) {
        $errors[] = "Admin email address is required.";
    }
    
    if (empty($password)) {
        $errors[] = "Admin password is required.";
    }

    // Attempt Authentication
    if (empty($errors)) {
        try {
            // Fetch user strictly ensuring they are an admin
            $stmt = $pdo->prepare("SELECT id, name, email, password, role, status FROM users WHERE email = :email AND role = 'admin' LIMIT 1");
            $stmt->bindParam(':email', $email, PDO::PARAM_STR);
            $stmt->execute();
            $admin_user = $stmt->fetch();

            // Verify admin exists and password is correct
            if ($admin_user && password_verify($password, $admin_user['password'])) {
                
                // Strictly check if the admin account is active
                if ($admin_user['status'] !== 'active') {
                    error_log("SECURITY ALERT: Suspended admin account attempted login. Email: " . $email);
                    $errors[] = "This administrative account has been suspended.";
                } else {
                    // Critical Security Step: Regenerate session ID to prevent session fixation
                    session_regenerate_id(true);

                    // Set session variables
                    $_SESSION['user_id'] = $admin_user['id'];
                    
                    // Welcome message
                    set_flash_message('success', 'Admin session initiated. Welcome, ' . htmlspecialchars($admin_user['name']) . '.');

                    // Secure redirect to dashboard
                    redirect(SITE_URL . '/admin/dashboard.php');
                }
            } else {
                // Generic error message. 
                // We do NOT want attackers knowing if an admin email exists but the password failed, or vice versa.
                error_log("FAILED ADMIN LOGIN ATTEMPT for email: " . $email . " from IP: " . $_SERVER['REMOTE_ADDR']);
                $errors[] = "Invalid administrative credentials.";
            }

        } catch (PDOException $e) {
            error_log("Admin Login System Error: " . $e->getMessage());
            $errors[] = "A critical system error occurred. Check server logs.";
        }
    }
}

// Set header variables
$page_title = "Admin Secure Login";
// Ensure we load the header from the includes directory
require_once '../includes/header.php';
?>

<style>
    .admin-auth-container {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: calc(100vh - 200px);
        padding: 40px 20px;
    }
    .admin-auth-card {
        width: 100%;
        max-width: 450px;
        padding: 40px;
        /* Slight red/orange hue to differentiate the admin login securely */
        border-top: 4px solid var(--accent-orange);
    }
    .admin-auth-header {
        text-align: center;
        margin-bottom: 32px;
    }
    .admin-icon {
        color: var(--accent-orange);
        margin-bottom: 16px;
    }
    .admin-auth-title {
        font-size: 1.8rem;
        margin-bottom: 8px;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }
    .admin-auth-subtitle {
        color: var(--danger);
        font-size: 0.85rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.1em;
    }
    .auth-form-errors {
        background: rgba(239, 68, 68, 0.1);
        border: 1px solid rgba(239, 68, 68, 0.3);
        border-radius: var(--radius-sm);
        padding: 16px;
        margin-bottom: 24px;
        color: var(--danger);
        font-size: 0.9rem;
    }
    .auth-form-errors ul {
        margin: 0;
        padding-left: 20px;
    }
    .return-link {
        display: block;
        text-align: center;
        margin-top: 24px;
        color: var(--text-muted);
        font-size: 0.9rem;
        transition: color var(--transition-fast);
    }
    .return-link:hover {
        color: var(--text-primary);
    }
</style>

<div class="admin-auth-container">
    <div class="glass-card admin-auth-card">
        <div class="admin-auth-header">
            <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="admin-icon"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
            <h1 class="admin-auth-title">System Portal</h1>
            <p class="admin-auth-subtitle">Restricted Access Only</p>
        </div>

        <?php if (!empty($errors)): ?>
            <div class="auth-form-errors">
                <ul>
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <form action="<?php echo SITE_URL; ?>/admin/login.php" method="POST">
            <?php echo csrf_field(); ?>

            <div class="form-group">
                <label for="email" class="form-label">Admin Email</label>
                <input type="email" name="email" id="email" class="form-control" value="<?php echo htmlspecialchars($email); ?>" required autofocus autocomplete="off">
            </div>

            <div class="form-group">
                <label for="password" class="form-label">Admin Password</label>
                <input type="password" name="password" id="password" class="form-control" required autocomplete="off">
            </div>

            <button type="submit" class="btn btn-glow" style="width: 100%; margin-top: 16px; padding: 14px;">Authorize Session</button>
        </form>

        <a href="<?php echo SITE_URL; ?>/index.php" class="return-link">&larr; Return to Public Site</a>
    </div>
</div>

<?php 
// Ensure we load the footer from the includes directory
require_once '../includes/footer.php'; 
?>