<?php
// --- LOGIC BLOCK: All PHP processing must happen before any HTML is sent ---
require_once 'includes/db.php';

$error_msg = '';

// If a user is already logged in, redirect them immediately to their respective dashboard
if (isset($_SESSION['user_id']) && isset($_SESSION['user_role'])) {
    if ($_SESSION['user_role'] == 'admin') {
        header("Location: admin/dashboard.php");
    } elseif (in_array($_SESSION['user_role'], ['tour_partner', 'hotel_partner'])) {
        header("Location: partner/");
    } else {
        header("Location: dashboard/");
    }
    exit();
}

// Process the form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $login_type = $_POST['login_type'] ?? 'customer'; // Identifies if the form is from /admin or public

    $stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password'])) {
            // --- ROLE-BASED LOGIN LOGIC ---
            
            // 1. Handle Admin Login Attempts
            if ($user['role'] == 'admin') {
                if ($login_type === 'admin') { // Admin is using the correct form from /admin/index.php
                    if ($user['status'] == 'active') {
                        session_regenerate_id(true);
                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['user_name'] = $user['full_name'];
                        $_SESSION['user_role'] = $user['role'];
                        $_SESSION['admin_logged_in'] = true;
                        header("Location: admin/dashboard.php");
                        exit();
                    } else {
                        $error_msg = "Your admin account is not active.";
                    }
                } else { // Admin is trying to use the public form
                    $error_msg = "Administrators must use the dedicated admin login page.";
                }
            }
            // 2. Handle Customer/Partner Login Attempts
            else {
                if ($login_type === 'admin') { // A non-admin is trying to use the admin form
                    header("Location: admin/index.php?error=not_admin");
                    exit();
                }

                if ($user['status'] == 'active') {
                    session_regenerate_id(true);
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['user_name'] = $user['full_name'];
                    $_SESSION['user_role'] = $user['role'];
                    if (in_array($user['role'], ['tour_partner', 'hotel_partner'])) {
                        header("Location: partner/");
                    } else { // Customer
                        header("Location: dashboard/");
                    }
                    exit();
                } elseif ($user['status'] == 'pending') {
                    $error_msg = "Your partner account is still pending approval.";
                } else { // Suspended
                    $error_msg = "Your account has been suspended. Please contact support.";
                }
            }
        }
    }
    
    if (empty($error_msg)) {
        $error_msg = "Invalid email or password. Please try again.";
    }
}

// --- PRESENTATION BLOCK ---
include 'includes/header.php';
?>
<div class="container my-5">
    <div class="row justify-content-center">
        <div class="col-md-5">
            <div class="card shadow-lg">
                <div class="card-body p-5">
                    <h2 class="text-center mb-4">Login</h2>
                    <?php if ($error_msg): ?>
                        <div class="alert alert-danger"><?php echo $error_msg; ?></div>
                    <?php endif; ?>
                    <form method="POST" action="login.php" novalidate>
                        <div class="mb-3"><label for="email" class="form-label">Email Address</label><input type="email" class="form-control" id="email" name="email" required></div>
                        <div class="mb-3"><label for="password" class="form-label">Password</label><input type="password" class="form-control" id="password" name="password" required></div>
                        <div class="text-end mb-3"><a href="forgot-password.php">Forgot Password?</a></div>
                        <div class="d-grid"><button type="submit" class="btn btn-primary">Login</button></div>
                        <p class="text-center mt-3">Don't have an account? <a href="register.php">Register as Customer</a></p>
                        <p class="text-center mt-2"><a href="partner-register.php">Register as Partner</a></p>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include 'includes/footer.php'; ?>
