<?php
require_once '../db/config.php';

session_start();
// Check if the user is logged in as an admin
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['order_id']) && isset($_POST['driver_id'])) {
    $order_id = $_POST['order_id'];
    $driver_id = $_POST['driver_id'];

    if (!empty($order_id) && !empty($driver_id)) {
        try {
            $pdo = db();

            // Check if an assignment already exists
            $check_stmt = $pdo->prepare("SELECT id FROM driver_assignments WHERE order_id = ?");
            $check_stmt->execute([$order_id]);

            if (!$check_stmt->fetch()) {
                // Create new assignment
                $insert_stmt = $pdo->prepare("INSERT INTO driver_assignments (order_id, driver_id) VALUES (?, ?)");
                $insert_stmt->execute([$order_id, $driver_id]);

                // Update order status
                $update_stmt = $pdo->prepare("UPDATE orders SET status = 'Confirmed' WHERE id = ?");
                $update_stmt->execute([$order_id]);
            }
        } catch (PDOException $e) {
            // Log error or handle it appropriately
            die("Database error: " . $e->getMessage());
        }
    }
}

header('Location: orders.php');
exit;
?>