<?php
session_start();
include_once('../../includes/db.php');

if (!isset($_SESSION['driver_logged_in'])) {
    header("Location: driver_login.php");
    exit;
}

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

    $valid_statuses = ['shipped', 'delivered'];

    if (!in_array($new_status, $valid_statuses)) {
        header("Location: driver_orders.php?error=Invalid status value.");
        exit;
    }

    // Verify order is assigned to this driver
    $stmt = $conn->prepare("SELECT id FROM orders WHERE id = ? AND driver_id = ?");
    $stmt->bind_param("ii", $order_id, $driver_id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 0) {
        $stmt->close();
        header("Location: driver_orders.php?error=You are not allowed to update this order.");
        exit;
    }
    $stmt->close();

    // Update status
    $stmt = $conn->prepare("UPDATE orders SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $new_status, $order_id);

    if ($stmt->execute()) {
        $stmt->close();
        header("Location: driver_orders.php?success=Order status updated.");
        exit;
    } else {
        $stmt->close();
        header("Location: driver_orders.php?error=Failed to update order.");
        exit;
    }
} else {
    header("Location: driver_orders.php?error=Invalid request.");
    exit;
}
