<?php
session_start();

// Security headers
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");

error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('includes/config.php');

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Rate limiting
if (!isset($_SESSION['admin_login_attempts'])) {
    $_SESSION['admin_login_attempts'] = 0;
    $_SESSION['admin_last_attempt'] = time();
}

// Reset attempts after 15 minutes
if (time() - $_SESSION['admin_last_attempt'] > 900) {
    $_SESSION['admin_login_attempts'] = 0;
}

// Handle admin login
if (isset($_POST['admin_login'])) {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || !isset($_SESSION['csrf_token'])) {
        $_SESSION['errmsg'] = "Session expired. Please refresh and try again.";
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    } elseif ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['errmsg'] = "Invalid security token. Please try again.";
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    // Check rate limiting
    elseif ($_SESSION['admin_login_attempts'] >= 5) {
        $time_remaining = 900 - (time() - $_SESSION['admin_last_attempt']);
        $minutes = ceil($time_remaining / 60);
        $_SESSION['errmsg'] = "Too many login attempts. Please try again in $minutes minutes.";
    } else {
        // Sanitize input (accepts email OR username for admins)
        $login_input = trim($_POST['email']); // Field accepts both
        $password = $_POST['password'];

        // Determine if input is email or username
        $is_email = filter_var($login_input, FILTER_VALIDATE_EMAIL);

        if ($is_email) {
            // Login with EMAIL - Allow any authorized staff role
            $stmt = $con->prepare("SELECT id, username, email, password, role FROM users WHERE email = ? AND role IN ('admin', 'staff', 'sales') LIMIT 1");
            $stmt->bind_param("s", $login_input);
        } else {
            // Login with USERNAME - Allow any authorized staff role
            $stmt = $con->prepare("SELECT id, username, email, password, role FROM users WHERE username = ? AND role IN ('admin', 'staff', 'sales') LIMIT 1");
            $stmt->bind_param("s", $login_input);
        }

        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();

            // Verify password
            if (strlen($user['password']) === 32) {
                // Legacy MD5
                if (md5($password) === $user['password']) {
                    $new_hash = password_hash($password, PASSWORD_DEFAULT);
                    $update_stmt = $con->prepare("UPDATE users SET password = ? WHERE id = ?");
                    $update_stmt->bind_param("si", $new_hash, $user['id']);
                    $update_stmt->execute();
                    $update_stmt->close();
                    $login_success = true;
                } else {
                    $login_success = false;
                }
            } else {
                $login_success = password_verify($password, $user['password']);
            }

            if ($login_success) {
                // Regenerate session ID
                session_regenerate_id(true);

                // Set session variables
                $_SESSION['login'] = $user['email'];
                $_SESSION['id'] = $user['id'];
                $_SESSION['username'] = $user['username']; // Use username for admins
                $_SESSION['role'] = $user['role'];
                $_SESSION['admin_login_attempts'] = 0;

                // Backward compatibility with old admin files
                $_SESSION['alogin'] = $user['username'];
                $_SESSION['aid'] = $user['id'];

                // Log successful admin login
                $uip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
                $log_file = __DIR__ . '/logs/admin_logins.log';
                $log_dir = dirname($log_file);

                if (!file_exists($log_dir)) {
                    @mkdir($log_dir, 0755, true);
                }

                $log_entry = sprintf(
                    "[%s] Successful admin login: %s (%s) from IP: %s\n",
                    date('Y-m-d H:i:s'),
                    $user['username'],
                    $user['email'],
                    $uip
                );
                @file_put_contents($log_file, $log_entry, FILE_APPEND);

                // Add to DB Activity Log
                $admin_id = $user['id'];
                $action = "Admin Login";
                $details = "Admin " . $user['username'] . " logged in successfully.";
                $details_esc = mysqli_real_escape_string($con, $details);
                mysqli_query($con, "INSERT INTO admin_activity_log (portal, admin_id, action, details, ip_address) VALUES ('admin', '$admin_id', '$action', '$details_esc', '$uip')");

                // Redirect to admin or intended page
                $redirect = isset($_SESSION['redirect_after_login']) ? $_SESSION['redirect_after_login'] : '__admin__/index.php';
                unset($_SESSION['redirect_after_login']);
                unset($_SESSION['admin_login_required']);

                header("location: $redirect");
                exit();
            } else {
                $_SESSION['admin_login_attempts']++;
                $_SESSION['admin_last_attempt'] = time();
                $_SESSION['errmsg'] = "Invalid admin credentials";
                $uip = $_SERVER['REMOTE_ADDR'];
                $details = "Failed login attempt for account: " . $user['username'];
                $details_esc = mysqli_real_escape_string($con, $details);
                mysqli_query($con, "INSERT INTO admin_activity_log (portal, admin_id, action, details, ip_address) VALUES ('admin', 0, 'Failed Login', '$details_esc', '$uip')");
            }
        } else {
            $_SESSION['admin_login_attempts']++;
            $_SESSION['admin_last_attempt'] = time();
            $_SESSION['errmsg'] = "Invalid admin credentials or account not found";
            $uip = $_SERVER['REMOTE_ADDR'];
            $details = "Failed login attempt for unrecognized user: " . $login_input;
            $details_esc = mysqli_real_escape_string($con, $details);
            mysqli_query($con, "INSERT INTO admin_activity_log (portal, admin_id, action, details, ip_address) VALUES ('admin', 0, 'Failed Login', '$details_esc', '$uip')");
        }
        $stmt->close();
    }

    // Regenerate CSRF token
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// If already logged in as admin/staff, redirect
if (isset($_SESSION['role']) && in_array($_SESSION['role'], ['admin', 'staff', 'sales'])) {
    header("location: __admin__/index.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Admin Portal Login - Awesome Mall">
    <meta name="robots" content="noindex, nofollow">
    <title>Admin Login - Awesome Mall</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
        integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
        crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

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

        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .admin-login-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 450px;
            width: 100%;
            overflow: hidden;
        }

        .admin-header {
            background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
            padding: 40px 30px;
            text-align: center;
            color: white;
        }

        .admin-header i {
            font-size: 60px;
            margin-bottom: 15px;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {

            0%,
            100% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.1);
            }
        }

        .admin-header h1 {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .admin-header p {
            font-size: 14px;
            opacity: 0.95;
        }

        .admin-form {
            padding: 40px 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            font-weight: 600;
            font-size: 14px;
            color: #333;
            margin-bottom: 8px;
            display: block;
        }

        .form-control {
            height: 50px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 12px 16px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-control:focus {
            border-color: #f44336;
            box-shadow: 0 0 0 3px rgba(244, 67, 54, 0.1);
        }

        .password-toggle {
            position: relative;
        }

        .password-toggle .toggle-icon {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #999;
            font-size: 18px;
        }

        .btn-admin-login {
            height: 50px;
            background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
            border: none;
            border-radius: 10px;
            color: white;
            font-weight: 600;
            font-size: 15px;
            transition: all 0.3s;
            width: 100%;
        }

        .btn-admin-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 16px rgba(244, 67, 54, 0.4);
        }

        .btn-admin-login:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .error-message {
            background: #fee;
            border-left: 4px solid #d32f2f;
            color: #d32f2f;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .rate-limit-warning {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            color: #856404;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .back-link {
            text-align: center;
            margin-top: 20px;
        }

        .back-link a {
            color: #666;
            text-decoration: none;
            font-size: 14px;
        }

        .back-link a:hover {
            color: #f44336;
        }

        .security-badge {
            text-align: center;
            margin-top: 20px;
            color: #999;
            font-size: 12px;
        }

        .security-badge i {
            color: #4caf50;
            margin-right: 5px;
        }
    </style>
</head>

<body>
    <div class="admin-login-container">
        <div class="admin-header">
            <i class="fas fa-shield-alt"></i>
            <h1>Admin Portal</h1>
            <p>Secure Administrator Access</p>
        </div>

        <div class="admin-form">
            <?php if (!empty($_SESSION['errmsg'])): ?>
                <div class="error-message">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($_SESSION['errmsg'], ENT_QUOTES, 'UTF-8'); ?>
                </div>
                <?php $_SESSION['errmsg'] = ""; ?>
            <?php endif; ?>

            <?php if ($_SESSION['admin_login_attempts'] >= 3 && $_SESSION['admin_login_attempts'] < 5): ?>
                <div class="rate-limit-warning">
                    <i class="fas fa-exclamation-triangle"></i>
                    <?php echo (5 - $_SESSION['admin_login_attempts']); ?> login attempts remaining
                </div>
            <?php endif; ?>

            <form method="post" autocomplete="off">
                <input type="hidden" name="csrf_token"
                    value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">

                <div class="form-group">
                    <label class="form-label">
                        <i class="fas fa-user me-1"></i> Email or Username
                    </label>
                    <input type="text" name="email" class="form-control" placeholder="admin@awesomemall.com or admin"
                        required autocomplete="username" maxlength="255">
                </div>

                <div class="form-group">
                    <label class="form-label">
                        <i class="fas fa-lock me-1"></i> Password
                    </label>
                    <div class="password-toggle">
                        <input type="password" name="password" class="form-control" id="adminPassword"
                            placeholder="Enter admin password" required autocomplete="current-password" maxlength="255">
                        <i class="fas fa-eye toggle-icon" onclick="togglePassword('adminPassword', this)"></i>
                    </div>
                </div>

                <button type="submit" name="admin_login" class="btn-admin-login" <?php echo ($_SESSION['admin_login_attempts'] >= 5) ? 'disabled' : ''; ?>>
                    <i class="fas fa-sign-in-alt me-2"></i> Admin Login
                </button>
            </form>

            <div class="back-link">
                <a href="index.php">
                    <i class="fas fa-arrow-left me-1"></i> Back to Website
                </a>
            </div>

            <div class="security-badge">
                <i class="fas fa-shield-alt"></i>
                Secured with enterprise-grade encryption
            </div>
        </div>
    </div>

    <script>
        function togglePassword(inputId, icon) {
            const input = document.getElementById(inputId);
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }

        // Prevent form resubmission
        if (window.history.replaceState) {
            window.history.replaceState(null, null, window.location.href);
        }
    </script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
        crossorigin="anonymous"></script>
</body>

</html>