<?php
include_once 'inc/functions.php';
include 'inc/database.php';

$hash   = $_REQUEST['store_hash'] ?? '';
$page   = isset($_GET['page']) ? (int)$_GET['page'] : 1; // page from query
$append = $page > 1;

// Get store details
$store_details = $db->select("stores", "*", ["store_id" => $hash]);
if (!$store_details) die("Invalid store hash");

$access_token       = $store_details['access_token'];
$is_wishlist_enable = $store_details['download_all_enabled'];

if ($is_wishlist_enable == 0) die("Permission denied");

$store_hash = $hash;
$base_url   = "https://api.bigcommerce.com/stores/$store_hash/";

function callBigCommerce($endpoint) {
    global $access_token, $base_url;
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $base_url.$endpoint,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "Accept: application/json",
            "X-Auth-Token:{$access_token}"
        ],
    ]);
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response, true);
}

$filename = "wishlist_csv/all_wishlist_" . $store_hash . ".csv";
$filepath = __DIR__ . "/" . $filename;

if ($page == 1 && file_exists($filepath)) unlink($filepath);

$fp = fopen($filepath, $append ? "a" : "w");
if ($page == 1) {
    fputcsv($fp, ["id","wishlist name","customer first name","customer last name","email","phone","product id","product name","product sku"]);
}

// Fetch wishlists
$wishlistResp = callBigCommerce("v3/wishlists?page=$page&limit=250");
if (!empty($wishlistResp['data'])) {
    foreach ($wishlistResp['data'] as $wishlist) {
        if (empty($wishlist['items'])) continue;
        $wishlistId   = $wishlist['id'];
        $wishlistName = $wishlist['name'];
        $customerId   = $wishlist['customer_id'];

       // $customer = callBigCommerce("v2/customers/$customerId");
        $firstName ="";
        $lastName  = "";
        $phone     = "";
        $email     = "";

        $product_ids = array_column($wishlist['items'], 'product_id');
        $product_ids_string = implode(",", $product_ids);

        $product_data = callBigCommerce("v3/catalog/products?id:in=".$product_ids_string);
        foreach ($product_data["data"] as $index => $product) {
            $productId   = $product['id'];
            $productName = $product['name'] ?? '';
            $productSku  = $product['sku'] ?? '';
            if ($index == 0) {
                fputcsv($fp, [$wishlistId, $wishlistName, $firstName, $lastName, $email, $phone, $productId, $productName, $productSku]);
            } else {
                fputcsv($fp, ["","","","","","",$productId, $productName, $productSku]);
            }
        }
    }
}
fclose($fp);

// Pagination
$meta = $wishlistResp['meta']['pagination'] ?? null;

if ($meta && $meta['current_page'] < $meta['total_pages']) {
    $nextPage = $meta['current_page'] + 1;
    $percent  = round(($meta['current_page'] / $meta['total_pages']) * 100);

    echo <<<HTML
<!DOCTYPE html>
<html>
<head>
  <title>Exporting Wishlists...</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css">
  <style>
    body { padding:40px; font-family: Arial; }
    .progress { height:30px; }
    .progress-bar { font-size:14px; line-height:30px; }
  </style>
</head>
<body>
  <h3>Exporting Wishlists...</h3>
  <div class="progress">
    <div class="progress-bar progress-bar-striped active" role="progressbar" 
         aria-valuenow="$percent" aria-valuemin="0" aria-valuemax="100" style="width: {$percent}%;">
      $percent%
    </div>
  </div>
  <p>Processing page {$meta['current_page']} of {$meta['total_pages']}...</p>
  <script>
    setTimeout(function(){
      window.location.href='download_wishlist_info_page_redirect.php?store_hash={$hash}&page={$nextPage}';
    }, 1000);
  </script>
</body>
</html>
HTML;
    exit;
}

// Finished
echo <<<HTML
<!DOCTYPE html>
<html>
<head>
  <title>Export Complete</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css">
  <style> body { padding:40px; font-family: Arial; } </style>
</head>
<body>
  <h2>Export Complete ✅</h2>
  <a href="$filename" class="btn btn-success">Download Wishlist CSV</a>
</body>
</html>
HTML;
exit;
