<?php
set_time_limit(300);
require_once('includes/load.php');

// Query to fetch all shops
$sql = "SELECT access_token, shop_id, refresh_token, code FROM shop";
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();

// Check if any records were found
if ($result->num_rows > 0) {
    // Initialize an array for responses
    $shopResponses = [];

    while ($row = $result->fetch_assoc()) {
        $listDataOrder = [];
        $dataOrder = [];

        // Get order list for the current shop
        $dataOrder = addOrderlist($row['access_token'], $row['refresh_token'], $row['shop_id']);
        $countOrder = count($dataOrder);

        // Chunk orders into groups of 50
        for ($i = 0; $i < $countOrder; $i += 50) {
            $chunkOrder = array_slice($dataOrder, $i, 50);
            $stringOrder = implode(',', $chunkOrder);
            $listDataOrder[] = $stringOrder;
        }

        // Process each chunk
        $countListOrder = count($listDataOrder);
        for ($i = 0; $i < $countListOrder; $i++) {
            $response = getDetailOrder(
                $row['access_token'],
                $row['refresh_token'],
                $row['shop_id'],
                $listDataOrder[$i]
            );

            // Save order details for this shop
            saveOrderDetails($response);
        }

        // Log a success message for the current shop
        $shopResponses[] = [
            'shop_id' => $row['shop_id'],
            'message' => 'Success'
        ];
    }
    // Return response for all shops
    echo json_encode(["shops" => $shopResponses, 'message' => 'Success']);
} else {
    // No shops found
    echo json_encode(["message" => "No shops found"]);
}
?>