<?php
ini_set('session.cookie_samesite', 'None');
session_set_cookie_params(['samesite' => 'None']);

@session_start();

ini_set("error_reporting", E_ALL);

ini_set("display_errors", true);

header('X-Frame-Options: GOFORIT');


error_reporting(E_ALL & ~E_NOTICE);

include_once 'inc/functions.php';

include 'inc/database.php';



require_once __DIR__ . '/vendor/autoload.php';

use Bigcommerce\Api\Client as Bigcommerce;



$config = array();



$page 			= $_GET["page"] ? $_GET["page"] : 1;



if( isset($_GET['signed_payload']) || (isset($_GET['store_hash']) && !empty($_GET['store_hash'])) ){

	$data = decodeSignedRequest($_GET['signed_payload']);

	$hash = isset($data['store_hash']) ? $data['store_hash'] : $_GET[

		'store_hash'];

	$_SESSION['store_hash'] = $hash;

	$access_token = $db->getSingleColumn( "stores", "access_token", array( "store_id" => $hash ));

		$_SESSION['access_token']	= $access_token;

        if( $access_token == "")

            die("store access token not found.");

        $config = array(

            'client_id'  => CLIENT_ID,

            'auth_token' => $access_token,

            'store_hash' => $hash

        );

    Bigcommerce::configure($config);

    Bigcommerce::verifyPeer(false);

	

	

   	$limit			= 20;

	

	$total_count	= 0;

	$show_next_page = false;

	// for($i=1; $i<=$page; $i++){

	$curl = curl_init();

	curl_setopt_array($curl, array(

		CURLOPT_URL => "https://api.bigcommerce.com/stores/".$hash."/v3/wishlists?page=".$page."&limit=".$limit,

		CURLOPT_RETURNTRANSFER => true,

		CURLOPT_ENCODING => "",

		CURLOPT_MAXREDIRS => 10,

		CURLOPT_TIMEOUT => 30,

		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

		CURLOPT_CUSTOMREQUEST => "GET",

		CURLOPT_HTTPHEADER => array(

		"Accept: application/json",

		"Cache-Control: no-cache",

		"Connection: keep-alive",

		"Content-Type: application/json",

		"X-Auth-Client: ".CLIENT_ID,

		"X-Auth-Token: ".$access_token,

		"cache-control: no-cache"

		),

	));

	$response 	= curl_exec($curl);

	$err 		= curl_error($curl);

	curl_close($curl);

	$response	= json_decode($response,true);

	if($response){	

		$wishlists	= $response['data'];			

		$count		= $response['meta']['pagination']['count'];

		if($count){

			$total_count	= $total_count + $count;

			foreach($wishlists as $key=>$singleWishlist){

			$id		= $singleWishlist['id'];

			$items	= $singleWishlist['items'];

				if(!empty($items)) {

					foreach($items as $key=>$item){	

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

					}	

				}

			}

		}

	}

	$curl = curl_init();



	$next_page = $page + 1;



	curl_setopt_array($curl, array(

		CURLOPT_URL => "https://api.bigcommerce.com/stores/".$hash."/v3/wishlists?page=".$next_page."&limit=".$limit,

		CURLOPT_RETURNTRANSFER => true,

		CURLOPT_ENCODING => "",

		CURLOPT_MAXREDIRS => 10,

		CURLOPT_TIMEOUT => 30,

		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

		CURLOPT_CUSTOMREQUEST => "GET",

		CURLOPT_HTTPHEADER => array(

		"Accept: application/json",

		"Cache-Control: no-cache",

		"Connection: keep-alive",

		"Content-Type: application/json",

		"X-Auth-Client: ".CLIENT_ID,

		"X-Auth-Token: ".$access_token,

		"cache-control: no-cache"

		),

	));

	$response 	= curl_exec($curl);

	$err 		= curl_error($curl);

	curl_close($curl);

	$response	= json_decode($response,true);

	if($response){	

		$wishlists	= $response['data'];			

		$count		= $response['meta']['pagination']['count'];

		if($count){

			$show_next_page = true;

		}

	}

	// }

	//echo 'No. of Wishlists: '.$total_count."<br>";

	$vals 	= @array_count_values($product_id);

	@arsort($vals);


    $store_url = $db->getSingleColumn("stores", "store_url", array( "access_token" => $access_token) );

}







?>

<!doctype html>

<html>

    <head>

        <meta charset="utf-8">

        <meta name="description" content="">

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Bigcommerce Wishlist App</title>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />



        <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/css/dataTables.bootstrap.min.css">

        <link rel="stylesheet" href="<?php  echo BASE_PATH ?>assets/css/custom.css?<?= time(); ?>">



        <script  src="https://code.jquery.com/jquery-3.3.1.js"></script>

        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

		<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js" type="text/javascript" charset="utf-8" ></script>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/dataTables.bootstrap.min.js" type="text/javascript" charset="utf-8" ></script>

        <script src="<?php  echo BASE_PATH ?>assets/js/cstm.js?v=1.21"></script>

        <style>

			.cstm-pageination {

				background: #337AB7;

				color: white;

				padding: 10px 15px;

				margin-right: 10px;

			}

        </style>

    </head>

    <body>

        <div class="app_conatiner">

				<div style="overflow: hidden;">				

               		<h1 class="total" >

						<span class="total-text">

							Wishlist App by Webecommercepros

						</span>

						<span class="req_feature"> 							

							<span class="contact-support">

								<button id="support_btn1" class="btn support_btn">

								<a href="//www.webecommercepros.com/" target="_blank">Contact Support</a></button>

							</span>

							<button id="request_btn" class="btn request_btn">Request a Feature</button> 

						</span>

					

					</h1> 

				</div>		

                <div id="main_content">

                	<div class="sub_conatiner">

                        <table id="show_record" class="table table-striped ">

                    	    <thead>

                    	      <tr>

                    	      	<th>Product Id</th>

                                <th>Product Name</th>

                                <th>Count</th> 

                                <th>Customers</th>

                    	       </tr>

                    	    </thead>

							<tbody>

								<?php 

									if($vals){

										foreach($vals as $key=>$value){ 

											$product	= Bigcommerce::getProduct($key);

											$pro_name	= $product->name;

											//echo $key." : ".$pro_name." : ".$value."<br>";

										?>

											<tr class="data">

												<td><?php echo $key ; ?></td>

												<td><?php echo $pro_name ; ?></td>

												<td><?php echo $value ; ?></td>  

												<td></td> 

											</tr>

										<?php 

									}

									}else{ ?>

										<tr>

											<td colspan="4"  align="center">Sorry, Items list not found..!</td>

										</tr>

										

									<?php }

								?>

							</tbody>

							<tfoot>

								<tr>

									<td colspan="4" style="text-align:right; padding: 20px 0 0 0;">

										<?

											

											if($page > 1){

											    $pre_page = (int) $page - 1;

												$prev_link = "load.php?signed_payload=".$_GET['signed_payload']."&page=".$pre_page;

												?>

													<a class="cstm-pageination" href="<? echo $prev_link; ?>">Previous</a>

												<?

											}

											else{

												?>

													<a class="cstm-pageination" style="pointer-events:none; cursor:no-drop; opacity: 0.5;" href="<? echo $next_link; ?>">Previous</a>

												<?

											}

											?>

										<?

											

											if($show_next_page){

											    $next_page = $page + 1;

												$next_link = "load.php?signed_payload=".$_GET['signed_payload']."&page=".$next_page;

												?>

													<a class="cstm-pageination" href="<? echo $next_link; ?>">Next</a>

												<?

											}else{

												?>

													<a class="cstm-pageination" style="pointer-events:none; cursor:no-drop; opacity: 0.5;" href="<? echo $next_link; ?>">Next</a>

												<?

											}

										?>

									</td> 

								</tr>

							</tfoot>

						</table>

                	</div>	              	

                </div>  			

				<div style="text-align: center; margin: 20px;">

					<a href="//www.webecommercepros.com/" target="_blank">

						<img src="assets/images/logo.png" width="170px" height="40px"> 

					</a>

				</div>

       				     

        </div>    

    	    	

    </body>

</html>   

<script>

    $(document).ready(function(){

        $('select[name="show_record_length"]').css('padding-top','0px'); 

		

//		$('#support_btn1').click(function() {

//      window.location.href='//www.webecommercepros.com/';

//		});

		

    });

    

</script> 	 

