<?php
include(__DIR__ . '/../db_connect.php');
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = mysqli_real_escape_string($conn, $_POST['form_email']);
    $password = mysqli_real_escape_string($conn, $_POST['form_password']);

    // Default redirect path
    $redirect = $_POST['redirect'] ?? '/carrentalone/frontend/account.php';

    $query = "SELECT * FROM users WHERE email='$email' LIMIT 1";
    $result = mysqli_query($conn, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $user = mysqli_fetch_assoc($result);

        if ($password === $user['password']) { // plain text comparison
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['first_name']; // ✅ fixed

            // ✅ Redirect immediately with PHP (no JS)
            header("Location: $redirect");
            exit();
        } else {
            echo "<script>alert('Invalid password'); window.location.href='../frontend/login.php';</script>";
        }
    } else {
        echo "<script>alert('User not found'); window.location.href='../frontend/login.php';</script>";
    }
}
?>
