<?php
date_default_timezone_set('Asia/Jakarta');
set_time_limit(30);
ini_set('max_execution_time', 30);
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('includes/load.php');

function processShopOrders($platform)
{
    global $db;
    $shopName = "";
    $countOrder = 0;

    $sql = "SELECT access_token, shop_id, refresh_token, code, shop_name 
            FROM shop 
            WHERE platform_id = ? AND access_token != '' 
            AND (last_call IS NULL OR last_call <= NOW() - INTERVAL 1 MINUTE) 
            ORDER BY last_call ASC LIMIT 1";

    $stmt = $db->prepare($sql);
    $stmt->bind_param("i", $platform); // Bind platform ID as integer
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $shopId = $row['shop_id'];
            $shopName = $row['shop_name'];
            $currentDatetime = date('Y-m-d H:i:s'); // Current datetime

            // Update the last_call timestamp
            $updateSql = "UPDATE shop SET last_call = ? WHERE shop_id = ?";
            $updateStmt = $db->prepare($updateSql);
            $updateStmt->bind_param("si", $currentDatetime, $shopId);
            $updateStmt->execute();

            // Get the shipment list
            $accessToken = $row['access_token'];
            $refreshToken = $row['refresh_token'];

            // Recursive shipment fetching
            $orderList = getShipmentListAll($accessToken, $refreshToken, $shopId);
            if ($orderList == null) {
                // No shipment found, retry the operation recursively
                return processShopOrders($platform); // Recursively retry fetching the orders
            }

            // Process orders
            $countOrder = count($orderList);
            for ($i = 0; $i < $countOrder; $i++) {
                $queueItem = [
                    'shop_id' => $shopId,
                    'access_token' => $accessToken,
                    'refresh_token' => $refreshToken,
                    'order_sn' => $orderList[$i],
                    'log_json' => '{}',
                    'platform_id' => $platform
                ];

                // Fetch order details
                $response = getDetailOrder($accessToken, $refreshToken, $shopId, $orderList[$i]);
                // Skip certain carriers
                $shipping_carrier = $response['response']['order_list'][0]['shipping_carrier'] ?? "";

                // Skip orders with certain carriers
                if (strpos(strtolower($shipping_carrier), "instant") !== false) {
                    continue;
                }

                // Skip orders with certain carriers
                if (strpos(strtolower($shipping_carrier), "same") !== false) {
                    continue;
                }
                insertOrderDetails($response, $shopId);



                // Process database transaction
                $db->begin_transaction();

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

                if ($checkRow['count'] == 0 && strpos(strtolower($shipping_carrier), "instant") === false && strpos(strtolower($shipping_carrier), "same") === false) {
                    $insertQuery = "INSERT INTO queue_shipment (order_sn, shop_id, access_token, refresh_token, log_json, platform_id, flag_delete) 
                                    VALUES (?, ?, ?, ?, ?, ?, 0)";
                    $stmtInsert = $db->prepare($insertQuery);
                    $stmtInsert->bind_param(
                        "sssssi",
                        $queueItem['order_sn'],
                        $queueItem['shop_id'],
                        $queueItem['access_token'],
                        $queueItem['refresh_token'],
                        $queueItem['log_json'],
                        $queueItem['platform_id']
                    );
                    $stmtInsert->execute();
                    $stmtInsert->close();
                }

                $db->commit();
            }

            // Update orders with packing queue data
            $updateOrdersSql = "UPDATE orders o 
                                JOIN orders_packing_queue opq ON o.order_sn = opq.order_sn 
                                SET o.zipcode = opq.zipcode 
                                WHERE o.zipcode IS NULL OR o.zipcode = ''";
            $updateStmt = $db->prepare($updateOrdersSql);
            $updateStmt->execute();

            echo json_encode(["message" => "Successfully", "shop_name" => $shopName, "order_count" => $countOrder]);
        }
    } else {
        echo json_encode(["message" => "No access token found"]);
    }
}

// Call the function to process shop orders
$sql = "
    UPDATE orders_packing_queue a
    JOIN orders o ON a.order_sn = o.order_sn
    JOIN shop s ON o.shop_id = s.shop_id
    JOIN platform p ON p.id = s.platform_id
    SET a.platform_id = p.id
    WHERE a.platform_id IS NULL
";

// Execute the query
$db->query($sql);
processShopOrders(1);
