<?php
require_once 'config/database.php';
require_once 'config/auth.php';
require_once 'includes/functions.php';

if (isLoggedIn()) {
    header('Location: admin/dashboard.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    
    if (login($username, $password)) {
        header('Location: admin/dashboard.php');
        exit;
    } else {
        $error = 'Invalid username or password';
    }
}

$page_title = 'Login';
include 'includes/header.php';
?>

<section class="login-section">
    <div class="container">
        <div class="login-card">
            <div class="login-header">
                <h1>Admin Login</h1>
                <p>Sign in to manage your blog content</p>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-error">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['expired'])): ?>
                <div class="alert alert-error">
                    Your session has expired due to inactivity. Please log in again.
                </div>
            <?php endif; ?>

            <form method="POST" class="login-form">
                <div class="form-group">
                    <label for="username">Username</label>
                    <input type="text" id="username" name="username" required>
                </div>

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

                <button type="submit" class="btn btn-primary btn-full">Login</button>
            </form>

            <div class="login-help">
                <p>Default credentials: admin / password</p>
            </div>
        </div>
    </div>
</section>

<?php include 'includes/footer.php'; ?>