<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(120);
ini_set('max_execution_time', 120);
require_once('includes/load.php');
$platform = 1;
$sql = "SELECT id, access_token, shop_id, refresh_token, order_sn FROM queue_shipment WHERE platform_id = $platform and flag_delete = 0 order by id asc limit 4";
$stmt = $db->prepare($sql);
$stmt->execute();
$data = array();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $db->query("UPDATE queue_shipment SET flag_delete = 1 WHERE id = " . $row['id']);
        $errorJson = json_encode("{}");
        $shopId = $row['shop_id'];
        $accessToken = $row['access_token'];
        $refreshToken = $row['refresh_token'];
        $orderSN = $row['order_sn'];

        $checkQuery = "SELECT COUNT(*) AS count FROM orders WHERE order_sn = ?";
        $stmtCheck = $db->prepare($checkQuery);
        $stmtCheck->bind_param("s", $orderSN);
        $stmtCheck->execute();
        $checkResult = $stmtCheck->get_result();
        $checkRow = $checkResult->fetch_assoc();
        $stmtCheck->close();

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

        // Ambil Shipping Parameter
        $responseShippingParamJson = getShippingParameter($accessToken, $refreshToken, $orderSN, $shopId);
        if (empty($responseShippingParamJson)) {
            $errorJson = $responseShippingParamJson;
            insertQueueShipment($shopId, $accessToken, $refreshToken, $orderSN, $errorJson, $platform);
            continue; // Langsung ke iterasi berikutnya jika error
        }

        $responseShippingParam = json_decode($responseShippingParamJson, true);
        if (!isset($responseShippingParam['response']['pickup']['address_list'])) {
            if (isPreOrder($responseShippingParam)) {
                continue;
            } else {
                $errorJson = $responseShippingParamJson;
                insertQueueShipment($shopId, $accessToken, $refreshToken, $orderSN, $errorJson, $platform);
                continue; // Langsung ke iterasi berikutnya jika error
            }
        }

        $addressList = $responseShippingParam['response']['pickup']['address_list'];
        $dataWarehouseDetailJson = getWarehouseDetail($accessToken, $refreshToken, $shopId);
        $dataWarehouseDetail = json_decode($dataWarehouseDetailJson, true);

        if (empty($dataWarehouseDetail['error'])) {
            $criteria = "location_id";
            $order = getDataOrderByOrderSn($orderSN);
            $value = $order['product_location_id'] ?? "";
            if (empty($dataWarehouseDetail['response'])) {
                $errorJson = $dataWarehouseDetailJson;
                insertQueueShipment($shopId, $accessToken, $refreshToken, $orderSN, $errorJson, $platform);
                continue; // Langsung ke iterasi berikutnya jika error
            } else {
                $warehouse = findWarehouse($dataWarehouseDetail['response'], $criteria, $value);
                $addressId = $warehouse['address_id'];
                $zipcode = $warehouse['zipcode'];
            }
        } else {
            $countdataShippingParameter = count($addressList);
            if ($countdataShippingParameter === 1) {
                $addressId = $addressList[0]['address_id'];
                $zipcode = $addressList[0]['zipcode'];
            } else {
                $errorJson = json_encode(
                    [
                        "message" => "Failed to find warehouse",
                        "addressList" => $addressList,
                        "orderSN" => $orderSN,
                        "shopID" => $shopId
                    ]
                );
                insertQueueShipment($shopId, $accessToken, $refreshToken, $orderSN, $errorJson, $platform);
                continue; // Langsung ke iterasi berikutnya jika error
            }
        }

        $pickupTimeId = findPickupTimeId($addressId, $addressList);
        $shipOrderJson = shipOrder($accessToken, $refreshToken, $shopId, $orderSN, $addressId);
        $updateShippingOrderJson = updateShippingOrder($accessToken, $refreshToken, $shopId, $orderSN, $addressId, $pickupTimeId);
        $getTrackingNumber = getTrackingNumber($accessToken, $refreshToken, $orderSN, $shopId);
        $response = json_decode($getTrackingNumber, true);
        $trackingNumber = $response['response']['tracking_number'];
        $updateStok = moveOrdersToAwb($orderSN, $trackingNumber, $zipcode, "shopee");
        sleep(60);
        $url = downloadAwb($accessToken, $refreshToken, $orderSN, $shopId);
        $data[] = ["order" => $orderSN, "url" => $url];
        $nameDownload = 'storage/awb/awb-' . $orderSN . '.pdf';
        repositoryOrdersPackingQueue($orderSN, $zipcode, $nameDownload, $updateStok, $trackingNumber, $platform);
    }
    echo json_encode(["message" => "Successfully", "data" => $data]);
} else {
    echo json_encode(["message" => "No Queue Shipment found"]);
}


// Fungsi untuk memasukkan data ke tabel queue_shipment
function insertQueueShipment($shopId, $accessToken, $refreshToken, $orderSN, $errorJson, $platform)
{
    global $db;
    if (empty($errorJson) || json_decode($errorJson) === null) {
        $errorJson = json_encode(['error' => 'Invalid or empty JSON']);
    }
    $query = "INSERT INTO queue_shipment (order_sn, shop_id, access_token, refresh_token, log_json, platform_id, flag_delete) 
              VALUES ('$orderSN', '$shopId', '$accessToken', '$refreshToken', '$errorJson', '$platform', 0)";
    $db->query($query);
}

function isPreOrder($data)
{
    // Periksa jika tidak ada error dan message kosong
    if ($data['error'] === "" && $data['message'] === "") {
        // Periksa jika slug_list dan branch_list bernilai null
        if (
            is_null($data['response']['dropoff']['slug_list']) &&
            is_null($data['response']['dropoff']['branch_list'])
        ) {
            // Periksa jika info_needed->dropoff adalah array kosong
            if (
                is_array($data['response']['info_needed']['dropoff']) &&
                empty($data['response']['info_needed']['dropoff'])
            ) {
                return true;
            }
        }
    }
    return false;
}
