<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// === CONFIGURATION === //
$store_url = 'https://ferry-telecom.myshopify.com';
$api_version = '2023-04';
$access_token = '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';

// === Get JSON Webhook Payload === //
$raw_input = file_get_contents('php://input');
$data = json_decode($raw_input, true);

// Optional: Log payload for debug
// file_put_contents('webhook_log.txt', $raw_input . PHP_EOL, FILE_APPEND);

if (!isset($data['order_id'])) {
    http_response_code(400);
    die("Missing order_id in payload.");
}
$order_id = $data['order_id'];

// === Shopify API Helper === //
function shopify_api($method, $endpoint, $data = null) {
    global $store_url, $api_version, $access_token;

    $url = "$store_url/admin/api/$api_version/$endpoint";
    $headers = [
        "Content-Type: application/json",
        "Accept: application/json",
        "X-Shopify-Access-Token: $access_token"
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers
    ]);

    if ($data) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return [$code, json_decode($response, true), $response];
}

// === STEP 1: Get the fulfillment === //
[$code, $response, $raw] = shopify_api('GET', "orders/$order_id/fulfillments.json");

if ($code !== 200 || empty($response['fulfillments'])) {
    http_response_code(422);
    echo "ould not get fulfillments (HTTP $code)\n";
    echo $raw;
    exit;
}

$fulfillment_id = $response['fulfillments'][0]['id'];

// === STEP 2: Generate tracking info === //
$tracking_number = 'per Briefpost'; // This is fine
$tracking_url = "https://api.ferrytelecom.com/track/" . urlencode($tracking_number); // MUST be encoded

$payload = [
    'fulfillment' => [
        'tracking_info' => [
            'number' => $tracking_number,
            'company' => 'swisspost',
            'url' => $tracking_url
        ],
        'notify_customer' => false
    ]
];

[$update_code, $update_data, $update_raw] = shopify_api('POST', "fulfillments/$fulfillment_id/update_tracking.json", $payload);

if ($update_code >= 200 && $update_code < 300) {
    echo "acking added: $tracking_number (Fulfillment ID: $fulfillment_id)";
} else {
    http_response_code(500);
    echo "iled to update tracking (HTTP $update_code)\n";
    echo $update_raw;
}