<?php
// Start session securely — must be at the very top
session_start([
    'cookie_httponly' => true,
    'cookie_secure' => isset($_SERVER['HTTPS']),
    'cookie_samesite' => 'Strict',// Assuming MPid is set to 2 for permanent members
]);

require_once 'db.php'; // Your database connection file

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

$message = null;
$error = null;

// Show registration success message (if any)
if (isset($_SESSION['registration_success'])) {
    $message = $_SESSION['registration_success'];
    unset($_SESSION['registration_success']);
}

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

        // Validate input
        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 {
            // Prepare SQL statement
            $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'])) {
                        // Successful login
                        session_regenerate_id(true); // Prevent session fixation
                        $_SESSION['authenticated_user'] = true;
                        $_SESSION['Mid'] = $row['Mid'];
                        $_SESSION['email'] = $row['Email'];
                        $_SESSION['name'] = $row['MembersName'];
                        $_SESSION['mpid'] = $row['MPid'];

                        if ($row['MPid'] == 1) {
                            header("Location: /LoanApprovalPredction/Admin/index.php");
                            exit;
                        } else {
                            header("Location: /LoanApprovalPredction/Members/index.php");
                            exit;
                        }
                    } else {
                        $error = "Invalid email or password!";
                    }
                } 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">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>LoanApprovalPredction - Login</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); }
        }
        .btn-primary {
            transition: background-color 0.3s ease, transform 0.2s ease;
        }
        .btn-primary:hover {
            background-color: #1e40af;
            transform: translateY(-2px);
        }
        .form-input {
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }
        .form-input:focus {
            outline: none;
            border-color: #2563eb;
            box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.5);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-gray-100 min-h-screen flex items-center justify-center font-sans">
    <!-- Message Display -->
    <div id="message" class="fixed top-4 left-1/2 transform -translate-x-1/2 hidden 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 flex items-center fade-in">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                </svg>
                <p><?php echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8'); ?></p>
            </div>
        <?php elseif (isset($error)): ?>
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-lg flex items-center fade-in">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                <p><?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?></p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Login Form -->
    <div class="w-full max-w-md p-8 bg-white rounded-xl shadow-2xl fade-in">
        <div class="flex items-center justify-center mb-6">
            <img src="images/Approval.png" alt="LoanApprovalPredction Logo" class="h-10 mr-2">
            
        </div>
        <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" id="login-form" class="space-y-5">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">
            <div class="flex flex-col">
                <label for="email" class="text-sm font-medium text-gray-700">Email</label>
                <input type="email" id="email" name="email" placeholder="Enter your email" value="<?php echo htmlspecialchars($_POST['email'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="form-input w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-blue-500" required aria-describedby="email-error">
                <span id="email-error" class="text-red-500 text-sm mt-1"></span>
            </div>
            <div class="flex flex-col">
                <label for="password" class="text-sm font-medium text-gray-700">Password</label>
                <input type="password" id="password" name="password" placeholder="Enter your password" class="form-input w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-blue-500" required aria-describedby="password-error">
                <span id="password-error" class="text-red-500 text-sm mt-1"></span>
            </div>
            <button type="submit" name="login" class="btn-primary w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Sign In</button>
            <p class="text-center text-gray-600 mt-4">Don't have an account? <a href="/LoanApprovalPredction/register.php" class="text-blue-600 hover:underline" aria-label="Go to register page">Register</a></p>
        </form>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const form = document.getElementById("login-form");
            const emailInput = document.getElementById("email");
            const passwordInput = document.getElementById("password");
            const messageElement = document.getElementById("message");

            // Show message if present
            <?php if (isset($message) || isset($error)): ?>
                messageElement.classList.remove("hidden");
                setTimeout(() => {
                    messageElement.classList.add("hidden");
                }, 5000);
            <?php endif; ?>

            // Real-time validation
            emailInput.addEventListener("input", function() {
                const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z.-]+\.[a-zA-Z]{2,}$/;
                const errorSpan = document.getElementById("email-error");
                if (emailRegex.test(emailInput.value) && emailInput.value.length <= 50) {
                    emailInput.classList.remove("border-red-500");
                    emailInput.classList.add("border-green-500");
                    errorSpan.textContent = "";
                } else {
                    emailInput.classList.remove("border-green-500");
                    emailInput.classList.add("border-red-500");
                    errorSpan.textContent = "Please enter a valid email (max 50 characters)";
                }
            });

            passwordInput.addEventListener("input", function() {
                const errorSpan = document.getElementById("password-error");
                if (passwordInput.value.length >= 8) {
                    passwordInput.classList.remove("border-red-500");
                    passwordInput.classList.add("border-green-500");
                    errorSpan.textContent = "";
                } else {
                    passwordInput.classList.remove("border-green-500");
                    passwordInput.classList.add("border-red-500");
                    errorSpan.textContent = "Password must be at least 8 characters";
                }
            });

            // Form submission validation
            form.addEventListener("submit", function(e) {
                if (
                    emailInput.classList.contains("border-red-500") ||
                    passwordInput.classList.contains("border-red-500")
                ) {
                    e.preventDefault();
                    alert("Please correct the highlighted fields before submitting.");
                }
            });
        });
    </script>
</body>
</html>