<?php
require_once('includes/load.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$platform = 1;
$orderSNLastCall = array();
$sql = "select s.access_token, s.refresh_token, s.shop_id, opq.awb_url, opq.order_sn, o.order_status, opq.id, opq.resi, opq.is_download_failed 
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 opq.processed = 0 
and s.platform_id = 1 
AND opq.is_download_failed = 1 
AND opq.created_at >= NOW() - INTERVAL 3 DAY 
AND opq.last_call <= NOW() - INTERVAL 5 MINUTE 
order by opq.id desc 
limit 50";
$stmt = $db->prepare($sql);
$stmt->execute();
$data = array();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $shopId = $row['shop_id'];
        $OrderQueueId = $row['id'];
        $accessToken = $row['access_token'];
        $refreshToken = $row['refresh_token'];
        $orderSN = $row['order_sn'];
        $orderSNLastCall[] = $orderSN;
        $orderStatus = $row['order_status'];
        $resi = $row['resi'];
        $awbUrl = $row['awb_url'];
        $isDownloadFailed = $row['is_download_failed'];
        $rootPath = $_SERVER['DOCUMENT_ROOT'];
        if ($orderStatus == 'CANCELLED') {
            delete_by_id('orders_packing_queue', $OrderQueueId);
            delete_by_field('order_detail', 'order_sn', $orderSN);
            delete_by_field('orders', 'order_sn', $orderSN);
            delete_by_field('awb', 'invoice', $orderSN);
            $sql = "UPDATE queue_shipment SET is_cancel = 1 WHERE order_sn = ?";
            $stmt = $db->prepare($sql);
            $stmt->bind_param("s", $orderSN);
            $stmt->execute();
        } elseif (in_array($orderStatus, ['COMPLETED', 'SHIPPED', 'TO_RETURN', 'RETRY_SHIP', 'TO_CONFIRM_RECEIVE'])) {
            $sql = "UPDATE orders_packing_queue SET processed = 1 WHERE order_sn = ?";
            $stmt = $db->prepare($sql);
            $stmt->bind_param("s", $orderSN);
            $stmt->execute();
        }

        if (!isPdfValid($rootPath . "/" . $row['awb_url'])) {
            downloadAwb($accessToken, $refreshToken, $orderSN, $shopId);
            $data[] = ["order" => $orderSN, "url" => $awbUrl, "tracking_number" => ""];
        } else {
            if ($isDownloadFailed == 1) {
                $sql = "UPDATE orders_packing_queue SET is_download_failed = 0 WHERE order_sn = ?";
                $stmt = $db->prepare($sql);
                $stmt->bind_param("s", $orderSN);
                $stmt->execute();
            }
        }
        if (empty($resi)) {
            // Mendapatkan tracking number dari API
            $getTrackingNumber = getTrackingNumber($accessToken, $refreshToken, $orderSN, $shopId);
            // echo $getTrackingNumber;
            $response = json_decode($getTrackingNumber, true);

            // Pastikan 'response' dan 'tracking_number' ada dalam hasil
            if (isset($response['response']['tracking_number'])) {
                $trackingNumber = $response['response']['tracking_number'];
                $data[] = ["order" => $orderSN, "url" => "", "tracking_number" => $trackingNumber];

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


                $sql = "
                UPDATE awb 
                SET resi = ? 
                WHERE invoice = ?";
                $stmt = $db->prepare($sql);
                $stmt->bind_param("ss", $trackingNumber, $orderSN);
                $stmt->execute();
            } else {
                $data[] = ["order" => $orderSN, "url" => "", "tracking_number" => "Tracking number not found for order SN: $orderSN"];
            }
        }
    }

    updateShipmentQueue($orderSNLastCall);
    echo json_encode(["message" => "Successfully", "data" => $data]);
} else {
    echo json_encode(["message" => "No Orders Packing Queue 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 updateShipmentQueue($orders)
{
    global $db;
    if (count($orders) > 0) {
        // Start building the update query
        $orderSNs = implode("', '", array_map('addslashes', $orders)); // Escape order SNs
        $updateQuery = "UPDATE queue_shipment SET updated_at = NOW() WHERE order_sn IN ('$orderSNs')";

        // Execute the update statement
        $result = $db->query($updateQuery);
        if (!$result) {
            throw new Exception("Error executing statement: " . implode(", ", $db->error));
        }
    }
}
