<?php defined('BASEPATH') OR exit('No direct script access allowed'); 
/*if(isset($_GET['shop']) && $_GET['shop']=="james-enorm.myshopify.com"){
	// error_reporting(-1);
	// 	ini_set('display_errors', 1);
}*/

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

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

class auth extends CI_Controller { 
	public  $api;
	public $shop,$token;
	public function __construct()
	{
		parent::__construct();// you have missed this line.
		$TOKEN='';
		// $API_KEY = $this->config->item('shopify_api_key');
		// $SECRET =$this->config->item('shopify_secret'); 
		
		$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); 
		 $STORE_URL = $this->input->get('shop');
		$this->shop = $STORE_URL;
		$getRow =$this->adminModel->get_row("app_record",array("shop_address"=>$this->shop));
		if($getRow){
			$this->shopData=$getRow;		
			$this->token = $getRow->shop_token??'';
		}
		($this->shop && $this->token)?$this->api->setSession(new Session($this->shop, $this->token)):'';
		
	}  

	public function index()
	{
		$shop=$this->input->get('shop');
		if($shop){ 
			$check= $this->adminModel->get_row('app_record',array('shop_address'=>$shop));
			if ($check) {
				
				redirect(base_url("/admin?".getQueryStringParameters())); 
				
			}else{
				redirect(base_url("/login"));
			
			}
				
		}else{ 
			redirect(base_url("/login"));
			exit();
		}

	}
	public function checkto(){  
		$shop = $this->input->get('shop');
		header('Set-Cookie: shop='.$shop.';path=/;HttpOnly; SameSite=None; Secure;'); 
		
		$check= $this->adminModel->get_row('app_record',array('shop_address'=>$shop));
			
		 redirect(base_url("/admin?".getQueryStringParameters())); 
				
	}

	public function access(){  
		$host = $this->input->get('host');
		$shop = $this->input->get('shop');
		header('Set-Cookie: host='.$host.';path=/;HttpOnly; SameSite=None; Secure;'); 
		$this->auth($shop);
	} 

	public function auth($shop){ 
		$shop = $this->input->get('shop');
	    $scopes = SHOPIFY_SCOPE; //what app can do

	    $this->api->setSession(new Session($this->shop));
	   	$check= $this->adminModel->get_row('app_record',array('shop_address'=>$shop));  
	   	if($check){
	   		redirect(base_url("/admin?".getQueryStringParameters())); 
	   	}else{
		    $redirect_url = base_url().REDIRECT_URL; //redirect url specified in app setting at shopify 
			$redirect = $this->api->getAuthUrl($scopes, $redirect_url);
			//header("Location: {$redirect}"); 
			$this->load->view("auth/escapeIframe",["installUrl"=>$redirect]);
		}
	}

    public function callback(){
        $code = $this->input->get('code');
        $shop = $this->input->get('shop');
	    // header('Set-Cookie: shop='.$shop.';path=/;HttpOnly; SameSite=None; Secure;'); 
        $check= $this->adminModel->get_row('app_record',array('shop_address'=>$shop));
		if(!$check){
			$this->api->setSession(new Session($this->shop));
			$access = $this->api->requestAccess($code);
			$token=$access->container['access_token'];
		  	$this->api->setSession(new Session($this->shop,$token));
		  	header('Set-Cookie: shop='.$shop.';path=/;HttpOnly;SameSite=None; Secure;');
			
		
			$query=$this->graphQuery->shop();
            $request=$this->api->graph($query);
            $shopInfo= $this->graphQuery->getBodyContainer($request,'shop');
		
		
			$inset_app_record=array("shop_token"=>$token,'shop_address'=>$shop,'shop_email'=>$shopInfo['email'],'shop_date'=>$shopInfo['createdAt'],'shop_owner'=>$shopInfo['name'],'installation_date'=>date("Y-m-d"),"pricing_plan"=>"free","plan"=>0,"app_status"=>1,"withCurrency"=>strip_tags($shopInfo['currencyFormats']['moneyWithCurrencyFormat']),"withoutCurrency"=>strip_tags($shopInfo['currencyFormats']['moneyFormat']));
			$this->adminModel->insert_and_update_data('app_record',$inset_app_record);
			
			
			//$this->setMail($shopInfo['email']);
		}else{
			// $inset_app_record=array("shop_token"=>token);
			// $this->adminModel->insert_and_update_data('app_record',$inset_app_record,array("shop_address"=>$this->shop));
			// redirect(base_url("/admin?".getQueryStringParameters())); 
			//echo $url= base_url("/admin?".getQueryStringParameters());
			//$this->load->view("auth/escapeIframe",["installUrl"=>$url]);
		}
		$this->webhook();
       
    }

    public function setMail($email){
		$subject = "Welcome to multiple Product - Photo Reviews by Enormapps!";
		$message = "<center style='text-align: left; margin: 0 auto; width: 800px; max-width: 98%;'><div style='font-size:14px; font-family:arial,sans-serif; line-height:28px;color:#444;'>Hello,<br/><br/>

		We are glad that you have installed Product - Photo Reviews by Enormapp!<br>
		We would be more than happy if we can help you in setting up the app. Please let us know if you need any kind of assistance from our side. 

		<br><br>

		If you want , we can configure the app for you. Our service doesn't include any charge for setting up the app.<br/><br/>

		<div style='font-size:14px;'>
		Please have a look at our other popular apps: <br/>
		<ul style='padding:0;'>
		<li style='list-style: none; color: #999;'><a style='color:#ff6f05;' href='https://apps.shopify.com/image-gallery-by-enormapps' target='_blank'>Image + Video Gallery by Enormapps</a> -  Create Multiple lookbooks, image galleries, video galleries</li>

		<li style='list-style: none; color: #999;'><a style='color:#ff6f05;' href='https://apps.shopify.com/multiple-image-sliders' target='_blank'>Multiple Image + Carousel + Logo Sliders by Enormapps</a> -  Showcase your images in an elegant slider, create lookbook</li>

		<li style='list-style: none; color: #999;'><a style='color:#ff6f05;' href='https://apps.shopify.com/faq-frequently-asked-questions' target='_blank'>FAQ & Accordions </a> - Help your site visitors understand your products and services</li>

		<li style='list-style: none; color: #999;'><a style='color:#ff6f05;' href='https://apps.shopify.com/text-rotator' target='_blank'>Multiple Announcement + Notification Rotator </a> -  Displays multiple key messages to keep your customer engaged</li>


		</ul>
		</div></div>
		<br/><br/>
		<div style='font-size:13.5px;font-family:arial,sans-serif; line-height:28px;color:#888;'>

		Best regards,<br/>
		Enormapps Support</div></center>";
		$details= array("to"=>$email,
				'reply_name'=>'Enorm Review - Photo Review',
				'reply'=>'info@enormapps.com',
	 			"subject"=>$subject,
	 			"body"=>  $message
	 		);
	 	

	 	// $this->Mail($details);	
	 	// $this->mailTo($details);
	 	$this->webhook();
	 	
	}

    function webhook(){
    	
    
    	$query =$this->graphQuery->getWebhook();
    	
        $request= $this->api->graph($query);

        $webhooks=$this->graphQuery->getBodyContainer($request,"webhookSubscriptions");
        if(count($webhooks['edges'])==0){
             $query =$this->graphQuery->webhookCreate();
                $input=[
                      'topic'=>'APP_UNINSTALLED',
                      'webhookSubscription'=>[
                        'callbackUrl'=>base_url("auth/uninstall?shop=").$this->shop,
                        "format"=> "JSON",
                      ]
                  ];
                $request= $this->api->graph($query,$input);

        }
        redirect(base_url("admin?".getQueryStringParameters()));

    	/*$getwebhook=$this->api->rest("get","/admin/webhooks.json");
		$webhooks= $this->adminModel->getBodyContainer($getwebhook,"webhooks"); //$getwebhook->body->webhooks;
	
		$check= array_filter($webhooks,function($webhook){
			return ($webhook['topic']=='app/uninstalled');
		});
		
		if(empty($check)){
		    $create= ["webhook"=>["topic"=>'app/uninstalled',"address"=>base_url("auth/uninstall?shop=").$this->shop,'format '=>'json']];
			$this->api->rest("post","/admin/webhooks.json",$create);
			$array=array("script_tag"=>array("event"=>"onload","src"=>base_url("frontend/js/reconvert.min.js")));
		    	$this->api->rest("POST","/admin/script_tags.json",$array);
	    
		   	redirect(base_url("admin?".getQueryStringParameters()));
		}else{
		    redirect(base_url("admin?".getQueryStringParameters()));
		}*/
		
	}

	

   	
	public function uninstall(){
		$shop= $this->input->get('shop')??$this->input->post('shop');
		$grow= $this->adminModel->get_row("app_record",array("shop_address"=>$shop));
		//$this->adminModel->insert_and_update_data("uninstall",array("shop_name"=>$shop,"shop_email"=>$grow->shop_email,"uninstall_date"=>date("Y-m-d")));
		$this->adminModel->deleterows('app_record',array("shop_address"=>$shop));
		
		$this->adminModel->deleterows('funnels',array("shop_name"=>$shop));
		$this->adminModel->deleterows('orders',array("shop_name"=>$shop));
		
		
		http_response_code(200);
		
	}	
	public function getCookies(){
		print_r($this->session->userdata());
		echo $this->input->cookie('shop',true);
	}

	 public function apiCharges(){

	 	

    	$chargeId= $this->input->get('charge_id');
		$createCharge=$this->api->rest("get","admin/recurring_application_charges/$chargeId.json");
		$applicationRecurringCharge= $this->adminModel->getBodyContainer($createCharge,"recurring_application_charge");
		if($applicationRecurringCharge['status']=="active"){
		

			$planArr = array(
				'pricing_plan'   => $this->input->get('planName'), 
				'plan'   => $this->input->get('plan'),
				"charge_status"=>$applicationRecurringCharge['status']
			);
			$planCheck= false;
			if($this->shopData->plan==1){
				$planCheck= true;
			}elseif($this->shopData->plan==0 && $this->input->get('plan')>2){
				$planCheck= true;
			}

			if($planCheck){
				$setting= json_decode($this->shopData->settings,true);
	 	
			 	
			 		$setting['customer_picture_show']="true";
			 		$setting['customer_picture']=" Customer Picture";
			 		$setting['customer_picture_placeholder']="Upload Picture";
			 		$setting['customer_picture_msg']="";
			 		$setting['imageLenght']=4;
			 	$planArr["settings"]=json_encode($setting);
			}
			
			
			$this->adminModel->insert_and_update_data("app_record",$planArr,array("shop_address"=>$this->shop));
			
		
			$getwebhook=$this->api->rest("get","admin/webhooks.json");
			$webhooks=$this->adminModel->getBodyContainer($getwebhook,"webhooks"); //$getwebhook['body']->container['webhooks'];
		
			$check= array_filter($webhooks,function($webhook){
				return ($webhook['topic']=='orders/fulfilled');
			});
			if(empty($check)){
				$createOrder= ["webhook"=>["topic"=>'orders/fulfilled',"address"=>base_url("webhook/ordersfulfilled?shop=").$this->shop,'format '=>'json']];
				$this->api->rest("post","admin/webhooks.json",$createOrder);
			}
			
			// if($activeCharge->body->recurring_application_charge=="active")
			if($this->shopData->plan<3){
				redirect(base_url("order?".getQueryStringParameters()));	
			}else{
				redirect(base_url("admin?".getQueryStringParameters()));	
			}
			
			// redirect(base_url("auth/webhook"));
		 }elseif ($applicationRecurringCharge['status']=="active"){
		 		redirect(base_url("admin?".getQueryStringParameters()));
		 }else{
			 redirect(base_url("admin/upgrade-plan?".getQueryStringParameters()));
		 }

	}

	function logout(){
		delete_cookie('shop');
		delete_cookie('accessToken');
		redirect(base_url("login"));
	}
		
	function login(){
		if($this->input->post("signIn")){
			$store=$this->input->post("store");
			redirect(base_url("auth/access/?".getQueryStringParameters()));
		}
		$this->load->view("pages/login");
	}

	function mailTo($details){
		$to      = 'viratjshah@gmail.com';
		$subject = 'New installed';
		$message = 'shop: '.$this->shop ."\r\n"."email:".$details["to"];
		$headers = 'From: no-reply@enormapps.com' . "\r\n" .
		    'Reply-To: no-reply@enormapps.com' . "\r\n" .
		    'X-Mailer: PHP/' . phpversion();

		mail($to, $subject, $message, $headers);
	}

	function Mail($details){
		// Instantiation and passing `true` enables exceptions
		$mail = new PHPMailer(true);
		try {
		    //Server settings
		                                               // Send using SMTP
		    $mail->SMTPDebug = SMTP::DEBUG_OFF;                      // Enable verbose debug output
		    $mail->isSMTP();                                            // Send using SMTP
		    $mail->Host       = 'email-smtp.us-east-1.amazonaws.com';                    // Set the SMTP server to send through
		    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
		    $mail->Username   = 'AKIARHDSV4EVWOSYCS7F';                     // SMTP username
		    $mail->Password   = 'BN4Sdwq+8XbjhKB+pVbEbkvE3zjGKccQvc8T+PRMvBBk';                                // SMTP password
		    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
		    $mail->Port       = 465;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
		    $mail->CharSet = 'UTF-8';  
		    //Recipients
		    $mail->setFrom('no-reply@enormapps.com', $details['reply_name']);
		   	$mail->addAddress($details["to"]);
		   	if(isset($details['reply']))  {             // Name is optional
		    	$mail->addReplyTo($details['reply'], $details['reply_name']);
		    }
		    // // Content
		    $mail->isHTML(true);                                  // Set email format to HTML
		    $mail->Subject = $details['subject'];
		    $mail->Body    = $details['body'];
		    $mail->send();
		    return true;

		} catch (Exception $e) {
			
		    //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
		    return false;
		}
	}	

}