<?php
@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);
	$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>
			select.input-sm{
				line-height: 1.5 !important;
			}
			#show_record_cstm_test{
				display: none;
			}
			#show_record_cstm_test button {
				background: none!important;
				border: none;
				padding: 0!important;
				font-family: arial, sans-serif;
				color: #069;
				text-decoration: underline;
				cursor: pointer;
			}
			.bar-loader {
				display: inline-block;
				position: relative;
				height: 80px;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			.bar-loader div {
				display: inline-block;
				margin-left: 8px;
				width: 16px;
				background: #337AB7;
				animation: bar-loader 1.2s cubic-bezier(0, 0.5, 0.5, 1) infinite;
			}
			.bar-loader div:nth-child(1) {
				left: 8px;
				animation-delay: -0.24s;
			}
			.bar-loader div:nth-child(2) {
				left: 32px;
				animation-delay: -0.12s;
			}
			.bar-loader div:nth-child(3) {
				left: 56px;
				animation-delay: 0;
			}
			@keyframes bar-loader {
				0% {
					top: 8px;
					height: 64px;
				}
				50%, 100% {
					top: 24px;
					height: 32px;
				}
			}
			.loading-msg{
				display: flex;
				justify-content: center;
				align-items: center;
			}
			.wep-logo{
				text-align: center;
				margin: 20px;
				position: absolute;
				left: 0;
				bottom: 20px;
				right: 0;
			}
		</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">
					<div class="loader-container" >
						<div class="bar-loader"><div></div><div></div><div></div></div>
						<div class="loading-msg" ><p>We're fetching the data, this may take several minutes.</p></div>
					</div>
					<table id="show_record_cstm_test" class="table table-striped "></table>
				</div>             	
			</div>			
			<div class="wep-logo" 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'); 
		var hash = "<?php echo $hash; ?>";
		var table = "";
		var table_shown = false;
		var fetching_data = false;
		function getWishlistProducts(page){
			fetching_data = true;
			localStorage.setItem("store_hash", hash);
			var localData = localStorage.getItem("localData_temp");
			var request_time = localStorage.getItem("request_time");
			if(request_time){
				request_time = JSON.parse(request_time);
			}
			else{
				request_time = 0
			}
			$.ajax({
				url: "https://wishlist.appsserver.net/bigcommerce_apps/wishlist/ajax.php",
				dataType: "json",
				type: "POST",
				crossDomain: true,
				data: {page, store_hash: hash, action: "get_wishlist_products", localData, request_time},
				success: function(res){
					console.log(res);
					if(res.status){
						var data = res.data;
						var _localData = res.localData;
						localStorage.setItem("localData_temp", JSON.stringify(_localData));
						var wishlist_data = localStorage.getItem("wishlist_data_temp");
						wishlist_data = JSON.parse(wishlist_data);
						if(res.data){
							console.log("in if");
							var _wishlist_data = [];
							if(wishlist_data){
								_wishlist_data = Object.assign(wishlist_data, res.data);
							}
							else{
								_wishlist_data = res.data;
							}
							if(_wishlist_data){
								var wishlist_data_array = Object.keys(_wishlist_data);
								// console.log(_wishlist_data);
								wishlist_data_array.map(function(_data){
									// console.log(_wishlist_data[_data]);
									_wishlist_data[_data].count = _localData[_data]
								});
								setTimeout(function() {
									// console.log(_wishlist_data);
									localStorage.setItem("wishlist_data_temp", JSON.stringify(_wishlist_data));
									getWishlistProducts(page+1);
								}, 500);
							}
						}
						else if(_localData){
							console.log("in else");
							if(wishlist_data){
								// console.log(wishlist_data);
								var wishlist_data_array = Object.keys(wishlist_data);
								wishlist_data_array.map(function(_data){
									wishlist_data[_data].count = _localData[_data]
								});
								setTimeout(function() {
									// console.log(wishlist_data);
									localStorage.setItem("wishlist_data_temp", JSON.stringify(wishlist_data));
									getWishlistProducts(page+1);
								}, 500);
							}
						}
					}
					else if(res.message == "use local storage"){
						console.log("stop everything");
					}
					else{
						console.log("fetching done...");
						fetching_data = false;
						localStorage.setItem("request_time", res.time);
						var wishlist_data_temp = localStorage.getItem("wishlist_data_temp");
						localStorage.setItem("wishlist_data", wishlist_data_temp);
						var wishlist_data = localStorage.getItem("wishlist_data");
						wishlist_data = JSON.parse(wishlist_data);
						if(wishlist_data && !table_shown){
							var wishlist_data = localStorage.getItem("wishlist_data");
							wishlist_data = JSON.parse(wishlist_data);
							var wishlist_data_array = Object.keys(wishlist_data);
							var datatableArray = [];
							wishlist_data_array.map(function(_data){
								datatableArray.push([
									wishlist_data[_data].id,
									wishlist_data[_data].name,
									wishlist_data[_data].count,
									""
								]);
							});
							// console.log(datatableArray);
							table = $('#show_record_cstm_test').DataTable( {
								data: datatableArray,
								columns: [
									{ title: "Product ID" },
									{ title: "Product Name" },
									{ title: "Count" },
									{ title: "Customers" }
								],
								"columnDefs": [
									{ "orderable": false, "targets": -1, "data": null, "defaultContent": "<button>Click here</button>" }
								],
								"order": [[ 2, "desc" ]],
								"oLanguage": {
									"sLengthMenu": "Show _MENU_ Entries"
								},
								"lengthMenu": [[10,30,60,100], [10,30,60,100]],
							});
						}
						$("#show_record_cstm_test").show();
						$(".loader-container").hide();
						$(".wep-logo").removeClass("wep-logo");
					}
				},
				error: function(err){
					console.log(err);
				}
			})
		}
		localStorage.removeItem("localData_temp");
		localStorage.removeItem("wishlist_data_temp");
		if(hash != localStorage.getItem("store_hash")){
			localStorage.removeItem("wishlist_data");
			localStorage.removeItem("request_time");
		}
		getWishlistProducts(1);
		var wishlist_data = localStorage.getItem("wishlist_data");
		if(wishlist_data){
			table_shown = true;
			wishlist_data = JSON.parse(wishlist_data);
			var wishlist_data_array = Object.keys(wishlist_data);
			var datatableArray = [];
			wishlist_data_array.map(function(_data){
				datatableArray.push([
					wishlist_data[_data].id,
					wishlist_data[_data].name,
					wishlist_data[_data].count,
					""
				]);
			});
			// console.log(datatableArray);
			$("#show_record_cstm_test").show();
			$(".loader-container").hide();
			$(".wep-logo").removeClass("wep-logo");
			table	= $('#show_record_cstm_test').DataTable( {
				data: datatableArray,
				columns: [
					{ title: "Product ID" },
					{ title: "Product Name" },
					{ title: "Count" },
					{ title: "Customers" }
				],
				"columnDefs": [
					{ "orderable": false, "targets": -1, "data": null, "defaultContent": "<button>Click here</button>" }
				],
				"order": [[ 2, "desc" ]],
				"oLanguage": {
					"sLengthMenu": "Show _MENU_ Entries"
				},
				"lengthMenu": [[10,30,60,100], [10,30,60,100]],
			});
		}
		function getUrlParameter(name) {
			name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
			var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
			var results = regex.exec(location.search);
			return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
		}
		$(document).on('click', '#show_record_cstm_test tbody td.details-control', function () {
			var tr = $(this).closest('tr');
			var row = table.row( tr );
	
			if ( row.child.isShown() ) {
				// This row is already open - close it
				row.child.hide();
				tr.removeClass('shown');
			}
			else {
				// Open this row
				row.child( format(row.data()) ).show();
				tr.addClass('shown');
			}
		});
		$(document).on( 'click', '#show_record_cstm_test tbody button', function () {
			var store_hash	= getUrlParameter('store_hash');
			var payload		= getUrlParameter('signed_payload');
			var data		= table.row( $(this).parents('tr') ).data();
			product_id		= data[0];
			var product_name= data[1];	
			var url      	= window.location.href;
			var queryParam 	= url ? url.split('?')[1] : window.location.search.slice(1); 
			
			if(product_name.length>30){
				product_name 	= product_name.substring(0, 30);
				product_name	= product_name+"..";
			}
			window.location = "//wishlist.appsserver.net/bigcommerce_apps/wishlist/load_customer.php?store_hash="+store_hash+"&product_id="+product_id+"&pro_name="+encodeURIComponent(product_name)+"&"+queryParam;
		});
	});
</script>