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

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

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

    $allowed_statuses = ['preparing', 'out for delivery', 'delivered', 'cancelled'];

    if (empty($order_id) || empty($status) || !in_array($status, $allowed_statuses)) {
        header('Location: index.php?error=Invalid input.');
        exit;
    }

    try {
        $pdo = db();

        // Security Check: Verify the order is assigned to this driver
        $check_stmt = $pdo->prepare(
            'SELECT o.id FROM orders o ' .
            'JOIN driver_assignments da ON o.id = da.order_id ' .
            'WHERE o.id = ? AND da.driver_id = ?'
        );
        $check_stmt->execute([$order_id, $driver_id]);
        $assignment = $check_stmt->fetch();

        if (!$assignment) {
            header('Location: index.php?error=You are not authorized to update this order.');
            exit;
        }

        // Update the order status
        $update_stmt = $pdo->prepare('UPDATE orders SET status = ? WHERE id = ?');
        
        if ($update_stmt->execute([$status, $order_id])) {
            header('Location: index.php?success=Order status updated successfully.');
            exit;
        } else {
            header('Location: index.php?error=Failed to update order status.');
            exit;
        }
    } catch (PDOException $e) {
        header('Location: index.php?error=A database error occurred.');
        exit;
    }
} else {
    header('Location: index.php');
    exit;
}
?>