<?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 = "";
  $orderID = [];
  $orderId[] = $orderSN;
  $result = TiktokgetOrderDetails($accessToken, $shopCipher, $orderId);
  if (empty($result['data']['orders'])) {
    continue;
  }

  $warehouseId = $result['data']['orders'][0]['warehouse_id'];
  $warehouseRespon = TiktokgetWarehouseList($accessToken, $shopCipher, $shopId);
  $warehouseList =  $warehouseRespon['data']['warehouse_list'];
  $zipcode = TiktokGetWarehouseZipcode($warehouseId, $warehouseList);
  $sql = "UPDATE orders_packing_queue SET zipcode = ? WHERE order_sn = ?";
  $stmt = $db->prepare($sql);
  $stmt->bind_param("ss", $zipcode, $orderSN);
  $stmt->execute();

  $sql = "UPDATE orders SET zipcode = ? WHERE order_sn = ?";
  $stmt = $db->prepare($sql);
  $stmt->bind_param("ss", $zipcode, $orderSN);
  $stmt->execute();
}


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 opq.processed = 0 and opq.zipcode = ''
          ORDER BY opq.id ASC";

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

  // 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;
}
