<?php 
	// ini_set("error_reporting", E_ALL);
	// ini_set("display_errors", true);

	include_once 'inc/functions.php';
	include_once 'inc/database.php';
	
	include_once 'requestFunctions.php';
	
	require_once __DIR__ . '/vendor/autoload.php';
	use Bigcommerce\Api\Client as Bigcommerce;
    
	$config = array();
	$types = array(
		"per_item_discount"=> "Per item discount", 
		"per_total_discount"=> "Order total discount", 
		"shipping_discount"=> "Shipping discount", 
		"percentage_discount"=> "Percentage discount"
	);

	if( isset($_GET['signed_payload']) || (isset($_GET['store_hash']) && !empty($_GET['store_hash'])) ){
		$data = decodeSignedRequest($_GET['signed_payload']);
		
		// To expire calls after 1 hour -- START
		if (isset($data['timestamp'])) {
    		$timestamp	= $data['timestamp'];
    		$expiryTime = $timestamp + 3600;
    		$curtime 	= time();
    		
    		if ($expiryTime < $curtime ) {
    			die('Request Expired');
    		}
		}
		
		
		$hash = isset($data['store_hash']) ? $data['store_hash'] : $_GET['store_hash'];
		$channel_id	= $_GET['channel_id'] ? $_GET['channel_id'] : 1;
		$access_payload	= $_GET['signed_payload'];
		$access_token = $db->getSingleColumn( "stores", "access_token", array( "store_id" => $hash ));
		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);	

		$API_PATH = 'https://api.bigcommerce.com/stores/'.$hash;

		$headers = array(
			"accept: application/json",
			"content-type: application/json",
			"x-auth-client: ".CLIENT_ID,
			"x-auth-token: ".$access_token
		);
		$store_hash = $hash;
		
		$isActiveSubscription = $db->select("subscription", "*" , array( "store_id" => $store_hash,"status" => "active", "channel_id"=> $channel_id));

		$created_date = $db->select("stores", "*", array( "store_id" => $store_hash, "channel_id"=> $channel_id));
		
		if(array_search($created_date["admin_email"], $exception_emails) !== false){
			$isActiveSubscription = true;
		}

		$added_7_days = new DateTime($created_date["created_at"]);
		$added_7_days = $added_7_days->format('Y-m-d H:i:s');	
		$remaining_days = date_diff(date_create($added_7_days), date_create(date("Y-m-d h:i:s")));

		$expired_on = "";
		$subscription_expired = false;

		if( ($remaining_days->d <= 7 && $remaining_days->m == 0 && $remaining_days->y == 0) ) {}
		else{
			if($isActiveSubscription){}
			else{
				$get_stripe_subscription_id = $db->getSingleColumn( "subscription", "stripe_subscription_id", array( "store_id" => $store_hash, "channel_id"=> $channel_id ));			
				if($get_stripe_subscription_id){				
					$get_subscription_payments = $db->getSingleColumn( "subscription", "unsubscribed_at", array( "stripe_subscription_id" => $get_stripe_subscription_id ));
					$date = strtotime($get_subscription_payments);
					$expired_on = date('F jS, Y', $date);
					$subscription_expired = true;				
				}
				else{
					$date = strtotime($added_7_days);
					$date = strtotime("+7 day", $date);
					$expired_on = date('F jS, Y', $date);
				}
			}
		}		
	}

	$url = $API_PATH."/v2/store";
	$res = curlGetRequest($url, $headers);
	
	$timezone_val = gmdate("H:i", str_replace("-", "", $res["timezone"]["raw_offset"]));
	
	if(strpos($res["timezone"]["raw_offset"], "-") !== false){
		$timezone_val = "-".$timezone_val;
	}
	else{
	    $timezone_val = "+".$timezone_val;
	}
	
	require_once("productPromotions.php");
    require_once("categoryPromotions.php");
    require_once("orderPromotions.php");
    require_once("customerPromotions.php");

	// custom code for promotions app
		
	if (isset($_POST["submit"])) {
		try{
			$file		= $_FILES["file"]["name"];
			$fileType	= strtolower(pathinfo($file,PATHINFO_EXTENSION));
			if($fileType=='csv'){
				$file_name	= __DIR__."/assets/temp_files/".rand(111,999)."_".time()."_".$_FILES["file"]["name"];
				move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);
				$row = 1;
				$response = array();
				$complete_response = array();
				$success_counter = 0;
				if (($handle = fopen($file_name, "r")) !== FALSE && $_FILES["file"]['size'] > 0) {
					try{
						while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
							if($row == 1){
								$row++;
								continue;
							}
							else{
								$row++;
								if($_POST["promo-type"] == "product1"){
									$response = product1($data); // buy one get one free
								}
								else if($_POST["promo-type"] == "product2"){
									$response = product2($data); // Buy (X units) of Product A, Get (Y units) of Product B For $ or % Off Per Unit
								}
								else if($_POST["promo-type"] == "product3"){
									$response = product3($data); // Get $ or % Off Product X
								}
								else if($_POST["promo-type"] == "product4"){
									$response = product4($data); // Take X% Off the Most Expensive Item in The Cart
								}
								else if($_POST["promo-type"] == "product5"){
									$response = product5($data); // Amount Off
								}
								else if($_POST["promo-type"] == "product6"){
									$response = product6($data); // Percentage Off
								}
								else if($_POST["promo-type"] == "category1"){
									$response = category1($data); // Get a $ or % Discount to Each Item in One or More Categories
								}
								else if($_POST["promo-type"] == "category2"){
									$response = category2($data); // Get a % discount to each Item in one or more categories, exclude items on sale
								}
								else if($_POST["promo-type"] == "category3"){
									$response = category3($data); // Buy X Units in (Category A), Get Y Additional Units in the Same Category Free (Must be of Equal or Lesser Value)
								}
								else if($_POST["promo-type"] == "order1"){
									$response = order1($data); // Spend X$ Get X$ Off Order
								}
								else if($_POST["promo-type"] == "order2"){
									$response = order2($data); // Order at Least $X Get X Item Free
								}
								else if($_POST["promo-type"] == "customer1"){
									$response = customer1($data); // X% off for X customer group
								}
								else if($_POST["promo-type"] == "customer2"){
									$response = customer2($data); // X% off for customers with total order count of Y or more
								}

								if($response['status'] == "success"){
									$success_counter++;
								}
								else{
									$msgLen = $complete_response["message"];
									if(strlen($msgLen) > 0){
										$complete_response["message"] .= ', ';
									}
									$complete_response["message"] .= '"'.$response["message"].'"';
								}
							}
						}
						
						if($complete_response['message'] && $success_counter == 0){
							$error = "Following Promotions were not created due to some error:";

							echo "<script>window.location.href='load.php?message=".$error." ".$complete_response['message']."&status_error=status_error&store_hash=".$hash."&activeTab=promotions'</script>";
						}                    
						else{
							$total_count = $row - 2; // because row starts with 1, and 1st row is not in use.
							$message = $success_counter."/".$total_count." Promotion(s) created successfully!";
							$status = "status_success";
							$error = "";
							if($complete_response['message']){
								$error = "Following Promotions were not created due to some error:".$complete_response['message'];
							}

							echo "<script>window.location.href='load.php?message=".$message."&status_success=".$status."&error=".$error."&store_hash=".$hash."&activeTab=promotions'</script>";
						}
					}
					catch(Exception $e) {
						echo "<script>window.location.href='load.php?message=Something went wrong try again later!&status_error=status_error&store_hash=".$hash."&activeTab=promotions'</script>";
					}
					fclose($handle);
				}
				
				unlink($file_name);
				
			}else{
				echo "<script>window.location.href='load.php?message= Wrong file type, Only CSV file is allowed.&status_error=status_error&store_hash=".$hash."&activeTab=promotions'</script>";
			}
		}
		catch(Exception $e) {
			print_r($e); 
		}
	}

	// custom code for promotions app
	

	function subscribeBtn($days){
		global $store_hash;
		global $channel_id;
        ?>
        <div style="padding-right: 5px;" class="alert alert-warning fade show d-flex align-items-center justify-content-between mb-3 mt-3" role="alert">
            <div>
                <svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Info:">
                    <use xlink:href="#info-fill" />
                </svg>
                You are using a free trial which will expire <? echo $days; ?>. Subscribe to prevent any interruption.
            </div>
			<a href="subscription/choose_plan.php?menu=subscription&store_hash=<?php echo $store_hash; ?>&channel_id=<?echo $channel_id;?>">
				<button type="button" class="btn btn-primary save-btn" >Subscribe</button>
			</a>
        </div>
        <?php
    }
    function subscription_bar(){
        global $remaining_days;
        global $isActiveSubscription;
        if(( ($remaining_days->d <= 7 && $remaining_days->m == 0 && $remaining_days->y == 0)) && !$isActiveSubscription) {
            if($remaining_days->days < 6) { 
                $days = 7 - $remaining_days->days; 
                subscribeBtn("in $days days"); 
            }
            else if($remaining_days->days == 6) {
                subscribeBtn("tomorrow"); 
            }
            else{
                subscribeBtn("today"); 
            }
        } 
    }
	function getActiveTab($tabName){
		if($_GET["activeTab"]) {
			if($_GET["activeTab"] == $tabName) echo "show active"; 
		}
		else if($tabName == "promotions"){
			echo "show active";
		}
	}
	function appendFormField($field_name, $field_label, $type){
		?>
			<div class="row align-items-c mb-3 form-group p-1">
				<div class="textOnInput">
					<label for="<?php echo $field_name ?>" ><?php echo $field_label ?></label>
					<input
						required class="form-control" min="<?php echo date("Y-m-d"); ?>"
						name="<?php echo $field_name ?>"
						type="<?php echo $type ?>" id="<?php echo $field_name ?>" 
					>
				</div>
			</div>
		<?php
	}
	function appendDropdownFormField($field_name, $field_label, $values){
		?>
			<div class="row align-items-c mb-3 form-group p-1">
				<div class="textOnInput">
					<label for="<?php echo $field_name ?>" ><?php echo $field_label ?></label>
					<select 
						id="<?php echo $field_name ?>"  name="<?php echo $field_name; ?>" 
						required class="form-control"
					>
					<option value="" disabled selected >Select type</option>
					<?php foreach ($values as $key => $option) {
						echo "<option value='$key'>$option</option>";
					} ?>
					</select>
				</div>
			</div>
		<?php
	}	
	function _appendDropdownFormField($field_name, $field_label, $values){
		global $channel_id;
		?>
			<div class="row align-items-c mt-3 mb-3 form-group p-1">
				<label for="<?php echo $field_name ?>" ><?php echo $field_label ?></label>
				<div class="textOnInput">
					<select 
						id="<?php echo $field_name ?>"  name="<?php echo $field_name; ?>" 
						style="width: 400px;"
						required class="form-control form-select"
					>
					<?php foreach ($values as $key => $option) {
						?>
							<option <? if($option["channel_id"] == $channel_id){ echo "selected"; }?> value='<? echo $option["channel_id"]; ?>'><? echo $option["store_name"]; ?></option>
						<?php
					} ?>
					</select>
				</div>
			</div>
		<?php
	}
?>
<!doctype html>
<html>
    <head>
	
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title><?php echo APP_HEADING; ?></title>
        
		<link type="text/css" rel="stylesheet" href="<?php  echo BASE_PATH ?>assets/css/style.css?v=2.0.5">
		<link type="text/css" rel="stylesheet" href="<?php  echo BASE_PATH ?>assets/css/custom.css">
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
		<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>

		<!-- bootstrap -->

		 <!-- Add icon library -->
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <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>  
		<style>
			#coupon-form input, #main_content select{
			    width: 400px !important;
			        padding: 0.375rem !important;
			}
			.textOnInput label {
                font-weight: bold;
            }
			.trial {
				right: 5px;
				left: 5px;
				background: #337AB7;
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 50px;
				padding: 20px;
				color: white;
				width: 100%;
			}
			.cstm-btn-success {
				background-color: #337AB7;
				border-color: #337AB7;
				margin-left: 5px;
			}
			.cstm-btn-success a{
				color: #fff !important;
				text-decoration:none;
			}
			#loader-container {
				z-index:99
			}
			.bottom-button{
				position: fixed;
				width: 100%;
				bottom: 0px;
				right: 0px;
				background: white;
				padding: 10px;
				justify-content: flex-end
			}
			.all_promtions_button{
				text-decoration: none;
			    background: #337AB7;
			    height: 40px;
			    color: white;
			    line-height: 40px;
			    /* padding: 3px; */
			    padding: 0px 6px;
			    border-radius: 6px;
			    font-size: 15px;
			    font-weight: 700;
			}
			.all_promtions_button:hover{
				color: white!important;
			}
		</style>

    </head>
    <body>
		<div id="loader-container" >
			<div id="loader"></div>
		</div>
		
		<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
            <symbol id="check-circle-fill" fill="currentColor" viewBox="0 0 16 16">
                <path
                    d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z" />
            </symbol>
            <symbol id="info-fill" fill="currentColor" viewBox="0 0 16 16">
                <path
                    d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm.93-9.412-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287zM8 5.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2z" />
            </symbol>
            <symbol id="exclamation-triangle-fill" fill="currentColor" viewBox="0 0 16 16">
                <path
                    d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
            </symbol>
        </svg>
		<?php
			include_once("subscription/header.php");
		?>
        <div class="app_conatiner">
			<div id="main_content">
				<? subscription_bar(); ?>
				<div class="sub_conatiner clearfix">
					<div>
						<?php 
							$href = "https://store-".$hash.".mybigcommerce.com/manage/marketing/";
							if($_GET["message"] && $_GET['status_success'] && $_GET["error"]){
								?>
								<div class="promo-message-div <?php echo $_GET['status_success'] ?>" >
									<div>
										<span><?php echo $_GET["message"] ?></span>
										<a href="<?php echo $href; ?>promotion-manager" >View in bigcommerce dashboard</a>
									</div>
									<div onClick="removeMessage();" >x</div>
								</div>
								<div class="mt-1 mb-3 promo-message-div status_error" >
									<span><?php echo $_GET["error"] ?></span>
									<div onClick="removeMessage();" >x</div>
								</div>
								<?php
							}
							else if($_GET["message"] && $_GET['status_success']){
								?>
									<div class="mb-5 promo-message-div <?php echo $_GET['status_success'] ?>" >
										<div>
											<span><?php echo $_GET["message"] ?></span>
											<a href="<?php echo $href; ?>promotion-manager" >View in bigcommerce dashboard</a>
										</div>
										<div onClick="removeMessage();" >x</div>
									</div>
								<?php
							}
							else if($_GET["coupon_message"]){
								?>
									<div class="mb-5 promo-message-div status_success" >
										<div>
											<span><?php echo $_GET["coupon_message"] ?></span>
											<a href="<?php echo $href; ?>coupons" >View in bigcommerce dashboard</a>
										</div>
										<div onClick="removeMessage();" >x</div>
									</div>
								<?php
							}
							else if($_GET["subscribe"]){
								?>
									<div class="mb-5 promo-message-div status_success" >
										<div>
											<span><?php echo $_GET["subscribe"] ?></span>
										</div>
										<div onClick="removeMessage();" >x</div>
									</div>
								<?php
							}
							if($_GET["message"] && $_GET['status_error']){
								?>
									<div class="mb-5 promo-message-div <?php echo $_GET['status_error'] ?>" >
										<span><?php echo $_GET["message"] ?></span>
										<div onClick="removeMessage();" >x</div>
									</div>
								<?php
							}
						?>
					</div>
					<?php
						if($expired_on){
							?>
								<div style="text-align: center" >
									<div class="m-5">
										<svg height="50px" viewBox="0 0 509.87489 509.87489" width="50px" xmlns="http://www.w3.org/2000/svg"><path d="m23.503906 198.367188 174.863282-174.863282c31.242187-31.242187 81.898437-31.242187 113.140624 0l174.863282 174.863282c31.242187 31.242187 31.242187 81.898437 0 113.140624l-174.863282 174.863282c-31.242187 31.242187-81.898437 31.242187-113.140624 0l-174.863282-174.863282c-31.242187-31.242187-31.242187-81.898437 0-113.140624zm0 0" fill="#ffda6b"/><g fill="#fff"><path d="m254.929688 142.9375c8.835937 0 16 7.164062 16 16v128c0 8.835938-7.164063 16-16 16-8.835938 0-16-7.164062-16-16v-128c0-8.835938 7.164062-16 16-16zm0 0"/><path d="m238.929688 334.9375h32v32h-32zm0 0"/></g></svg>
									</div>
									<div class = "trial-expired-container" >
										<h4>Your <?php if($subscription_expired == true ) echo "subscription"; else  echo "trial"; ?> has expired </h4>
										<p>Thank you for using our app. Your <?php if($subscription_expired == true ) echo "subscription"; else  echo "free trial"; ?> was expired on <?php echo $expired_on; ?>. </p>
										<p style="width: 75%; margin: auto;" >To resume using our awesome app, please <?php if($subscription_expired == true ) echo "proceed with the payment"; else  echo "upgrade your account to paid account"; ?>. All of your data will be saved for the next few weeks. If you have any questions, please <a href="//www.webecommercepros.com/contact-us" style="color: #0d6efd" target="_blank">contact support.</a></p>
									</div>
									<div class="expiry-action-container m-5" >
										<a class="add-payment-method" href='subscription/choose_plan.php?channel_id=<?php echo $channel_id; ?>&menu=subscription&store_hash=<?php echo $store_hash; ?>'>Proceed to Payment</a>
									</div>
								<div>
							<?php
						}
						else{
							?>
            					<div class="background-white p-3" >
            						<ul class="nav nav-tabs mt-3 mb-3 align-items-c" id="myTab" role="tablist">
            							<li class="nav-item promotions-btn" role="presentation">
            								<button class="nav-link <?php echo getActiveTab("promotions"); ?>" id="promotions-tab" data-bs-toggle="tab" data-bs-target="#promotions" type="button" role="tab" aria-controls="promotions" aria-selected="true">Promotions</button>
            							</li>
            							<li class="nav-item coupons-btn" role="presentation">
            								<button class="nav-link <?php echo getActiveTab("coupons"); ?>" id="coupons-tab" data-bs-toggle="tab" data-bs-target="#coupons" type="button" role="tab" aria-controls="coupons" aria-selected="false">Coupons</button>
            							</li>
            						</ul>
            					</div>
            					<div class="tab-content p-5 background-white" id="myTabContent">
            						<div class="tab-pane fade <?php echo getActiveTab("promotions"); ?>" id="promotions" role="tabpanel" aria-labelledby="promotions-tab">

            							<div class="d-flex justify-content-between">
            							   <h4 class="mb-5">Promotions</h4>
            							   <a class="all_promtions_button" href='get_all_promotions.php?redemption_type=AUTOMATIC&<?php  echo "hash=$hash&channel=All Channels"?>' style="display:none;">All Promotions</a>
            						    </div>
            							<form method="post" name="promo-form" id="promo-form" enctype="multipart/form-data" class="m-5">
            								<div class="mb-5" >
            									<p>Every promotion type has different CSV template with its relevant fields and the sample for the template will be available for download upon selection of the promotion type.</p>
            								</div>
            								<div class="row align-items-c mb-3 form-group p-1">
            									<div class="textOnInput">
            										<label for="promo-category">Select Promotion</label>
            										<select required="true" class="form-control" id="promo-category" name="promo-type">
            											<option value="" disabled selected>Choose Option</option>
            											<option value="product">Product Level</option>
            											<option value="category">Category Level</option>
            											<option value="order">Order Level</option>
            											<option value="customer">Customer Level</option>
            										</select>
            									</div>
            								</div>
            								<div style="display:none" class="row align-items-c mb-3 form-group p-1 promo-type-div">
            									<div class="textOnInput">
            										<label for="promo-type">Select Promotion Type</label>
            										<select required="true" class="form-control" id="promo-type" name="promo-type"></select>
            									</div>
            								</div>
            								
            								<div class="form-group hide w-25 p-2">
            									<label for="file">Upload File</label>
            									<input name="file" type="file" class="form-control-file" id="file" accept=".csv" required="true">
            								</div>
            
            								<div class="hide p-2">
            									<span> Download <a href="#" id="download-file" >sample csv for </a><span  class="download-sample-btn"></span></span>
            								</div>
            
            								<div class="mt-5 hide p-2" >
            									<button type="submit" name="submit" id="submit-form" class="btn support_btn mb-2">Submit</button>
            								</div>
            							</form>
            						</div>
            						<div class="tab-pane fade <?php echo getActiveTab("coupons"); ?>" id="coupons" role="tabpanel" aria-labelledby="coupons-tab">
            							<div class="d-flex justify-content-between">
            							  <h4 class="mb-5">Single Use Coupons</h4>
            							  <a class="all_promtions_button" href='get_all_promotions.php?redemption_type=COUPON&<?php  echo "hash=$hash&channel=All Channels"?>' style="display:none;">All Coupons</a>
            						    </div>
            							<form method="post" target="_blank" name="coupon-form" id="coupon-form" enctype="multipart/form-data" class="m-5">
            							    <p>Please fill in the following details. The app will create coupons automatically and will be available in "Marketing -> Coupon Codes" section in your BigCommerce dashboard. It will also offer you a CSV download containing newly created coupons.</p>
            								<?php appendFormField("limit", "How many coupons you want to create (Max 50)", "number") ?>
            								<?php appendDropdownFormField("type", "Type", $types) ?>
            								<?php appendFormField("amount", "Amount", "number") ?>
            								<?php appendFormField("expiry", "Expiry", "date") ?>
            								
            								<div class="mt-5 p-1" >
            									<button type="submit" name="coupon-submit" id="coupon-form" class="btn support_btn mb-2">Submit</button>
            								</div>
            							</form>
            						</div>
            					</div>
            				<?php
						}
					?>
					<div class="logo-img" >
						<a href="https://www.webecommercepros.com/">
							<img src="<?php BASE_PATH ?>assets/images/logo.png" />
						</a>
					</div>
				</div>				
			</div>				
			<script>
				function exportToCsv(filename, rows) {
					var processRow = function (row) {
						var finalVal = '';
						for (var j = 0; j < row.length; j++) {
							var innerValue = row[j] === null ? '' : row[j].toString();
							if (row[j] instanceof Date) {
								innerValue = row[j].toLocaleString();
							};
							var result = innerValue.replace(/"/g, '""');
							if (result.search(/("|,|\n)/g) >= 0)
								result = '"' + result + '"';
							if (j > 0)
								finalVal += ',';
							finalVal += result;
						}
						return finalVal + '\n';
					};

					var csvFile = '';
					for (var i = 0; i < rows.length; i++) {
						csvFile += processRow(rows[i]);
					}

					var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
					if (navigator.msSaveBlob) { // IE 10+
						navigator.msSaveBlob(blob, filename);
					} else {
						var link = document.createElement("a");
						if (link.download !== undefined) { // feature detection
							// Browsers that support HTML5 download attribute
							var url = URL.createObjectURL(blob);
							link.setAttribute("href", url);
							link.setAttribute("download", filename);
							link.style.visibility = 'hidden';
							document.body.appendChild(link);
							link.click();
							document.body.removeChild(link);
						}
					}
					setTimeout(() => {
						window.location.href="load.php?store_hash=<?php echo $hash; ?>&activeTab=coupons&coupon_message=Coupons created successfully.";
					}, 100);
				}
				var fileNames = {
					"product1":"Buy One Get One Free",
					"product2":"Buy (X units) of Product A, Get (Y units) of Product B For Z percentage Off Per Unit",
					"product3":"Get percentage Off Product X",
					"product4":"Get X percentage Off the Most Expensive Item in the Cart",
					"product5":"Get $X off of a Product Amount",
					// "product6":"Get X percentage off of a Product",
					// "product7":"Buy three for the price of two",

					"category1":"Get a $ or percentage Discount to Each Item in One or More Categories",
					"category2":"Get a $ or percentage off discount to each item in one or more categories, exclude items on sale",
					"category3":"Buy X Units in (Category A), Get Y Additional Units in the Same Category Free (Must be of Equal or Lesser Value)",
					
					"order1":"Spend $X Get Y$ Off Order",
					"order2":"Order at least $X Get Y Item Free",

					"customer1":"X percentage off for Y customer group",
					"customer2":"X percentage off for customers with a total order count of Y or more",
				}
				$("#promo-category").on("change", function(element){
					$("#promo-type").html("");
					var type = element.target.value;
					var appendData = "<option value='' disabled selected>Choose Option</option>";
					var category_array = [];
					if(type == "product"){
						category_array = [
							{name: fileNames.product1, value:"product1"},
							{name: fileNames.product2, value:"product2"},
							{name: fileNames.product3, value:"product3"},
							{name: fileNames.product4, value:"product4"},
							{name: fileNames.product5, value:"product5"},
							// {name: fileNames.product6, value:"product6"},
							// {name: fileNames.product7, value:"product7"},
						];

					}
					else if(type == "category"){
						category_array = [
							{name: fileNames.category1, value:"category1"},
							{name: fileNames.category2, value:"category2"},
							{name: fileNames.category3, value:"category3"},
						];
					}
					else if(type == "order"){
						category_array = [
							{name: fileNames.order1, value:"order1"},
							{name: fileNames.order2, value:"order2"},
						];
					}
					else if(type == "customer"){
						category_array = [
							{name:fileNames.customer1, value:"customer1"},
							{name:fileNames.customer2, value:"customer2"},
						];

					}
					category_array.map(item=>{
						appendData +="<option value='"+item.value+"' >"+item.name+"</option>"
					});
					$(".hide").hide();
					$("#promo-type").append(appendData);
					$(".promo-type-div").show("");
				});
				$("#promo-type").on("change", function(element){
					var typeName = $("#promo-type").val();
					var fileName = "assets/files_to_download/"+fileNames[typeName]+".csv";
					$(".download-sample-btn").html("" + fileNames[element.target.value] +" promotion");
					$("#download-file").attr("href",fileName);
					$("[name='file']").val("");
					$(".hide").slideDown();
				});
				$("#download-file").on("click", function(){
					var type = $("#promo-type").val();
				});
				function removeMessage(){
					window.location.href="load.php?store_hash=<?php echo $hash; ?>";
				}
				$("#promo-form").on("submit",function(){
					$("#loader-container").show();
				});
				$("#coupon-form").on("submit",function(event){
					event.preventDefault();
					var limit = $("#limit").val();
					var type = $("#type :selected").val();
					var amount = $("#amount").val();
					var expiry = $("#expiry").val();
					if(limit < 1 || limit > 50){
						alert("Please enter a valid number");
						$("#limit").focus();
					}
					else if(type == ""){
						alert("Please select a type");
						$("#type").focus();
					}
					else if(amount < 1){
						alert("Please enter a valid amount");
						$("#amount").focus();
					}
					else if(type == "percentage_discount" && amount > 100){
						alert("Please enter a valid percentage amount");
						$("#amount").focus();
					}
					else if(!expiry){
						alert("Please select a valid date");
						$("#expiry").focus();
					}
					else{
						$("#loader-container").show();
						$.ajax({type: "POST",
							dataType: 'json',
							crossDomain:true,
							url: "export_coupon.php",
							data: {
								"store_hash": "<?php echo $hash; ?>",
								"coupon_submit": true,
								"limit": limit,
								"type": type,
								"amount": amount,
								"expiry": expiry,
								"timezone": "<?php echo $timezone_val; ?>"
							},
							success:function(result) {
								var time = Date.now();
								console.log(result);
								var file_name	= "single_use_coupons_"+time+".csv";						
								exportToCsv(file_name,result.data);
								// $("#loader-container").hide();
							}
						});
					}
				});
				$(document).on("click", "#type", function(){
                    if($(this).val() == "percentage_discount"){
                        $("label[for='amount']").html("Percentage")
                    }
                    else{
                        $("label[for='amount']").html("Amount")
                    }
                })
			</script>
		</div>				
	</body>				
</html>