<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Delivery.php';

$auth = new Auth();
$user = $auth->requireAuth();
$delivery = new Delivery();

if ($user['role'] !== 'rider') {
    jsonResponse(['success' => false, 'message' => 'Unauthorized'], 403);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $delivery_id = $input['delivery_id'] ?? null;
    $status = $input['status'] ?? null;

    if (!$delivery_id || !$status) {
        jsonResponse(['success' => false, 'message' => 'Delivery ID and status are required'], 400);
    }

    try {
        // The updateStatus method should verify the rider owns the delivery
        $success = $delivery->updateStatus($delivery_id, $status, $user['id']); // This method should return true/false
        if ($success) {
            $updated_deliveries = $delivery->getRiderDeliveries($user['id']); // Fetch the updated list
            jsonResponse(['success' => true, 'message' => 'Status updated', 'deliveries' => $updated_deliveries]);
        } else {
            jsonResponse(['success' => false, 'message' => 'Failed to update status'], 400);
        }
    } catch (Exception $e) {
        jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
    }
}
?>