<?php

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;




// get all promotion from bigcom
if(isset($_GET['store_hash']) )
{
	global $channel_id1;
	$channel_id1 = $_GET["channel_id"];
	global $store_hash;
	$store_hash = $_GET['store_hash'];
	global $access_token;
	$access_token = $db->getSingleColumn( "stores", "access_token", array( "store_id" => $store_hash ));
	global $redemption_type;
	$redemption_type = $_GET["redemption_type"];
	$page=$_GET['page'];


	//$channel_id=$_GET["channels"];
	$all_promotions=get_all_promotions();

	/*echo "<pre>";
	print_r($all_promotions);
	echo "</pre>";*/
	
	// make pagination

	$counPage= $all_promotions["meta"]["pagination"]["total_pages"];
	$current_page=$all_promotions["meta"]["pagination"]["current_page"];
	$pagination="";
	for($i=1;$i<=$counPage;$i++){
		 $class = ($current_page == $i) ? 'active' : ''; // Check if it's the current page
         $pagination .= '<span data-page="'.$i.'" class="'.$class.'">'.$i.'</span>';


	}	

	$all_promotion_row="";
	$formFiled='<div id="append_form">';
	$target_product_ids=array();
	$promotion_product_ids=array();
	$minimum_quantity="";

   foreach ($all_promotions['data'] as $promotion_value)
   {
   	 
		 $created_from=trim($promotion_value["created_from"]);


		 if($promotion_value["created_from"]==$created_from)
		{
		 	// make dynamic form

		 	$apply_once=$promotion_value["rules"][0]["apply_once"];
		 	$stop=$promotion_value["stop"];

		 	$promotion_product_ids=$promotion_value["rules"][0]["action"]["cart_items"]["items"]["products"];
		 	/*echo "promtion ids is:";
		 	print_r($promotion_product_ids);*/

		 	$promotion_minimum_quantity=$promotion_value["rules"][0]["action"]["cart_items"]["quantity"];

		 	$target_product_ids=$promotion_value["rules"][0]["condition"]["cart"]["items"]["products"];
		 	//print_r($product_ids);

		 	$target_minimum_quantity=$promotion_value["rules"][0]["condition"]["cart"]["minimum_quantity"];

		 	//echo "min",$minimum_quantity;

		 	$category=$promotion_value["rules"][0]["action"]["cart_items"]["items"]["categories"][0];

		 	$promtion_quantity=$promotion_value["rules"][0]["action"]["cart_items"]["quantity"];
		 	$target_quantity=$promotion_value["rules"][0]["condition"]["cart"]["minimum_quantity"];


		 	$currency_code=$promotion_value["currency_code"];
		 	$week_frequency=$promotion_value["schedule"]["week_frequency"];
		 	$week_days=$promotion_value["schedule"]["week_days"];

		 	$notificationsArray=$promotion_value["notifications"];

		 	$minimum_spend=$promotion_value["rules"][0]["condition"]["cart"]["minimum_spend"];

		 	$gift_item=$promotion_value["rules"][0]["action"]["gift_item"]["product_id"];
		 	$minimum_order_count=$promotion_value["customer"]["minimum_order_count"];
		 	$customer_group=$promotion_value["customer"]["group_ids"];
		 	$customer_group_ids=implode(",",$customer_group);

		 	if(!empty($customer_group_ids))
		 	{
		 		
		 		
		 		$formField.='<div class="form-group"><label for="name">Customer Group Ids</label><input type="text" class="form-control" id="customer_group_ids" name="minimum_order_count" value="'.$customer_group_ids.'"></div>';

		 	}

		 	if(!empty($minimum_order_count))
		 	{
		 		
		 		
		 		$formField.='<div class="form-group"><label for="name">Minimum Order</label><input type="text" class="form-control" id="minimum_order_count" name="minimum_order_count" value="'.$minimum_order_count.'"></div>';

		 	}

		 	if(!empty($gift_item))
		 	{
		 		
		 		
		 		$formField.='<div class="form-group"><label for="name">Gift Product Id</label><input type="text" class="form-control" id="gift_product_id" name="product_minimum_spend" value="'.$gift_item.'"></div>';

		 	}


		 	if(!empty($minimum_spend))
		 	{
		 		$product_minimum_spend=$minimum_spend;
		 		
		 		$formField.='<div class="form-group"><label for="name">Minimum Spend</label><input type="text" class="form-control" id="product_minimum_spend" name="product_minimum_spend" value="'.$product_minimum_spend.'"></div>';

		 	}


		 	//echo "code $currency_code";

		 	if(!empty($category))
		 	{
		 		$category_ids1=$category;
		 		
		 		
		 		$formField.='<div class="form-group"><label for="name">Category Id</label><input type="text" class="form-control" id="Category_ids" name="Category_ids" value="'.$category_ids1.'"></div>';

			 	if(!empty($promtion_quantity))
			 	{
			 		$formField.='<div class="form-group"><label for="name">Promotion Product Quantity</label><input type="text" class="form-control" id="promotion_product_quantity" name="product_minimum_spend" value="'.$promtion_quantity.'"></div>';
			 		

			 	}

			 	if(!empty($target_quantity))
			 	{
			 		$formField.='<div class="form-group"><label for="name">Target Product Quantity</label><input type="text" class="form-control" id="target_product_quantity" name="product_minimum_spend" value="'.$target_quantity.'"></div>';
			 		

			 	}

		 	}



		 	


		 	if(!empty($promotion_product_ids))
		 	{
		 		//print_r($promotion_product_ids);
		 		
		 		$promotion_product_ids1=$promotion_product_ids[0];
		 		
		 		$formField.='<div class="form-group"><label for="name">Promotion Product Id</label><input type="text" class="form-control" id="Promotion_product_ids" name="Promotion_product_ids" value="'.$promotion_product_ids1.'"></div>';

		 		$formField.='<div class="form-group"><label for="name">Promotion Product Quantity</label><input type="text" class="form-control" id="promotion_minimum_quantity" name="promotion_minimum_quantity" value="'.$promotion_minimum_quantity.'"></div>';
		 	}

		 	if(!empty($target_product_ids))
		 	{
		 		$target_product_ids1=$target_product_ids[0];
		 		
		 		$formField.='<div class="form-group"><label for="name">Target Product Id</label><input type="text" class="form-control" id="targets_product_ids" name="target_product_ids" value="'.$target_product_ids1.'"></div>';

		 		$formField.='<div class="form-group"><label for="name">Target Product Quantity</label><input type="text" class="form-control" id="target_minimum_quantity" name="target_minimum_quantity" value="'.$target_minimum_quantity.'"></div>';
		 	}

		 		if (isset($promotion_value['rules'][0]['action']['cart_value']['discount']["percentage_amount"])) 
		 	    {
				    
				 	$discount_array= $promotion_value['rules'][0]['action']['cart_value']['discount'];
				 	   /* foreach($discount_array as $discount_key=>$discount_value){
				 	    	//echo "discount_key: $discount_key <br>";
				 	    	//echo "discount_value: $discount_value <br>";

				 	    }*/

				 	    $discount_value=$discount_array["percentage_amount"];
				 	    $formField.='<div class="form-group"><label for="name">Percentage Discount</label><input type="text" class="form-control" id="Percentage-Discount" name="Percentage-Discount" value="'.$discount_value.'"></div>';
				}

		 	
		 	if (isset($promotion_value['rules'][0]['action']['cart_items']['discount']["percentage_amount"])) 
		 	    {
				    
				 	$discount_array= $promotion_value['rules'][0]['action']['cart_items']['discount'];
				 	   /* foreach($discount_array as $discount_key=>$discount_value){
				 	    	//echo "discount_key: $discount_key <br>";
				 	    	//echo "discount_value: $discount_value <br>";

				 	    }*/

				 	    $discount_value=$discount_array["percentage_amount"];
				 	    $formField.='<div class="form-group"><label for="name">Percentage Discount</label><input type="text" class="form-control" id="Percentage-Discount" name="Percentage-Discount" value="'.$discount_value.'"></div>';
				}

				if (isset($promotion_value['rules'][0]['action']['cart_value']['discount']["fixed_amount"])) {
				    
				 	$discount_array= $promotion_value['rules'][0]['action']['cart_value']['discount'];
				 	    /*foreach($discount_array as $discount_key=>$discount_value){
				 	    	echo "discount_key: $discount_key <br>";
				 	    	echo "discount_value: $discount_value <br>";

				 	    }*/
				 	     $discount_value=$discount_array["fixed_amount"];
				 	    $formField.='<div class="form-group"><label for="name">Fixed Discount</label><input type="text" class="form-control" id="Fixed-Discount" name="Fixed-Discount" value="'.$discount_value.'"></div>';
				}
				 if(!empty($apply_once))
			 	 {

				    $formField .= '<div class="form-group" style="display:none;"><label for="name">Apply Once</label><select class="form-select" aria-label="Default select example" name="apply-once" id="apply-once"><option value="true" ' . (trim($apply_once) == "1" ? 'selected' : '') . '>True</option><option value="false" ' . (trim($apply_once) == "0" ? 'selected' : '') . '>False</option></select></div>';
				}
			 	 if(!empty($stop))
			 	 {

		 	       $formField .= '<div class="form-group"><label for="name">Stop</label><select class="form-select" aria-label="Default select example" name="stop" id="stop"><option value="false" ' . ($stop == "false" ? 'selected' : '') . '>False</option><option value="true" ' . ($stop == "true" ? 'selected' : '') . '>True</option></select></div>';
			 	 }

		 	    $formField .= '<div class="form-group" style="display:none;"><label for="currency_code">Currency Code</label><select class="form-select" id="currency_code" name="currency_code" aria-label="Default select example">';
				$formField .= '<option value="USD" ' . ($currency_code == "USD" ? 'selected' : '') . '>USD</option>';
				$formField .= '<option value="EUR" ' . ($currency_code == "EUR" ? 'selected' : '') . '>EUR</option>';
				$formField .= '<option value="CAD" ' . ($currency_code == "CAD" ? 'selected' : '') . '>CAD</option>';
				$formField .= '<option value="NZD" ' . ($currency_code == "NZD" ? 'selected' : '') . '>NZD</option>';
				$formField .= '<option value="PKR" ' . ($currency_code == "PKR" ? 'selected' : '') . '>PKR</option>';
				$formField .= '</select></div>';

				// build notification  form field

				// end dynamic form

		 	  // $formFiled=$formFiled."</div>";


		 	

			   //echo  json_encode($formFiled);

		 	
				$start_date = date("Y-m-d", strtotime($promotion_value["start_date"]));
				$end_date = date("Y-m-d", strtotime($promotion_value["end_date"]));

		     
			$all_promotion_row .= '<tr><td scope="row" style="display: none;" id="dynamic-form">' . $formField . '</td><td scope="row" style="display: none;" >' . $promotion_value["id"] . '</td><td><input type="checkbox" name="promtion_ids[]" value="' . $promotion_value["id"] . '"></td><td>' . $promotion_value["name"] . '</td><td>' . $start_date . '</td><td>' . $end_date . '</td><td>' . $promotion_value["status"] . '</td><td><button class="btn btn-primary update-button"data-bs-toggle="modal" data-bs-target="#updateModal">Edit</button></td></tr>';

		    $formField='<div id="append_form">';
		    $target_product_ids=array();
	        $promotion_product_ids=array();
		    $minimum_quantity="";


		}

   }
	 

	  echo json_encode(["all_promotions"=>$all_promotion_row,"pagination"=>$pagination,"form_field"=>$formFiled]);
}

function get_all_promotions()
{
	global $store_hash, $access_token ,$channel_id1,$redemption_type,$page;
	$url = "https://api.bigcommerce.com/stores/".$store_hash."/v3/promotions?page=$page&limit=250&redemption_type=$redemption_type&status=ENABLED&channels=$channel_id1";

		$headers = array(
			"accept: application/json",
			"content-type: application/json",
			"x-auth-client: ".CLIENT_ID,
			"x-auth-token: ".$access_token
		);


	$all_promotions1= curlGetRequest($url, $headers);
	return $all_promotions1;

}

?>

