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

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

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

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

    try {
        $pdo = db();

        // Check if driver already exists
        $sql = "SELECT id FROM drivers WHERE email = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            die('Email already exists.');
        }

        // Insert into drivers table
        $password_hash = password_hash($password, PASSWORD_BCRYPT);
        $sql = "INSERT INTO drivers (full_name, email, password_hash, phone_number, vehicle_details, approval_status) VALUES (?, ?, ?, ?, ?, 'pending')";
        $stmt = $pdo->prepare($sql);
        
        if ($stmt->execute([$full_name, $email, $password_hash, $phone_number, $vehicle_details])) {
            // Redirect to a pending approval page
            header("Location: driver_pending_approval.php");
            exit;
        } else {
            die("Error: Could not execute the query.");
        }
    } catch (PDOException $e) {
        die("Could not connect to the database: " . $e->getMessage());
    }
}
?>