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

if (!isset($_SESSION['driver_id'])) {
    header('Location: /driver/login.php');
    exit;
}

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

    if (empty($order_id)) {
        header('Location: index.php?error=Invalid order.');
        exit;
    }

    $pdo = db();

    try {
        $pdo->beginTransaction();

        // Check if the order is still available
        $check_stmt = $pdo->prepare('SELECT driver_id FROM orders WHERE id = ? AND status = \'ready for pickup\'');
        $check_stmt->execute([$order_id]);
        $order = $check_stmt->fetch();

        if (!$order || $order['driver_id'] !== null) {
            header('Location: index.php?error=Order is no longer available.');
            $pdo->rollBack();
            exit;
        }

        // Assign driver and update status
        $update_stmt = $pdo->prepare('UPDATE orders SET driver_id = ?, status = \'out for delivery\' WHERE id = ?');
        $update_stmt->execute([$driver_id, $order_id]);

        // Create driver assignment record
        $assign_stmt = $pdo->prepare('INSERT INTO driver_assignments (order_id, driver_id) VALUES (?, ?)');
        $assign_stmt->execute([$order_id, $driver_id]);

        $pdo->commit();

        header('Location: index.php?success=Order accepted successfully!');
        exit;

    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        // Log the error properly in a real application
        header('Location: index.php?error=An error occurred. Please try again.');
        exit;
    }
} else {
    header('Location: index.php');
    exit;
}
