<?php
session_start([
    'cookie_httponly' => true,
    'cookie_secure' => isset($_SERVER['HTTPS']),
    'cookie_samesite' => 'Strict',
]);

require_once 'db.php';

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

$message = null;
$error = null;

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['login'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error = "Invalid CSRF token!";
    } else {
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';

        if (empty($email) || empty($password)) {
            $error = "All fields are required!";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($email) > 50) {
            $error = "Please enter a valid email (max 50 characters)!";
        } elseif (strlen($password) < 8) {
            $error = "Password must be at least 8 characters!";
        } else {
            $sql = "SELECT Mid, Email, MembersName, PassKey, MPid, status FROM members WHERE Email = ?";
            $stmt = mysqli_prepare($conn, $sql);

            if (!$stmt) {
                $error = "Database error: " . mysqli_error($conn);
            } else {
                mysqli_stmt_bind_param($stmt, "s", $email);
                mysqli_stmt_execute($stmt);
                $result = mysqli_stmt_get_result($stmt);

                if (mysqli_num_rows($result) === 1) {
                    $row = mysqli_fetch_assoc($result);

                    if ($row['status'] === 'not_verify') {
                        $error = "Please verify your email with the OTP sent to complete registration!";
                    } elseif ($row['status'] !== 'verify') {
                        $error = "Your account is not active. Please contact support.";
                    } elseif (!password_verify($password, $row['PassKey'])) {
                        $error = "Invalid email or password!";
                    } elseif ($row['MPid'] != 1) {
                        $error = "Access denied! Only admin users can login here.";
                        echo "Email" .$row['Email'] . " " . $row['MPid'];
                    } else {
                        session_regenerate_id(true);
                        $_SESSION['authenticated_user'] = true;
                        $_SESSION['mpid'] = $row['MPid'];

                        header("Location: /LoanApprovalPredction/Admin/index.php");
                        exit;
                    }
                } else {
                    $error = "Invalid email or password!";
                }
                mysqli_stmt_close($stmt);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login | LoanApprovalPredction</title>
    <link rel="icon" href="images/Approval.png" type="image/png">
    <link rel="stylesheet" href="CSS/style.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-gray-100 min-h-screen flex items-center justify-center font-sans">

    <div id="message" class="fixed top-4 left-1/2 transform -translate-x-1/2 z-50 max-w-md">
        <?php if (isset($message)): ?>
            <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded-lg fade-in">
                <p><?php echo htmlspecialchars($message); ?></p>
            </div>
        <?php elseif (isset($error)): ?>
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-lg fade-in">
                <p><?php echo htmlspecialchars($error); ?></p>
            </div>
        <?php endif; ?>
    </div>

    <div class="w-full max-w-md p-8 bg-white rounded-xl shadow-2xl fade-in">
        <div class="flex justify-center mb-6">
            <img src="images/Approval.png" alt="Logo" class="h-10">
        </div>
        <h2 class="text-xl font-semibold text-center text-gray-700 mb-4">Admin Login</h2>
        <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="space-y-5">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
            
            <div>
                <label for="email" class="block text-sm font-medium text-gray-700">Email</label>
                <input type="email" name="email" id="email" required class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring focus:ring-blue-200 focus:border-blue-400" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
            </div>

            <div>
                <label for="password" class="block text-sm font-medium text-gray-700">Password</label>
                <input type="password" name="password" id="password" required class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:ring focus:ring-blue-200 focus:border-blue-400">
            </div>

            <button type="submit" name="login" class="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 transition duration-200">Sign In</button>
        </form>
    </div>
</body>
</html>
