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

ini_set("error_reporting", E_ALL);
ini_set("display_errors", true);

error_reporting(E_ALL & ~E_NOTICE);
$hash   = $_POST['store_hash'];

$db->select("stores","*" ,array( "store_id" => $hash) );

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


    if($is_wishlist_enable==0){

        echo "permission denied";
        exit();

    }



$store_hash   =$hash;

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



function callBigCommerce($endpoint) {
    global $access_token, $base_url;

    //echo $base_url.$endpoint;

    $curl = curl_init();

    curl_setopt_array($curl, [
      CURLOPT_URL => $base_url.$endpoint,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_HTTPHEADER => [
        "Content-Type: application/json",
        "Accept: application/json",
        "X-Auth-Token:{$access_token}"
      ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
     /* echo "cURL Error #:" . $err;*/
    return json_decode("[]", true);

    } else {
      //echo $response;
         return json_decode($response, true);
    }

}

// Get params
$page   = isset($_POST['page']) ? (int)$_POST['page'] : 1;
$append = isset($_POST['append']) ? (bool)$_POST['append'] : false;


$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");
/*print_r($wishlistResp);
exit();*/


if (!empty($wishlistResp['data'])) {
    foreach ($wishlistResp['data'] as $wishlist) {
        $wishlistId   = $wishlist['id'];
        $wishlistName = $wishlist['name'];
        $customerId   = $wishlist['customer_id'];

     
        $customer = callBigCommerce("v2/customers/$customerId");

     /*   echo "<pre>";
        print_r($customer);
        echo "</pre>";*/
        $firstName = $customer['first_name'] ?? '';
        $lastName  = $customer['last_name'] ?? '';
        $phone  = $customer['phone'] ?? '';
        $email  = $customer['email'] ?? '';

        if (empty($wishlist['items'])) {
            //fputcsv($fp, [$wishlistId, $wishlistName, $firstName, $lastName,$email,$phone, '', '', '']);
            continue;
        }

        $counter=1;

        foreach ($wishlist['items'] as $item) {


            $productId = $item['product_id'];
            $product   = callBigCommerce("v3/catalog/products/$productId");

            //print_r($product);

            $productName = $product['data']['name'] ?? '';
            $productSku  = $product['data']['sku'] ?? '';

            if($counter===1)
            {

                fputcsv($fp, [$wishlistId, $wishlistName, $firstName, $lastName,$email,$phone, $productId, $productName, $productSku]);
            }else{
                fputcsv($fp, ["","","","","","",$productId, $productName, $productSku]);
            }

            $counter++;
        }
    }
}
fclose($fp);

// Pagination
$meta = $wishlistResp['meta']['pagination'] ?? null;
$total=$wishlistResp['meta']['pagination']["total"]; 
if ($meta && $meta['current_page'] < $meta['total_pages']) {
    $remaining = ($meta['total_pages'] - $meta['current_page']) * $meta['per_page'];

    echo json_encode([
        "next_page" => $meta['current_page'] + 1,
        "append"    => true,
        "remaining" => $remaining,
        "total"=>$total,
        "res"=>$wishlistResp['meta']['pagination']
    ]);
    exit;
}


echo json_encode([
    "download" => $filename
]);
exit;
