<?php
session_start();
require_once 'db/config.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];
    $password = $_POST['password'];

    if (empty($email) || empty($password)) {
        die('Please fill all required fields.');
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        die('Invalid email format.');
    }

    try {
        $pdo = db();

        $sql = "SELECT * FROM users WHERE email = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['user_role'] = $user['role'];

            // Merge guest cart with user cart
            $session_id = session_id();
            $merge_sql = "UPDATE cart SET user_id = ?, session_id = NULL WHERE session_id = ?";
            $merge_stmt = $pdo->prepare($merge_sql);
            $merge_stmt->execute([$user['id'], $session_id]);

            if ($user['role'] == 'admin') {
                $_SESSION['admin_logged_in'] = true;
                header("Location: admin/index.php");
            } elseif ($user['role'] == 'driver') {
                $driver_sql = "SELECT approval_status FROM drivers WHERE user_id = ?";
                $driver_stmt = $pdo->prepare($driver_sql);
                $driver_stmt->execute([$user['id']]);
                $driver = $driver_stmt->fetch();

                if ($driver) {
                    if ($driver['approval_status'] == 'approved') {
                        header("Location: driver/index.php");
                    } elseif ($driver['approval_status'] == 'pending') {
                        header("Location: driver_pending_approval.php");
                    } else { // rejected
                        header("Location: driver_rejected.php");
                    }
                } else {
                    // This case should ideally not happen if data is consistent
                    die('Driver profile not found.');
                }
            } else { // customer
                header("Location: index.php");
            }
            exit;
        } else {
            die('Invalid email or password.');
        }
    } catch (PDOException $e) {
        die("Could not connect to the database $dbname :" . $e->getMessage());
    }
}
?>