<?php
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
require_once('includes/load.php');
$platform = 2;
$issue = "";
$datas = getOrdersByDate();
$data = array();
foreach ($datas as $row) {
  $shopId = $row['shop_id'];
  $OrderQueueId = $row['id'];
  $accessToken = $row['access_token'];
  $refreshToken = $row['refresh_token'];
  $orderSN = $row['order_sn'];
  $orderStatus = $row['order_status'];
  $resi = $row['resi'];
  $awbUrl = $row['awb_url'];
  $rootPath = $_SERVER['DOCUMENT_ROOT'];
  $shopCipher = $row['shop_cipher'];
  $packageId = "";

  if (!isPdfValid($rootPath . "/" . $row['awb_url'])) {
    $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);
    $nameDownload = 'storage/awb/awb-' . $orderSN . '.pdf';
    downloadFileFromUrl($resultAWBPL['data']['doc_url'], $nameDownload);
    $data[] = ["order" => $orderSN, "url" => $awbUrl];
  }

  // if (empty($resi)) {
  //   // Mendapatkan tracking number dari API
  //   $response = TiktokGetFulfillmentDetails($accessToken, $shopCipher, $shopId, $packageId);

  //   // Pastikan 'response' dan 'tracking_number' ada dalam hasil
  //   if (isset($response['data']['tracking_number'])) {
  //     $trackingNumber = $response['data']['tracking_number'];

  //     $sql = "UPDATE orders_packing_queue SET resi = ? WHERE order_sn = ?";
  //     $stmt = $db->prepare($sql);
  //     $stmt->bind_param("ss", $trackingNumber, $orderSN);
  //     $stmt->execute();

  //     // Menutup prepared statement
  //     $stmt->close();
  //   } else {
  //     // Tangani jika tracking_number tidak ada dalam response
  //     // Misalnya, Anda bisa mencatat kesalahan atau memberi pesan kepada pengguna
  //     $issue = "Tracking number not found for order SN: $orderSN";
  //   }
  // }
}


echo json_encode(["message" => "Successfully", "data" => $data, 'issue' => $issue]);


function getOrdersByDate()
{
  global $db;
  // Get the current date in 'YYYY-MM-DD' format
  $currentDate = date('Y-m-d');

  // SQL query to select records for the current date
  $sql = "SELECT s.access_token, s.refresh_token, s.shop_cipher, s.shop_id, opq.awb_url, opq.order_sn, o.order_status, opq.id, opq.resi 
          FROM orders_packing_queue opq 
          JOIN orders o ON opq.order_sn = o.order_sn 
          JOIN shop s ON o.shop_id = s.shop_id 
          WHERE s.platform_id = 2 AND DATE(opq.created_at) = ? 
          ORDER BY opq.id ASC";

  // Prepare the statement
  $stmt = $db->prepare($sql);

  // Bind the parameter (current date) to the query
  $stmt->bind_param('s', $currentDate);  // 's' is for string type

  // Execute the query
  $stmt->execute();

  // Get the result
  $result = $stmt->get_result();

  // Initialize an empty array to store the data
  $data = array();

  // Check if there are any rows returned
  if ($result->num_rows > 0) {
    // Fetch the data into the array
    while ($row = $result->fetch_assoc()) {
      $data[] = $row;
    }
  }

  // Return the data as an array
  return $data;
}
