<?php
set_time_limit(30);
require_once('includes/load.php');
$platform = 1;
$order = array();
$sql = "SELECT s.access_token, s.shop_id, s.refresh_token, s.code, o.order_sn FROM shop s join orders o on o.shop_id = s.shop_id where s.platform_id = $platform and o.order_status IN ('READY_TO_SHIP', 'UNPAID', 'PROCESSED', 'SHIPPED') and (o.last_call IS NULL OR o.last_call <= NOW() - INTERVAL 15 MINUTE) order by o.last_call asc limit 20;";
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();

// // Check if any record was found
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $currentDatetime = date('Y-m-d H:i:s');

        $sql = "UPDATE orders SET last_call = ? WHERE order_sn = ?";
        $stmt = $db->prepare($sql);

        // Mengikat parameter untuk last_call dan shop_id
        $stmt->bind_param("ss", $currentDatetime, $row['order_sn']);
        $stmt->execute();
        array_push($order, $row['order_sn']);
        $response = getDetailOrder($row['access_token'], $row['refresh_token'], $row['shop_id'], $row['order_sn']);
        insertOrderDetails($response, $row['shop_id']);
    }
    echo json_encode(["message" => "Success!", "order_id" => $order]);
} else {
    echo json_encode(["message" => "No access token found"]);
}
