<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/config.php';
require_once 'includes/security_logger.php';
require_once 'includes/admin_security.php';

// Check if user is already logged in
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
    header('Location: dashboard.php');
    exit;
}

if (isset($_GET['blocked']) && $_GET['blocked'] === '1') {
    $error = 'This IP address is blocked from the admin panel.';
}

// Handle login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (!isset($error))) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if (empty($username) || empty($password)) {
    } else {
        try {
            $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $ip_status = get_ip_security_status($pdo);
            if ($ip_status['is_blocked']) {
                $blocked_message = $ip_status['is_manual_block']
                    ? 'Access from your IP address has been blocked by an administrator.'
                    : 'Too many failed login attempts. Please try again in ' . max(1, $ip_status['minutes_remaining']) . ' minute(s).';

                log_security_event($pdo, 'login_blocked', $username, $blocked_message);
                $error = $blocked_message;
            } else {
                $stmt = $pdo->prepare("SELECT * FROM members WHERE username = ? AND is_admin = 1");
                $stmt->execute([$username]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($user && password_verify($password, $user['password']) && !$user['suspended']) {
                    $updateStmt = $pdo->prepare("UPDATE members SET last_access = NOW() WHERE id = ?");
                    $updateStmt->execute([$user['id']]);

                    log_security_event($pdo, 'login_success', $username, "Admin login successful");
                    clear_ip_security_state($pdo);

                    session_regenerate_id(true);

                    $_SESSION['admin_logged_in'] = true;
                    $_SESSION['admin_username'] = $username;
                    $_SESSION['admin_id'] = $user['id'];
                    $_SESSION['user_ip'] = get_client_ip_address();
                    $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
                    $_SESSION['admin_name'] = $user['firstName'] . ' ' . $user['lastName'];
                    $_SESSION['last_activity'] = time();

                    header('Location: dashboard.php');
                    exit;
                } elseif ($user && $user['suspended']) {
                    register_failed_login_attempt($pdo, $username, 'Suspended account login attempt');
                    $error = 'Account suspended. Please contact an administrator.';
                } else {
                    $ip_status = register_failed_login_attempt($pdo, $username, 'Invalid credentials');
                    $error = $ip_status['is_blocked']
                        ? 'Too many failed login attempts. Please try again in ' . max(1, $ip_status['minutes_remaining']) . ' minute(s).'
                        : 'Invalid username or password.';
                }
            }
        } catch (PDOException $e) {
            $error = 'Database connection error. Please try again later.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login - <?php echo BRAND_NAME; ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #3b82f6;
            --primary-dark: #2563eb;
            --bg-dark: #0f172a;
            --bg-darker: #020617;
            --card-bg: #1e293b;
            --border-color: #334155;
            --text-light: #f8fafc;
            --text-muted: #94a3b8;
            --accent: #ec4899;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, var(--bg-darker) 0%, var(--bg-dark) 100%);
            color: var(--text-light);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-container {
            width: 100%;
            max-width: 400px;
            padding: 2rem;
        }

        .login-card {
            background: var(--card-bg);
            border-radius: 16px;
            padding: 2.5rem;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
            border: 1px solid var(--border-color);
        }

        .logo {
            text-align: center;
            margin-bottom: 2rem;
        }

        .logo-text {
            font-size: 2rem;
            font-weight: 800;
            color: var(--text-light);
            letter-spacing: -0.5px;
        }

        .logo-highlight {
            color: var(--accent);
        }

        .login-title {
            text-align: center;
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: var(--text-light);
        }

        .login-subtitle {
            text-align: center;
            color: var(--text-muted);
            margin-bottom: 2rem;
            font-size: 0.9rem;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text-light);
            font-weight: 500;
        }

        .form-input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: var(--bg-dark);
            color: var(--text-light);
            font-size: 1rem;
            transition: all 0.2s ease;
        }

        .form-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
        }

        .login-btn {
            width: 100%;
            padding: 0.75rem 1rem;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            margin-top: 0.5rem;
        }

        .login-btn:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        }

        .error-message {
            background: rgba(239, 68, 68, 0.1);
            color: #fca5a5;
            padding: 0.75rem;
            border-radius: 8px;
            border: 1px solid rgba(239, 68, 68, 0.3);
            margin-bottom: 1rem;
            text-align: center;
        }

        .footer {
            text-align: center;
            margin-top: 2rem;
            color: var(--text-muted);
            font-size: 0.85rem;
        }

        .footer a {
            color: var(--primary);
            text-decoration: none;
        }

        .footer a:hover {
            text-decoration: underline;
        }

        @media (max-width: 480px) {
            .login-container {
                padding: 1rem;
            }

            .login-card {
                padding: 2rem 1.5rem;
            }

            .logo-text {
                font-size: 1.75rem;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="logo">
                <div class="logo-text">
                    <?php echo htmlspecialchars(BRAND_NAME); ?>
                </div>
            </div>

            <h1 class="login-title">Admin Login</h1>
            <p class="login-subtitle">Access the administration panel</p>

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

            <form method="POST" action="">
                <div class="form-group">
                    <label class="form-label" for="username">Username</label>
                    <input
                        type="text"
                        id="username"
                        name="username"
                        class="form-input"
                        required
                        autocomplete="username"
                        value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
                    >
                </div>

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

                <button type="submit" class="login-btn">
                    Sign In
                </button>
            </form>

            <div class="footer">
                <p>Forgot your password? <a href="mailto:<?php echo htmlspecialchars(SUPPORT_EMAIL); ?>">Contact Support</a></p>
            </div>
        </div>
    </div>
</body>
</html>
