<?php
require 'vendor/autoload.php';
use Firebase\JWT\JWT;

// DoorDash credentials
$developer_id = '2335bf7c-574e-47db-b81b-9a44467b6f0a';
$key_id = 'c619bf51-1d2b-4a9d-a9fe-5b1775057eeb';
$signing_secret = 'q9BJxa1qVTqKLzcKOuGEc--PWfaHc_e8GAhp5096XIw';

// Base64url decode function
function base64url_decode($data) {
    $remainder = strlen($data) % 4;
    if ($remainder) {
        $padlen = 4 - $remainder;
        $data .= str_repeat('=', $padlen);
    }
    return base64_decode(strtr($data, '-_', '+/'));
}

// JWT payload
$payload = [
    "aud" => "doordash",
    "iss" => $developer_id,
    "kid" => $key_id,
    "exp" => time() + 1800, // 30 minutes
    "iat" => time()
];

// JWT header
$headers = [
    'alg' => 'HS256',
    'typ' => 'JWT',
    'dd-ver' => 'DD-JWT-V1'
];

// JWT encode (HS256) with decoded secret and custom header
$decoded_secret = base64url_decode($signing_secret);
$jwt = JWT::encode($payload, $decoded_secret, 'HS256', null, $headers);

// ... (rest of your code as before) ...
// Sample delivery data (replace with your real data)
$data = [
    "pickup_address" => [
        "city" => "San Francisco",
        "state" => "CA",
        "street" => "101 Howard Street",
        "unit" => "Apt 301",
        "zip_code" => "94105"
    ],
    "pickup_phone_number" => "+16505555555",
    "pickup_instructions" => "Ring the bell",
    "dropoff_address" => [
        "city" => "San Francisco",
        "state" => "CA",
        "street" => "901 Market Street",
        "unit" => "Suite #600",
        "zip_code" => "94105"
    ],
    "dropoff_instructions" => "Leave at the front desk",
    "customer" => [
        "phone_number" => "+16505555555",
        "first_name" => "Jane",
        "last_name" => "Goodall",
        "email" => "jane.goodall@megacorp.io"
    ],
    "order_value" => 1999,
    "pickup_time" => gmdate("Y-m-d\TH:i:s\Z", strtotime("+30 minutes")),
    "external_delivery_id" => uniqid("test_", true),
    "external_business_name" => "Test Restaurant",
    "items" => [
        [
            "name" => "Test Item",
            "quantity" => 1
        ]
    ],
    "allow_unattended_delivery" => true,
    "tip" => 0
];

// cURL request
$ch = curl_init('https://openapi.doordash.com/drive/v1/deliveries');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $jwt,
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$response = curl_exec($ch);
$error = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Output
echo "HTTP Code: $http_code<br>";
echo "Error: $error<br>";
echo "Response: $response<br>";
?>