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

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

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

    try {
        if (!$input) {
            throw new Exception('Invalid request format');
        }

        $delivery_id = $delivery->createDelivery($user['id'], $input);

        // Notify all riders about the new delivery
        $riders = $auth->getUsersByRole('rider');
        foreach ($riders as $rider) {
            $message = "New delivery available from '{$input['pickup_location']}'.";
            $notification->create($rider['id'], $message, "/rider_dashboard");
        }

        jsonResponse([
            'success' => true,
            'message' => 'Delivery created successfully',
            'delivery_id' => $delivery_id
        ]);
    } catch (Exception $e) {
        error_log("Create delivery error: " . $e->getMessage()); // Log the error
        http_response_code(500); // Set HTTP status code to 500
        jsonResponse([
            'success' => false,
            'message' => $e->getMessage()
        ], 500);
    }
} else {
    jsonResponse([
        'success' => false,
        'message' => 'Method not allowed'
    ], 405);
}

?>