<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(60 * 14);
require_once('includes/load.php');

$sql = "SELECT access_token, shop_id, refresh_token, code, shop_name FROM shop WHERE platform_id = 1 AND access_token != ''";
$stmt = $db->prepare($sql);
$stmt->execute();
$errorArr = array();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $shopId = $row['shop_id'];
        $shopName = $row['shop_name'];
        $accessToken = $row['access_token'];
        $refreshToken = $row['refresh_token'];
        $orderList = getShipmentListAll($accessToken, $refreshToken, $shopId);
        if ($orderList == null) {
            // echo json_encode(["message" => "No shipment found"]);
            continue;
        }
        $countOrder = count($orderList);
        $arrayPackingList = array();
        for ($i = 0; $i < $countOrder; $i++) {
            if ($i > 10) {
                break;
            }
            $pickupTimeId = "";
            $updateStok = 0;
            $addressId = 0;
            $zipcode = "";
            $OrderSN = $orderList[$i];
            $response = getDetailOrder(
                $accessToken,
                $refreshToken,
                $shopId,
                $OrderSN
            );
            insertOrderDetails($response, $shopId);
            $shipping_carrier = $response['response']['order_list'][0]['shipping_carrier'] ?? "";
            if (strpos(strtolower($shipping_carrier), "instan") !== false || strpos(strtolower($shipping_carrier), "same") !== false) {
                $errorArr[] = [
                    "message" => "Failed to find warehouse",
                    "ShopName" => $shopName,
                    "orderSN" => $OrderSN,
                    "shopID" => $shopId
                ];
                continue;
            }
            $responseShippingParamJson = getShippingParameter($accessToken, $refreshToken, $OrderSN, $shopId);
            $responseShippingParam = json_decode($responseShippingParamJson, true);
            $order = getDataOrderByOrderSn($OrderSN);
            $value = $order['product_location_id'] ?? "";
            if (!isset($responseShippingParam['response']['pickup']['address_list']) || !empty($value)) {
                $criteria = "location_id";
                $dataWarehouseDetailJson = getWarehouseDetail($accessToken, $refreshToken, $shopId);
                $dataWarehouseDetail = json_decode($dataWarehouseDetailJson, true);
                if (!isset($dataWarehouseDetail['response'])) {
                    if (!isset($responseShippingParam['response']['pickup']['address_list'])) {
                        $errorArr[] = [
                                "message" => "Failed to find warehouse",
                                "addressList" => $responseShippingParam,
                                "orderSN" => $OrderSN,
                                "shopID" => $shopId,
                                "dataWarehouseDetail" => $dataWarehouseDetail
                        ];
                        continue;
                    }
                    $addressList = $responseShippingParam['response']['pickup']['address_list'];
                    $countdataShippingParameter = count($addressList);
                    if ($countdataShippingParameter === 1) {
                        $addressId = $addressList[0]['address_id'];
                        $zipcode = $addressList[0]['zipcode'];
                        $pickupTimeId = findPickupTimeId($addressId, $addressList);
                    } else {
                        echo json_encode(
                            [
                                "message" => "Failed to find warehouse",
                                "addressList" => $addressList,
                                "orderSN" => $OrderSN,
                                "shopID" => $shopId
                            ]
                        );
                        die();
                    }
                } else {
                    $warehouse = findWarehouse($dataWarehouseDetail['response'], $criteria, $value);
                    $addressId = $warehouse['address_id'];
                    $zipcode = $warehouse['zipcode'];
                }
              
            } else {
                $addressList = $responseShippingParam['response']['pickup']['address_list'];
                $countdataShippingParameter = count($addressList);
                if ($countdataShippingParameter === 1) {
                    $addressId = $addressList[0]['address_id'];
                    $zipcode = $addressList[0]['zipcode'];
                    $pickupTimeId = findPickupTimeId($addressId, $addressList);
                } else {
                    echo json_encode(
                        [
                            "message" => "Failed to find warehouse",
                            "addressList" => $addressList,
                            "orderSN" => $OrderSN,
                            "shopID" => $shopId
                        ]
                    );
                    die();
                }
            }
           
            $shipOrderJson = shipOrder($accessToken, $refreshToken, $shopId, $OrderSN, $addressId);
            if (!empty($pickupTimeId)) {
                $errorArr[] = [
                    "message" => "Failed to find pickup time",
                    "ShopName" => $shopName,
                    "orderSN" => $OrderSN,
                    "shopID" => $shopId
                ];
                continue;
            }
            $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 = moveOrdersToAwbAndUpdateStok($OrderSN, $trackingNumber, $zipcode);
            $url = downloadAwb($accessToken, $refreshToken, $OrderSN, $shopId);
            if ($url === null || $url === array()) {
                $errorArr[] = [
                    "message" => "Failed to download awb",
                    "ShopName" => $shopName,
                    "orderSN" => $OrderSN,
                    "shopID" => $shopId,
                    "url" => $url
                ];
                repositoryOrdersPackingQueue($OrderSN, $zipcode, "", $updateStok, $trackingNumber);
                continue;
            }
            repositoryOrdersPackingQueue($OrderSN, $zipcode, $url, $updateStok, $trackingNumber);
        }
    }
    echo json_encode(["message" => "Successfully", "error" => $errorArr]);
} else {
    echo json_encode(["message" => "No access token found"]);
}