<?php
set_time_limit(120);
ini_set('max_execution_time', 120);
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('includes/load.php');
$startTime = microtime(true);
$platform = 2;  // Platform ID yang ingin dipilih

// Query yang sudah diformat dengan prepared statement
$sql = "
SELECT 
    MAX(id) AS id, 
    access_token, 
    shop_id, 
    refresh_token, 
    order_sn,
    shop_cipher,
    packageId,
    tracking_number,
    zipcode
FROM 
    queue_shipment 
WHERE 
    platform_id = ? 
    AND flag_delete = 0 
GROUP BY 
    order_sn, access_token, shop_id, refresh_token, shop_cipher, packageId, tracking_number, zipcode
ORDER BY 
    id ASC
LIMIT 10;
";

// Menyiapkan query
$stmt = $db->prepare($sql);

// Memastikan koneksi berhasil dan query berhasil disiapkan
if ($stmt === false) {
  die('Query preparation failed: ' . $db->error);
}

// Mengikat parameter platform_id sebagai integer
$stmt->bind_param('i', $platform);

// Eksekusi query
$stmt->execute();

// Mengambil hasil query
$result = $stmt->get_result();

// Array untuk menyimpan data
$data = array();

// Memeriksa apakah ada hasil yang ditemukan
if ($result->num_rows > 0) {
  // Proses setiap baris data
  while ($row = $result->fetch_assoc()) {
    $accessToken = $row['access_token'];
    $refreshToken = $row['refresh_token'];
    $shopCipher = $row['shop_cipher'];
    $shopId = $row['shop_id'];
    $orderId = $row['order_sn'];
    $packageId = $row['packageId'];
    $trackingNumber = $row['tracking_number'];
    $zipcode = $row['zipcode'];
    $id = $row['id'];

    echo "processing order: $orderId\n";

    $query = "UPDATE queue_shipment SET flag_delete = 1 WHERE order_sn = '" . $db->escape($orderId) . "'";
    $db->query($query);

    $checkQuery = "SELECT COUNT(*) AS count FROM orders_packing_queue WHERE order_sn = '" . $db->escape($orderId) . "'";

    $result = $db->query($checkQuery);

    // Cek apakah query berhasil
    if ($result) {
      $checkRow = $result->fetch_assoc();

      if ($checkRow['count'] != 0) {
        continue;
      }
    }

    $ShipPackage = TiktokShipPackage($accessToken, $shopCipher, $shopId, $packageId);



    $resultAWBPL = TikTokGetShippingDocuments($accessToken, $packageId, $shopCipher, $shopId, 3);
    $nameDownload = 'storage/awb/awb-' . $orderId . '.pdf';
    if (empty($resultAWBPL['data']['doc_url'])) {
      $errorJson = json_encode($resultAWBPL);
      insertQueueShipmentTiktok(
        $shopId,
        $accessToken,
        $refreshToken,
        $orderId,
        $errorJson,
        $platform,
        $shopCipher,
        $packageId,
        $trackingNumber,
        $zipcode
      );
      continue;
    }
    if (empty($trackingNumber)) {
      $response = TiktokGetFulfillmentDetails($accessToken, $shopCipher, $shopId, $packageId);
      if (empty($response['data']['tracking_number'])) {
        $errorJson = json_encode($response);
        insertQueueShipmentTiktok(
          $shopId,
          $accessToken,
          $refreshToken,
          $orderId,
          $errorJson,
          $platform,
          $shopCipher,
          $packageId,
          $trackingNumber,
          $zipcode
        );
        continue;
      }
      $trackingNumber = $response['data']['tracking_number'];
    }
    downloadFileFromUrl($resultAWBPL['data']['doc_url'], $nameDownload);

    // Catat waktu selesai
    $endTime = microtime(true);

    // Hitung durasi eksekusi
    $executionTime = $endTime - $startTime;
    echo "Execution Time: " . round($executionTime, 4) . " seconds\n";
    echo "finnis order: $orderId\n";
    // repositoryOrdersPackingQueue($orderId, $zipcode, $nameDownload, 0, $trackingNumber);
  }
}
