<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header("Access-Control-Allow-Headers: Authorization, Content-Type");
header("Access-Control-Allow-Origin: *");
header('content-type: application/json; charset=utf-8');	


// New Shopify Api
use Osiset\BasicShopifyAPI\BasicShopifyAPI;
use Osiset\BasicShopifyAPI\Options;
use Osiset\BasicShopifyAPI\Session;


class FrontController extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */

	public  $api,$shopData;
	public $shop;
	public function __construct()
	{
		parent::__construct();// you have missed this line.
		
		
		$options = new Options();
		$options->setVersion(SHOPIYF_VERSION);
		$options->setApiKey(SHOPIFY_API_KEY);
		$options->setApiSecret(SHOPIFY_SECRET_KEY);
		// Create the client and session
		$this->api = new BasicShopifyAPI($options);
		$this->shop = $this->input->post('shop')??''; 
		$this->shopData =$this->adminModel->get_row("app_record",array("shop_address"=>$this->shop));
		if(!$this->shop || !$this->shopData){
			echo "404 not found";
		}
	
		
	}

	function products(){
		echo json_encode(['error'=>'404 not found']);
		die();
		if($this->input->post("subTotal") && $this->input->post("products")){
			$subTotal=$this->input->post("subTotal");
			$products=$this->input->post("products");

			
			$token = $this->shopData->shop_token??'';
			$this->api->setSession(new Session($this->shop, $token));
			$productsIds =explode(",",$products);
			
		    $condition=["shop_name"=>$this->shop,'location'=>"thankuPage"];
		    $offers=[];
		    $whereOn=array_merge($condition,["triggerOn"=>"minValue","minValue<="=>$subTotal,"status"=>1]);
		    $getOffers=$this->adminModel->get_data('funnels',$whereOn);
		    if($getOffers){
			    foreach($getOffers as $keys){
			    	$offer=json_decode($keys->offer);
			    	$id=base64_encode($keys->id);
			    	
			    	$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
			    	$offers[]=["id"=>$id,"funnelName"=>$keys->funnelName,"offer"=>$offer,"design"=>json_decode($keys->design),"settings"=>json_decode($keys->settings),"language"=>json_decode($keys->language),"products"=>$products,"position"=>$keys->position];
			    	
			    }
		    }
		    $whereOnAll=array_merge($condition,["triggerOn"=>"all","status"=>1]);
		    $getOffers=$this->adminModel->get_data('funnels',$whereOnAll);
		    if($getOffers){
			    foreach($getOffers as $keys){
			    	$id=base64_encode($keys->id);
			    	$offer=json_decode($keys->offer);
			    	
			    	$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
			    	$searchKey=array_search($id, array_column($offers, 'id'));
			    	if($searchKey>-1){
			    		continue;
			    	}
			    	$offers[]=["id"=>$id,"funnelName"=>$keys->funnelName,"offer"=>$offer,"design"=>json_decode($keys->design),"settings"=>json_decode($keys->settings),"language"=>json_decode($keys->language),"products"=>$products,"position"=>$keys->position];
			    	
			    }

			  
		    }

		   	if(is_array($productsIds)){
		   		$whereOnIds=array_merge($condition,["triggerOn"=>"products","status"=>1]);
		   		foreach($productsIds as $productId){
		   			$keys=$this->adminModel->get_front_row('funnels',$whereOnIds,["recommendedProduct"=>$productId]);
		   			
		   			if($keys){
			   			$id=base64_encode($keys->id);
				    	$offer=json_decode($keys->offer);
				    	//$offers[$id]=["id"=>$id,"funnelName"=>$keys->funnelName,"offer"=>json_decode($keys->offer),"design"=>json_decode($keys->design),"settings"=>json_decode($keys->settings),"language"=>json_decode($keys->language)];

				    	$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
				    	$searchKey=array_search($id, array_column($offers, 'id'));
				    	if($searchKey>-1){
				    		continue;
				    	}
				    	$offers[]=["id"=>$id,"funnelName"=>$keys->funnelName,"offer"=>$offer,"design"=>json_decode($keys->design),"settings"=>json_decode($keys->settings),"language"=>json_decode($keys->language),"products"=>$products,"position"=>$keys->position];
			    	}
			    	//$offers[$id]["products"]=$products;
		   		}

		   		
		   	}

		   	echo json_encode(["offers"=>$offers,"withCurrency"=>$this->shopData->withCurrency,"withoutCurrency"=>$this->shopData->withoutCurrency]);
		    die();
		   
		  //  		$result = $this->api->rest("get","/admin/api/products.json",->rec["ids"=>$offer->offerProduct ,"fields"=>"id,title,handle,images,options,variants","status"=>"active"]);

		  //  		$result=$this->adminModel->getBodyContainer($result,'products');
		  //  		$productData=[];
			// foreach($result as $value){
			// 	//$value["body_html"]=strip_tags($value["body_html"]);
			// 	$value["discount"]=['discountValue'=>$offer->discountValue,"type"=>$offer->discount,"minQty"=>$offer->minQty];
			// 	$inventory=false;
			// 	$variants=[];
			// 	foreach($value["variants"] as $variant){
			// 		if($variant['inventory_quantity']>0 || $variant['inventory_quantity']<0){
			// 			array_push($variants,$variant);
			// 			$inventory=true;
			// 		}
			// 	}
			// 	if($inventory){
			// 		$value["variants"]=$variants;
			// 		array_push($productData, $value);
			// 	}

			// }

			// echo json_encode($productData);
		}
		// $request=$this->api->rest("get","/admin/api/products.json",["limit"=>5,"fields"=>"id,title,variants,images,handle"]);
		// $products = $this->adminModel->getBodyContainer($request,"products"); 
		// echo json_encode($products);

	}

	// new coditions
	public function getByProducts()
	{
		echo json_encode(['error'=>'404 not found']);
		die()
		// code...
		if($this->input->post("subTotal") && $this->input->post("products")){
			$subTotal=$this->input->post("subTotal");
			$total=$this->input->post("total");
			$products=$this->input->post("products");
			$productsTitles=$this->input->post('productsTitles');
			$prices=$this->input->post('prices');
			$itemCount=$this->input->post('itemCount');
			$token = $this->shopData->shop_token??'';
			$this->api->setSession(new Session($this->shop, $token));
			$productsIds =explode(",",$products);
			$productsTitle =explode(",",$productsTitles);
			$productsPrices =explode(",",$prices);
			$offers=[];
		    $condition=["shop_name"=>$this->shop,'location'=>"thankuPage","status"=>1];
		    $whereOnAll=array_merge($condition,["triggerOn"=>"all"]);
		    $getOffersAll=$this->adminModel->get_data('funnels',$whereOnAll);
			
		    // Fetch all Orders
		    $ids="";
		    if($getOffersAll){
				
			    foreach($getOffersAll as $keys){
			    	$id=base64_encode($keys->id);
			    	$offer=json_decode($keys->offer);
			    	$products=	$offer->offerProduct;
			    	$searchKey=array_search($id, array_column($offers, 'id'));
			    	if($searchKey>-1){
			    		continue;
			    	}
			    	$ids .=empty($ids)?$products:",".$products;
			    	$offers[]=["id"=>$id,"funnelName"=>$keys->funnelName,"offer"=>$offer,"design"=>json_decode($keys->design),"layout"=>json_decode($keys->layout),"settings"=>json_decode($keys->settings),"language"=>json_decode($keys->language),"products"=>$products,"position"=>$keys->position];
			    }

			}
			
			if(is_array($productsIds)){
		   		$whereOnIds=array_merge($condition,["triggerOn"=>"products","status"=>1]);
		   		foreach($productsIds as $productId){
		   			$keys=$this->adminModel->get_front_row('funnels',$whereOnIds,["recommendedProduct"=>$productId]);
		   			
		   			if($keys){
			   			$id=base64_encode($keys->id);
				    	$offer=json_decode($keys->offer);
				    	$products=	$offer->offerProduct;
				    	//$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
				    	$searchKey=array_search($id, array_column($offers, 'id'));
				    	if($searchKey>-1){
				    		continue;
				    	}
				    	$ids .=empty($ids)?$products:",".$products;
				    	$offers[]=["id"=>$id,"funnelName"=>$keys->funnelName,"offer"=>$offer,"design"=>json_decode($keys->design),"layout"=>json_decode($keys->layout),"settings"=>json_decode($keys->settings),"language"=>json_decode($keys->language),"products"=>$products,"position"=>$keys->position];
			    	}
			    	
		   		}
			}
			
			// order total
		    $whereOnTotal=array_merge($condition,["triggerOn"=>"orderTotal"]);
		    $getTotalOffer=$this->adminModel->get_data('funnels',$whereOnTotal);
		    if($getTotalOffer){
		    	foreach($getTotalOffer as $subTotalOffers){
		    		$checkOffer= $this->conditionForNumber($subTotalOffers,$total);
		    		if(!empty($checkOffer)){
		    			$ids .=empty($ids)?$checkOffer["products"]:",".$checkOffer["products"];
		    			$offers[]=$checkOffer;
		    		}
		    	}
		    }

		    // subtotal triggerOn
		    $whereOnSubTotal=array_merge($condition,["triggerOn"=>"orderSubtotal"]);
		    $getSubTotalOffer=$this->adminModel->get_data('funnels',$whereOnSubTotal);
		    if($getSubTotalOffer){
		    	foreach($getSubTotalOffer as $subTotalOffers){
		    		$checkOffer= $this->conditionForNumber($subTotalOffers,$subTotal);
		    		if(!empty($checkOffer)){
		    			$ids .=empty($ids)?$checkOffer["products"]:",".$checkOffer["products"];
		    			$offers[]=$checkOffer;
		    		}

		    	}
		    }

		    // trigger on the no of line item
		    $whereOnLineItem=array_merge($condition,["triggerOn"=>"noOfLineItem"]);
		    $getLineItemOffer=$this->adminModel->get_data('funnels',$whereOnLineItem);
		    if($getLineItemOffer){
		    	foreach($getLineItemOffer as $subTotalOffers){
		    		$checkOffer= $this->conditionForNumber($subTotalOffers,$itemCount);
		    		if(!empty($checkOffer)){
		    			$ids .=empty($ids)?$checkOffer["products"]:",".$checkOffer["products"];
		    			$offers[]=$checkOffer;
		    		}
		    		

		    	}
		    }

		    // item title
		    if(is_array($productsTitle)){
		   		$whereOnTitle=array_merge($condition,["triggerOn"=>"lineItemTitle"]);
		   		foreach($productsTitle as $title){
		   			$keys=$this->adminModel->get_front_row('funnels',$whereOnTitle,["productTitle"=>$title]);
		   			
		   			if($keys){
			   			$id=base64_encode($keys->id);
				    	$offer=json_decode($keys->offer);
				    	$products=	$offer->offerProduct;
				    	//$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
				    	$searchKey=array_search($id, array_column($offers, 'id'));
				    	if($searchKey>-1){
				    		continue;
				    	}
				    	$ids .=empty($ids)?$products:",".$products;
				    	$offers[]=["id"=>$id,"funnelName"=>$keys->funnelName,"offer"=>$offer,"design"=>json_decode($keys->design),"layout"=>json_decode($keys->layout),"settings"=>json_decode($keys->settings),"language"=>json_decode($keys->language),"products"=>$products,"position"=>$keys->position];
			    	}
			    	
		   		}
			}

			// item Price
		    if(is_array($productsPrices)){
		   		$whereOnLineItemPrice=array_merge($condition,["triggerOn"=>"lineItemPrice"]);
		   		$prces=$productsPrices[0];
		   	    $getOnLineItemPrice=$this->adminModel->get_data('funnels',$whereOnLineItemPrice);
			    if($getOnLineItemPrice){
			    	foreach($getOnLineItemPrice as $subTotalOffers){
			    		$checkOffer= $this->conditionForNumber($subTotalOffers,$prces);
			    		if(!empty($checkOffer)){
			    			$ids .=empty($ids)?$checkOffer["products"]:",".$checkOffer["products"];
			    			$offers[]=$checkOffer;
			    		}
			    		

			    	}
			    }
		   		// foreach($productsPrices as $price){
		   		// 	$keys=$this->adminModel->get_front_row('funnels',$whereOnTitle,["productTitle"=>$title]);
		   			
		   		// 	if($keys){
			   	// 		$id=base64_encode($keys->id);
				   //  	$offer=json_decode($keys->offer);
				    	
				   //  	$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
				   //  	$searchKey=array_search($id, array_column($offers, 'id'));
				   //  	if($searchKey>-1){
				   //  		continue;
				   //  	}
				   //  	$offers[]=["id"=>$id,"funnelName"=>$keys->funnelName,"offer"=>$offer,"design"=>json_decode($keys->design),"settings"=>json_decode($keys->settings),"language"=>json_decode($keys->language),"products"=>$products,"position"=>$keys->position];
			    // 	}
			    	
		   		// }
			}


		   	// print_r($getOffers);
		    // die();
		    // $whereOn=array_merge($condition,["triggerOn"=>"minValue","minValue<="=>$subTotal,"status"=>1]);
		    // $getOffers=$this->adminModel->get_data('funnels',$whereOn);
		    // if($getOffers){
			   //  foreach($getOffers as $keys){
			   //  	$offer=json_decode($keys->offer);
			   //  	$id=base64_encode($keys->id);
			    	
			   //  	$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
			   //  	$offers[]=["id"=>$id,"funnelName"=>$keys->funnelName,"offer"=>$offer,"design"=>json_decode($keys->design),"settings"=>json_decode($keys->settings),"language"=>json_decode($keys->language),"products"=>$products,"position"=>$keys->position];
			    	
			   //  }
		    // }
		    // $whereOnAll=array_merge($condition,["triggerOn"=>"all","status"=>1]);
		    // $getOffers=$this->adminModel->get_data('funnels',$whereOnAll);
		    // if($getOffers){
			   //  foreach($getOffers as $keys){
			   //  	$id=base64_encode($keys->id);
			   //  	$offer=json_decode($keys->offer);
			    	
			   //  	$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
			   //  	$searchKey=array_search($id, array_column($offers, 'id'));
			   //  	if($searchKey>-1){
			   //  		continue;
			   //  	}
			   //  	$offers[]=["id"=>$id,"funnelName"=>$keys->funnelName,"offer"=>$offer,"design"=>json_decode($keys->design),"settings"=>json_decode($keys->settings),"language"=>json_decode($keys->language),"products"=>$products,"position"=>$keys->position];
			    	
			   //  }

			  
		    // }
			$products=[];
		   	if(!empty($ids)){
		   		$products=$this->getProducts($ids);
		   	}
		   	echo json_encode(["offers"=>$offers,"withCurrency"=>$this->shopData->withCurrency,"withoutCurrency"=>$this->shopData->withoutCurrency,"products"=>$products]);
		    die();
		}
	}

	private function conditionForNumber($subTotalOffers,$value)
	{
		$offers=[];
		// echo $value;
		// print_r($subTotalOffers);
		// code...
		if($subTotalOffers->triggerOnType=="is" && $subTotalOffers->minValue==$value){

			$id=base64_encode($subTotalOffers->id);
	    	$offer=json_decode($subTotalOffers->offer);
	    	$products=	$offer->offerProduct;
	    	//$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
	    	
			$offers=["id"=>$id,"funnelName"=>$subTotalOffers->funnelName,"offer"=>$offer,"design"=>json_decode($subTotalOffers->design),"layout"=>json_decode($subTotalOffers->layout),"settings"=>json_decode($subTotalOffers->settings),"language"=>json_decode($subTotalOffers->language),"products"=>$products,"position"=>$subTotalOffers->position];
	    	
	    	

		}else if($subTotalOffers->triggerOnType=="isNot" && $subTotalOffers->minValue!=$value){

			$id=base64_encode($subTotalOffers->id);
	    	$offer=json_decode($subTotalOffers->offer);
	    	$products=	$offer->offerProduct;
	    	//$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
	    		$offers=["id"=>$id,"funnelName"=>$subTotalOffers->funnelName,"offer"=>$offer,"design"=>json_decode($subTotalOffers->design),"layout"=>json_decode($subTotalOffers->layout),"settings"=>json_decode($subTotalOffers->settings),"language"=>json_decode($subTotalOffers->language),"products"=>$products,"position"=>$subTotalOffers->position];
	    	

		}else if($subTotalOffers->triggerOnType=="moreThan" && $subTotalOffers->minValue<$value){
			$id=base64_encode($subTotalOffers->id);
	    	$offer=json_decode($subTotalOffers->offer);
	    	$products=	$offer->offerProduct;
	    	//$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
	    		$offers=["id"=>$id,"funnelName"=>$subTotalOffers->funnelName,"offer"=>$offer,"design"=>json_decode($subTotalOffers->design),"layout"=>json_decode($subTotalOffers->layout),"settings"=>json_decode($subTotalOffers->settings),"language"=>json_decode($subTotalOffers->language),"products"=>$products,"position"=>$subTotalOffers->position];
	    	
		}else if($subTotalOffers->triggerOnType=="isNot" && $subTotalOffers->minValue!=$value){

			$id=base64_encode($subTotalOffers->id);
	    	$offer=json_decode($subTotalOffers->offer);
	    	$products=	$offer->offerProduct;
	    	//$products=$offer->offerProduct?$this->getProducts($offer->offerProduct):[];
	    		$offers=["id"=>$id,"funnelName"=>$subTotalOffers->funnelName,"offer"=>$offer,"design"=>json_decode($subTotalOffers->design),"layout"=>json_decode($subTotalOffers->layout),"settings"=>json_decode($subTotalOffers->settings),"language"=>json_decode($subTotalOffers->language),"products"=>$products,"position"=>$subTotalOffers->position];
	    	

		}
		return $offers;
	}



	private function getProducts($ids)
	{
		// code...
		$token = $this->shopData->shop_token??'';
		$this->api->setSession(new Session($this->shop, $token));	

	   		$result = $this->api->rest("get","/admin/api/products.json",["ids"=>$ids ,"fields"=>"id,title,handle,images,options,variants","status"=>"active"]);

	   		$result=$this->adminModel->getBodyContainer($result,'products');
	   		$productData=[];
			foreach($result as $value){
				$inventory=false;
				$variants=[];
				foreach($value["variants"] as $variant){
					if($variant['inventory_quantity']>0 || $variant['inventory_quantity']<0){
						array_push($variants,$variant);
						$inventory=true;
					}
				}
				if($inventory){
					$value["variants"]=$variants;
					$productData[$value["id"]]=$value;
					//array_push($productData, $value);
				}

			}

			return $productData;
	}

    function checkout()
	{	
		$token = $this->shopData->shop_token??'';
		$this->api->setSession(new Session($this->shop, $token));
		$lineItemArr=$this->input->post("line_items");
		$email=$this->input->post("email");

		if($this->input->post("id")){
			$id=base64_decode($this->input->post("id"));
			$whereOn=["shop_name"=>$this->shop,"id"=>$id];
			$offers=$this->adminModel->get_front_row('funnels',$whereOn);
			if($offers){
				$offer=json_decode($offers->offer);

				$codeStartDate 	=  date('Y-m-d');
				$codeEndDate 	=  date('Y-m-d', strtotime(' +1 day'));

				$bytes = random_bytes(4);
				$uniq_generateC =  bin2hex($bytes);

				$codeTitle = "ENAP-Reconvert-".$uniq_generateC."-".$offer->discountValue;  
				$PriceruleOptions = [
						"price_rule"=>[
							"title"=> $codeTitle,
						    "target_type"=> "line_item",
						    "target_selection"=> "entitled",
						    "allocation_method"=> "across",
						    "value_type"=> $offer->discount=="percent"?"percentage":'fixed_amount',
						    "value"=> "-".($offer->discount=="percent"?(int)$offer->discountValue:$offer->discountValue),
						    "customer_selection"=> "all", 
						    "once_per_customer" =>true,
						    "allocation_limit"=>1,
						    "usage_limit" 	=> 1,  
						    "starts_at"		=> $codeStartDate,
						    "ends_at"		=> $codeEndDate,
						    "entitled_variant_ids"=>[$lineItemArr[0]['variant_id']] 
					    ]  
				];
				
				$priceRule= $this->api->rest("post","/admin/api/price_rules.json",$PriceruleOptions);
				
				
				$priceRule=$this->adminModel->getBodyContainer($priceRule,'price_rule');
				
				$discountCode =  array('discount_code' => array('code' =>$codeTitle) );

			 	$discountApi = $this->api->rest('POST', '/admin/api/price_rules/'.$priceRule['id'].'/discount_codes.json',  $discountCode); 
			 	$getDiscount=$this->adminModel->getBodyContainer($discountApi,'discount_code');
			 	
			 	}

				$finalDraft = [
					"checkout"=>[
						"line_items"=>$lineItemArr,
						"applied_discount"=> [
							"value_type"=> $offer->discount=="percent"?"percentage":'fixed_amount',
							"value"=> $offer->discountValue, 
							"title"=> $codeTitle
					    ],
						"email"=>$email,
						"customer_id"=>$this->input->post("customerId"),
						"shipping_address"=>$this->input->post("shippingAddress"),
						"tags"=>'enap-reconvert', 
			  			"secret"=>true
					]
				]; 
				$getProducts = $this->api->rest('POST', '/admin/api/checkouts.json',  $finalDraft); 
				
				$products = $this->adminModel->getBodyContainer($getProducts,"checkout"); 
				
			    echo json_encode($products);
		}

		
		//echo $getProducts["body"]["checkout"]["web_url"];

	}

	

	
} 


