<?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'];

$store_details=$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) {

    fwrite($fp, "\xEF\xBB\xBF");
    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) {

        if (empty($wishlist['items'])) {
            //fputcsv($fp, [$wishlistId, $wishlistName, $firstName, $lastName,$email,$phone, '', '', '']);
            continue;
        }
        $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'] ?? '';

        

        $counter=1;
        $product_ids=array();

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

           
            $product_ids[]=$item['product_id'];            
        }

        $product_ids_string=implode(",",$product_ids);
            
        $product_data   = callBigCommerce("v3/catalog/products?id:in=".$product_ids_string);

        foreach($product_data["data"] as $product_data_index=> $product_data_row)
        {
            $productName = $product_data_row['name'] ?? '';
            $productSku  = $product_data_row['sku'] ?? '';
            $productId=$product_data_row['id'];

            if($product_data_index==0)
            {

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

        }

        //print_r($product);          

            
    }
}
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,
        "response"=>$wishlistResp['meta']['pagination']
    ]);
    exit;
}


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