<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$accessToken = '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';
$shop = 'aaodevus.myshopify.com';

$webhookContent = file_get_contents('php://input');
$orderData = json_decode($webhookContent, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "❌ Invalid JSON received: " . json_last_error_msg();
    exit;
}

$orderId = $orderData['id'] ?? 'UNKNOWN_ORDER_ID';
$formattedJson = json_encode($orderData, JSON_PRETTY_PRINT);
$logFile = __DIR__ . '/order_create_log.txt';
$logEntry = date('Y-m-d H:i:s') . " - Order ID: $orderId\n$formattedJson\n\n";
file_put_contents($logFile, $logEntry, FILE_APPEND);

if (strpos($orderId, 'gid://') !== 0) {
    $orderId = 'gid://shopify/Order/' . $orderId;
}

function callShopifyGraphQL($query, $variables = []) {
    global $accessToken, $shop;
    
    $ch = curl_init("https://$shop/admin/api/2024-04/graphql.json");
    $payload = json_encode(['query' => $query, 'variables' => $variables]);
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "X-Shopify-Access-Token: $accessToken",
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if ($response === false) {
        echo "❌ cURL Error: " . curl_error($ch);
        curl_close($ch);
        return false;
    }
    
    curl_close($ch);
    
    if ($httpCode !== 200) {
        echo "❌ HTTP Error: $httpCode\n";
        return false;
    }
    
    return json_decode($response, true);
}

// Add a small delay to allow Shopify's background worker to create fulfillment orders
sleep(3);

// Get the order details including fulfillment orders
$orderQuery = <<<GQL
query getOrder(\$id: ID!) {
  order(id: \$id) {
    id
    fulfillmentOrders(first: 10) {
      edges {
        node {
          id
          assignedLocation {
            location {
              id
            }
          }
          lineItems(first: 50) {
            edges {
              node {
                id
                lineItem {
                  variant {
                    id
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
GQL;

$orderResponse = callShopifyGraphQL($orderQuery, ['id' => $orderId]);
if ($orderResponse === false) {
    echo "❌ Failed to get order details\n";
    exit;
}

$fulfillmentOrders = $orderResponse['data']['order']['fulfillmentOrders']['edges'] ?? [];
if (empty($fulfillmentOrders)) {
    echo "⏳ No fulfillment orders found yet. This might be normal - Shopify creates fulfillment orders in the background.\n";
    echo "📋 Order webhook data received and logged. If fulfillment orders are not ready, the system will need to process this later.\n";
    exit;
}

// Map each fulfillment order to its assigned location
$fulfillmentLocationMap = [];
$allAssignedLocations = [];

foreach ($fulfillmentOrders as $edge) {
    $fulfillmentOrder = $edge['node'];
    $locationId = $fulfillmentOrder['assignedLocation']['location']['id'] ?? null;
    
    if ($locationId) {
        $fulfillmentLocationMap[] = $locationId;
        $allAssignedLocations[$locationId] = true;
        
        // Log the variants in this fulfillment order
        $lineItems = $fulfillmentOrder['lineItems']['edges'] ?? [];
        foreach ($lineItems as $lineEdge) {
            $variantId = $lineEdge['node']['lineItem']['variant']['id'] ?? null;
            if ($variantId) {
                echo "📦 Fulfillment Order: Variant $variantId → Location $locationId\n";
            }
        }
    }
}

if (empty($allAssignedLocations)) {
    echo "❌ No fulfillment location assignments found\n";
    exit;
}

// Check unique locations assigned for fulfillment
$uniqueLocations = array_keys($allAssignedLocations);
$locationCount = count($uniqueLocations);

echo "📍 Order has fulfillment orders assigned to " . $locationCount . " unique location(s):\n";
foreach ($uniqueLocations as $locationId) {
    echo "  - Location: $locationId\n";
}

// If all fulfillment orders are assigned to the same location, do nothing
if ($locationCount <= 1) {
    echo "✅ All fulfillment orders are assigned to the same location. No additional variants needed.\n";
    exit;
}

echo "⚡ Multiple fulfillment locations detected. Adding location-specific variants...\n";

// Map location IDs to the variant IDs you want to add per location
$locationToVariantMap = [
    // Replace with your actual location GIDs and variant GIDs:
    'gid://shopify/Location/83538051296' => 'gid://shopify/ProductVariant/47509476638944',
    'gid://shopify/Location/77130301664' => 'gid://shopify/ProductVariant/47508918534368',
    // Add more mappings as needed
];

// Get only the locations that are actually assigned in this order and have variant mappings
$locationsToProcess = array_intersect($uniqueLocations, array_keys($locationToVariantMap));

if (empty($locationsToProcess)) {
    echo "⚠️ No variant mappings found for any of the assigned fulfillment locations. Exiting.\n";
    foreach ($uniqueLocations as $loc) {
        echo "  - Assigned location: $loc (no mapping)\n";
    }
    exit;
}

// Start order edit
$beginMutation = <<<GQL
mutation orderEditBegin(\$id: ID!) {
  orderEditBegin(id: \$id) {
    calculatedOrder {
      id
    }
    userErrors {
      field
      message
    }
  }
}
GQL;

$beginResponse = callShopifyGraphQL($beginMutation, ['id' => $orderId]);
if ($beginResponse === false || !empty($beginResponse['errors']) || !empty($beginResponse['data']['orderEditBegin']['userErrors'])) {
    echo "❌ Failed to begin order edit:\n";
    if ($beginResponse !== false) print_r($beginResponse);
    exit;
}

$calculatedOrderId = $beginResponse['data']['orderEditBegin']['calculatedOrder']['id'];
echo "✅ Order edit started: $calculatedOrderId\n";

$addItemMutation = <<<GQL
mutation orderEditAddVariant(\$id: ID!, \$variantId: ID!, \$quantity: Int!) {
  orderEditAddVariant(id: \$id, variantId: \$variantId, quantity: \$quantity) {
    calculatedOrder {
      id
    }
    userErrors {
      field
      message
    }
  }
}
GQL;

// Add variants for each unique fulfillment location in the order
foreach ($locationsToProcess as $locId) {
    $variantIdToAdd = $locationToVariantMap[$locId];

    $addItemResponse = callShopifyGraphQL($addItemMutation, [
        'id' => $calculatedOrderId,
        'variantId' => $variantIdToAdd,
        'quantity' => 1
    ]);

    if ($addItemResponse === false || !empty($addItemResponse['errors']) || !empty($addItemResponse['data']['orderEditAddVariant']['userErrors'])) {
        echo "❌ Failed to add variant for location $locId:\n";
        if ($addItemResponse !== false) print_r($addItemResponse);
        continue;
    }

    echo "✅ Added variant $variantIdToAdd for location $locId\n";
}

// Commit order edit
$commitMutation = <<<GQL
mutation orderEditCommit(\$id: ID!) {
  orderEditCommit(id: \$id) {
    order {
      id
    }
    userErrors {
      field
      message
    }
  }
}
GQL;

$commitResponse = callShopifyGraphQL($commitMutation, ['id' => $calculatedOrderId]);
if ($commitResponse === false || !empty($commitResponse['errors']) || !empty($commitResponse['data']['orderEditCommit']['userErrors'])) {
    echo "❌ Failed to commit order edit:\n";
    if ($commitResponse !== false) print_r($commitResponse);
    exit;
}

echo "✅ Order edit committed successfully\n";
?>