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

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

    if (empty($email) || empty($password)) {
        header("Location: login.php?error=Please fill all fields");
        exit;
    }

    try {
        $pdo = db();

        $sql = "SELECT id, full_name, email, password_hash, approval_status FROM drivers WHERE email = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$email]);
        $driver = $stmt->fetch();

        if ($driver) {
            if ($driver['approval_status'] === 'pending') {
                header("Location: ../driver_pending_approval.php");
                exit;
            } elseif ($driver['approval_status'] === 'rejected') {
                header("Location: ../driver_rejected.php");
                exit;
            }

            if ($driver['approval_status'] === 'approved' && password_verify($password, $driver['password_hash'])) {
                $_SESSION['driver_id'] = $driver['id'];
                $_SESSION['driver_name'] = $driver['full_name'];
                header("Location: index.php");
                exit;
            } else {
                header("Location: login.php?error=Invalid credentials");
                exit;
            }
        } else {
            header("Location: login.php?error=Invalid credentials");
            exit;
        }
    } catch (PDOException $e) {
        header("Location: login.php?error=A database error occurred");
        exit;
    }
}
?>