<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('includes/load.php');

$row = getTikTokShopsAndPerformAction();
foreach ($row as $item) {
  $shopId = $item['shop_id'];
  $orderIDs = getOrderIDs($shopId, "PL20241211958Y6SFZ");
  // var_dump($orderIDs);
  $accessToken = $item['access_token'];
  $shopCipher = $item['shop_cipher'];
  foreach ($orderIDs as $orderId) {
    $resi = $orderId['resi'];
    $orderSN = $orderId['order_sn'];
    $orderId = [];
    $orderId[] = $orderSN;
    $result = TiktokgetOrderDetails($accessToken, $shopCipher, $orderId);
    $packageId = $result['data']['orders'][0]['packages'][0]['id'];
    $resultAWBPL = TikTokGetShippingDocumentsV2($accessToken, $packageId, $shopCipher, $shopId, "SHIPPING_LABEL_AND_PACKING_SLIP", "A6", $resi);
    echo $resultAWBPL['data']['doc_url'];
    echo "</br>";
    echo $resultAWBPL['data']['tracking_number'];
    echo "</br>";
    echo $resi;
    echo "</br>";
    echo "</br>";
    $nameDownload = 'storage/awb/awb-' . $orderSN . '.pdf';
    sendFileFromAPI("https://test.wiselie.co.id/upload_url_api.php", $resultAWBPL['data']['doc_url'], $nameDownload, 5);
  }
}
function getOrderIDs($shopId, $plcode)
{
  global $db;

  // Safely escape the parameters for debugging
  $escapedShopId = $db->escape($shopId);

  // If multiple PL codes are provided, split them and escape each one
  $plcodesArray = explode(',', $plcode);
  $escapedPlcodes = array_map(function ($code) use ($db) {
    return "'" . $db->escape($code) . "'";  // Escape each code and wrap in quotes
  }, $plcodesArray);

  // Join the escaped PL codes with commas
  $escapedPlcodesString = implode(',', $escapedPlcodes);

  // Directly inject the escaped values into the query for debugging
  $query = "
    SELECT o.order_sn, opq.resi
    FROM orders o
    JOIN packing_list pl ON o.id_packing_list = pl.id
    JOIN shop s ON s.shop_id = o.shop_id
    JOIN orders_packing_queue opq ON opq.order_sn = o.order_sn
    WHERE pl.code IN ($escapedPlcodesString) 
    AND s.platform_id = 2
    AND s.shop_id = '$escapedShopId'
  ";

  // Output the query for debugging
  // echo "Query: $query\n";  // This will print the query and allow you to inspect it

  $result = $db->query($query);  // Use query() directly for debugging

  $orderIDs = [];

  // Combine order_sn and resi in a single array for each row
  while ($row = $result->fetch_assoc()) {
    $orderIDs[] = [
      'order_sn' => $row['order_sn'],
      'resi' => $row['resi']
    ];
  }
  return $orderIDs;
}

function sendFileFromAPI($apiUrl, $fileUrl, $savePath, $retries)
{
  // Prepare POST data
  $postData = [
    'url'  => $fileUrl,
    'path' => $savePath
  ];

  // Retry logic
  for ($i = 0; $i <= $retries; $i++) {
    // Initialize cURL session
    $ch = curl_init();

    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));  // Send data as POST form data
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Return response as string

    // Disable SSL verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // Disable SSL certificate verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // Disable host verification

    // Execute cURL request
    $response = curl_exec($ch);

    // Check if there was an error
    if ($response === false) {
      // If an error occurs and retries are available
      if ($i < $retries) {
        // Log the error and retry
        echo "Error while making API download request: " . curl_error($ch) . ". Retrying...\n";
        sleep($i * 20); // Increase the delay each retry
        continue;
      }
      // If no retries are left, return the error
      return "Error after retries: " . curl_error($ch);
    }

    // Close cURL session
    curl_close($ch);

    // Return the response from the API
    return $response;
  }

  return null; // In case retries exceeded without success
}
