<?php
set_time_limit(300);
ini_set('max_execution_time', 300);
error_reporting(E_ALL);
require_once('includes/load.php');
$row = getTikTokShopsAndPerformAction();
$orderArray = [];
$shipmentsArray = [];
$shopArray = [];
$platform = 2;
$orderProses = 0;
$nextPage = '';
if (isset($_GET['next_page'])) {
    $nextPage = $_GET['next_page'];
}

$execution_time = 0;
foreach ($row as $item) {
    $orderResponse = TiktokGetOrdersNextPage($item['access_token'], $item['shop_cipher'], 10, $nextPage);
    if (isset($orderResponse['error'])) {
        echo "Error: " . $orderResponse['error']['message'];
        die();
    }
    $next_page_token = '';
    if (isset($orderResponse['data']['next_page_token'])) {
        $next_page_token = $orderResponse['data']['next_page_token'];
    } else {
        $next_page_token = '';
    }

    $shopArray[] = [
        'shop_name' => $item['shop_name'],
        'order_total_count' => $orderResponse['data']['total_count']
    ];

    if ($orderResponse['data']['total_count'] == 0) {
        continue;
    }
    // echo "total order " . $orderResponse['data']['total_count'] . "\n";
    $start_time = microtime(true);
    foreach ($orderResponse['data']['orders'] as $order_item) {
        $orderID = [];
        $accessToken = $item['access_token'];
        $shopCipher = $item['shop_cipher'];
        $shopId = $item['shop_id'];
        $orderId[] = $order_item['id'];

        $result = TiktokgetOrderDetails($accessToken, $shopCipher, $orderId);
        if (empty($result['data']['orders'])) {
            // echo "Error: Order ID $orderId[0] Shop ID $shopId TiktokgetOrderDetails not found";
            // echo "\n";
            $orderArray[] = $order_item['id'] . " - 1";
            continue;
        }
        $packageId = $order_item['packages'][0]['id'];
        $warehouseId = $order_item['warehouse_id'];
        if ($warehouseId === null || $warehouseId === '') {
            // echo "Error: warehouseId not found for Order ID $orderId[0] Shop ID $shopId";
            // echo "\n";
            $orderArray[] = $order_item['id'] . " - 2";
            continue;
        }
        $warehouseRespon = TiktokgetWarehouseList($accessToken, $shopCipher, $shopId);
        $warehouseList =  $warehouseRespon['data']['warehouse_list'];
        $zipcode = TiktokGetWarehouseZipcode($warehouseId, $warehouseList);
        if ($zipcode === null) {
            // echo "<pre>";
            // print_r($warehouseList);
            // echo "</pre>";
            // echo "Error: Zipcode not found for warehouse ID $warehouseId Order ID $orderId[0] Shop ID $shopId";
            // echo "\n";
            $orderArray[] = $order_item['id'] . " - 3";
            continue;
        }
        TiktokInsertOrderData($result, $shopId);

        $checkQuery = "SELECT COUNT(*) AS count FROM queue_shipment WHERE order_sn = '" . $db->escape($order_item['id']) . "'";

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

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

            if ($checkRow['count'] == 0) {
                // Jika count = 0
                $orderProses++;
                $orderArray[] = $order_item['id'] . " - 0";
                $shipmentsArray[] = [
                    'shopId' => $shopId,
                    'accessToken' => $accessToken,
                    'refreshToken' => '',
                    'orderSN' => $order_item['id'],
                    'errorJson' => '{}',
                    'platform' => $platform,
                    'packageId' => $packageId,
                    'zipcode' =>  $zipcode,
                    'trackingNumber' => '',
                    'shopCipher' => $shopCipher
                ];
            } else {
                // Jika count > 0
                $orderArray[] = $order_item['id'] . " - 4";
            }
        }
        $result->free();
        // $ShipPackage = TiktokShipPackage($accessToken, $shopCipher, $shopId, $packageId);
        // $resultAWBPL = TikTokGetShippingDocuments($accessToken, $packageId, $shopCipher, $shopId, 3);
        // $nameDownload = 'storage/awb/awb-' . $orderId[0] . '.pdf';
        // downloadFileFromUrl($resultAWBPL['data']['doc_url'], $nameDownload);
        // $response = TiktokGetFulfillmentDetails($accessToken, $shopCipher, $shopId, $packageId);
        // $trackingNumber = $response['data']['tracking_number'];
        // repositoryOrdersPackingQueue($orderId[0], $zipcode, $nameDownload, 0, $trackingNumber);
    }


    $end_time = microtime(true);  // Waktu selesai
    $execution_time = $end_time - $start_time;  // Waktu yang dibutuhkan untuk memproses order

    // echo "Proses selesai dalam: " . $execution_time . " detik Proses Order $orderProses \n";
}

$isInserted = insertQueueShipmentTiktokMulti($shipmentsArray);
echo json_encode([
    'execution_time' => $execution_time, // Total waktu eksekusi
    'nextPage' => $next_page_token,             // Halaman berikutnya (jika ada)
    'order' => $orderProses,             // Halaman berikutnya (jika ada)
    'multiInsert' => $isInserted,             // Halaman berikutnya (jika ada)
    'orderItem' => $orderArray,
    'shop' => $shopArray
]);
