<?php
set_time_limit(300);
ini_set('max_execution_time', 300);
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('includes/load.php');
$platform = 5;
// Mendapatkan waktu mulai (00:00:00) kemarin
$startOfYesterday = strtotime('yesterday midnight');  // Kemarin 00:00:00

// Mendapatkan waktu selesai (23:59:59) hari ini
$endOfToday = strtotime('today 23:59:59');  // Hari ini 23:59:59

// Konversi ke format Unix timestamp (milidetik)
$startTimestamp = $startOfYesterday * 1000;
$endTimestamp = $endOfToday * 1000;

$sql = "SELECT id, access_token, shop_id, shop_name FROM shop WHERE platform_id = ?";

// Persiapkan query
$stmt = $db->prepare($sql);

if (!$stmt) {
  die("Prepare failed: " . $db->error); // Debug jika prepare gagal
}

// Bind parameter (gunakan 'i' untuk integer)
$stmt->bind_param("i", $platform);

// Eksekusi query
if (!$stmt->execute()) {
  die("Execution failed: " . $stmt->error); // Debug jika eksekusi gagal
}

// Dapatkan hasil query
$result = $stmt->get_result();

if (!$result->num_rows > 0) {
  die("No results shop found.");
}
if ($result && $result->num_rows > 0) {
  while ($row = $result->fetch_assoc()) {
    $id = $row['id'];
    $storeCode = $row['shop_id'];
    $shopName = $row['shop_name'];
    $ApiSellerKey = $row['access_token'];

    $respons = BlibliGetListOrder($startTimestamp, $endTimestamp, $storeCode, $shopName, $ApiSellerKey, 0, 10);
    if (!isset($respons['content'])) {
      echo json_encode($respons, true);
      die();
    }
    echo json_encode($respons, true);
    $orderCount = count($respons['content']);
    // // Insert data ke database
    for ($index = 0; $index < $orderCount; $index++) {
      if ($respons['content'][$index]['orderItems'][0]['order']['itemStatus'] != 'FP') {
        continue;
      }

      $packageID = '';

      $orderItemIDArray = array();
      for ($i = 0; $i < count($respons['content'][$index]['orderItems']); $i++) {
        $orderItemIDArray[] = $respons['content'][$index]['orderItems'][$i]['order']['itemId'];
      }

      $responseCteatePackage = BlibliCreatePackage($storeCode, $shopName, $ApiSellerKey, $orderItemIDArray);
      echo "<pre>";
      print_r($responseCteatePackage);
      echo "</pre>";
      $order_id_inserted = 0;
      for ($i = 0; $i < count($orderItemIDArray); $i++) {
        $data = BlibliGetOrderItem($orderItemIDArray[$i], $storeCode, $shopName, $ApiSellerKey);
        if (!isset($data['content'])) {
          echo json_encode($data, true);
          die();
        }
        $order = $data['content'];
        $packageID = $order['packageId'];
        $order_sn = $order['id'];
        $status = $order['status'];
        $recipient_name = $order['recipient']['name'];
        $delivery_address = $order['recipient']['streetAddress'];
        $city = $order['recipient']['city'];
        $zipcode = $order['pickupPoint']['zipCode'];
        if ($zipcode == '15154') {
          $zipcode = "15151";
        }
        $provinsi = $order['recipient']['state'];
        $shop_id = $order['store']['code'];
        $buyer_username = $order['recipient']['name'];
        $shipping_carrier = $order['shipment']['logistic']['product']['name'];
        $phone_number = $order['recipient']['phoneNumber'];

        $trackingNumber = $order['shipment']['airwayBill']['number'] ?? "";
        // Extract order_detail data
        $product = $order['product'];
        $item_name = $product['name'];
        $variant_name = $product['variantName'];
        $blibli_sku = $product['blibliSku'];
        $seller_sku = $product['sellerSku'];
        $weight = $order['shipment']['totalWeight'];
        $amount_item = $order['amount']['item'];
        $item_sku = $blibli_sku; // Using blibliSku for item_sku
        $currency = 'Rp';

        global $db;
        if ($i == 0) {
          $stmt_order = $db->prepare("
      INSERT INTO orders (order_sn, order_status, recipient_name, delivery_address, city, zipcode, phone_number, province, shop_id, currency, create_time, pay_time, buyer_username, shipping_carrier)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now(), now(), ?, ?)
  ");

          $stmt_order->bind_param('ssssssssssss', $order_sn, $status, $recipient_name, $delivery_address, $city, $zipcode, $phone_number, $provinsi, $shop_id, $currency, $buyer_username, $shipping_carrier);
          $stmt_order->execute();

          // Get the last inserted order ID
          $order_id_inserted = $stmt_order->insert_id;
        }

        $stmt_detail = $db->prepare("
    INSERT INTO order_detail (order_id, order_sn, order_item_id, item_name, model_quantity_purchased, weight, model_sku, item_sku, model_discounted_price, model_original_price)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
        echo "<br>";
        echo $order_sn;
        echo "<br>";
        echo $order_id_inserted;
        echo "<br>";
        $stmt_detail->bind_param('issssdssdd', $order_id_inserted, $order_sn, $order_id, $item_name, $order['quantity'], $weight, $seller_sku, $seller_sku, $amount_item, $amount_item);
        $stmt_detail->execute();
        $nameDownload = 'storage/awb/awb-' . $order_sn . '.pdf';
        $updateStok = moveOrdersToAwb($order_sn, $trackingNumber, $zipcode, 'blibli');
        repositoryOrdersPackingQueue($order_sn, $zipcode, $nameDownload, $updateStok, $trackingNumber, $platform);

        $shippingAWB = BlibliGetShippingLabel($packageID, $storeCode, $shopName, $ApiSellerKey);
        if (!isset($shippingAWB['content'])) {
          echo json_encode($shippingAWB, true);
          die();
        }
        $fileData = base64_decode($shippingAWB['content']['shippingLabel']);

        file_put_contents($nameDownload, $fileData);
      }
    }
  }
}
