<?php

namespace App\Controllers;
use App\Libraries\Shopify;
use App\Models\Install;
class Home extends BaseController
{
    
      public function __construct()
    {
        $this->shopify = new Shopify();
        $this->install = new Install();
      
    }
    
    
    public function index(): string
    {
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);
       

        if(isset($_GET["shop"]))
            {
           
                $shop = $_GET['shop']; 
                header ("Content-Security-Policy: frame-ancestors https://$shop https://admin.shopify.com");
                
                //if($_GET['shop']=="ests-test-app.myshopify.com"){
                // echo     $shop ="wrkwer.myshopify.com"; 
                // }   
           
             $installModelData=  $this->install->getByColumns(array("shop"=>$shop));
             
              if(count($installModelData)>0){
                  $installModelData=  $installModelData[0];
                            $data = array();
                            $data['shop'] = $shop;
                            $data['allinstalldata'] = $installModelData;
                            $data['shopify'] = $this->shopify;
                            
                            
                            if(isset($_GET["charge_id"]))
                            {
                                $charge_ID = $_GET["charge_id"];
                                $token= $installModelData["access_token"];
                                $charge = $this->shopify->shopify_call($token, $shop, "/admin/api/2024-07/recurring_application_charges/$charge_ID.json", array(), 'GET');
                                
                                $charge = json_decode($charge['response'], JSON_PRETTY_PRINT);
                                
                                
                                $shopDetail = $this->shopify->shopify_call($token, $shop, "/admin/api/2024-04/shop.json", array(), 'GET');
                                $shopDetail = json_decode($shopDetail['response'], JSON_PRETTY_PRINT);
                                $data['country'] = $shopDetail["shop"]["country"];
                             
                                
                                $status="";
                                $status =  $charge["recurring_application_charge"]["status"];
                                if($status == "active")
                                {
                                     $id =  $charge["recurring_application_charge"]["id"];
                                     $name =  $charge["recurring_application_charge"]["name"];
                                     $dataColumn=array();
                                     $dataColumn['active_plan_name']=$name;
                                     $dataColumn['charge_id']=$id;
                                     $this->install->updateByColumns(array("shop"=>$shop),$dataColumn);
                                    
                                     
                                     
                                    $data['title'] = ucfirst("Home"); // Page title
                                    $data['content'] = view('pages/index', $data); // Dynamic page content
                                    return view('templates/layout', $data);   
                                     
                                     
                                     
                                }
                                else
                                {
                                      // Prepare data
        $data['title'] = ucfirst("Change Plan"); // Page title
        $data['content'] = view('pages/change_plan', $data); // Dynamic page content
        return view('templates/layout', $data); 
                                }
                            }else{
                                
                                
                                 $charge_id= $installModelData["charge_id"];
                                 if($charge_id)
                                 {
                                    
                                      $data['title'] = ucfirst("Home"); // Page title
        $data['content'] = view('pages/index', $data); // Dynamic page content
        return view('templates/layout', $data);   
                                 }
                                 else
                                 {
                                     
                            
                                      
        // Prepare data
        $data['title'] = ucfirst("Change Plan"); // Page title
        $data['content'] = view('pages/change_plan', $data); // Dynamic page content

        // Load the base template and pass the content to it
        return view('templates/layout', $data); 
                                     
                                     
                                     
                                 }
                                
              }
                  
      }else{
                            $api_key = getenv('ClIENT_ID');
                            $scopes = getenv('SCOPE');
                            $redirect_uri = getenv('WEBSITE_URL')."install/";
                                if ($shop == "")
                                    {
                                    
                                              $data['title'] = ucfirst("Install"); // Page title
        $data['content'] = view('pages/install', $data); // Dynamic page content

        // Load the base template and pass the content to it
       return view('templates/layout', $data);   
                                        
                                        
                                        
                                }
                                else
                                    { 
                                    $install_url = "https://" . $shop . "/admin/oauth/authorize?client_id=" . $api_key . "&scope=" . $scopes . "&redirect_uri=" . urlencode($redirect_uri);
                                    header("Location: " . $install_url);
                                    die();
                                }
          
      }
      
                
                
                
               
       
    }else{
          $data['title'] = ucfirst("Install"); // Page title
        $data['content'] = view('pages/install', $data); // Dynamic page content

        // Load the base template and pass the content to it
       return  view('templates/layout', $data);   
    }
    
    }
    
    public function install(): string
    {
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);

        $api_key = getenv('ClIENT_ID');
        $shared_secret = getenv('ClIENT_SECRET');
        $params = $_GET;
        $hmac = $_GET['hmac'];
        $params = array_diff_key($params, array('hmac' => ''));
        ksort($params);
        $computed_hmac = hash_hmac('sha256', http_build_query($params) , $shared_secret);
        $shop=$params['shop'];
           if (hash_equals($hmac, $computed_hmac))
        {
            $query = array(
                "client_id" => $api_key,
                "client_secret" => $shared_secret,
                "code" => $params['code']
            );

            $access_token_url = "https://" .$shop . "/admin/oauth/access_token";
            $access_token = $this->shopify->genrateToken($access_token_url, $query);
                //update token code start
     
             $installModelData=  $this->install->getByColumns(array("shop"=>$shop));
             
              if(count($installModelData)>0){
                  
                  
                                     $columnArray=array();
                                     $columnArray['access_token']=$access_token['access_token'];
                                     $this->install->updateByColumns(array("shop"=>$shop),$columnArray);
              }
        

             else{

            $columnArray = array();
            $columnArray['access_token'] = $access_token['access_token'];
            $columnArray['shop'] = $params['shop'];
            $columnArray['install_date'] = date("Y/m/d h:i:sa");
            $this->install->insertData($columnArray);
             }
             
                $shopDetailAPI = $this->shopify->shopify_call($access_token['access_token'], $shop, "/admin/api/2024-04/shop.json", array(), 'GET');
                $shopDetailAPI = json_decode($shopDetailAPI['response'], JSON_PRETTY_PRINT);
                
                $customerEmail = $shopDetailAPI["shop"]["customer_email"];
                $shop_owner = $shopDetailAPI["shop"]["shop_owner"];
                $mailData = array();
                $mailData['appName'] = getenv('AppName');
                $mailData['store'] = $shop;
                $mailData['customerEmail'] = $customerEmail;
                $mailData['shop_owner'] = $shop_owner;
               
                
                     
                $subject = getenv('AppName'). " :App Install";
                $LoadFileMail4Customer = view("email_template/admin_install_app", $mailData);
                $LoadFileMail4ESTS = view("email_template/customer_install_app", $mailData);
                
                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    
                // Send email to customer
                $customerMail = mail($customerEmail, $subject, $LoadFileMail4Customer, $headers);
        
                // Send email to Admin
                $AdminMail = mail(getenv('AppOwnerEmail'), $subject, $LoadFileMail4ESTS, $headers);
                if ($customerMail) 
                { log_message("error","Mail Sent to Customer");
                } else {
                log_message("error","Unable to sent Mail to Customer");
                }
                 if ($AdminMail) 
                { log_message("error","Mail Sent to Admin");
                } else {
                log_message("error","Unable to sent Mail to Admin");
                }
           
                
          
            //1st webhook code start
        $array = array(
                'webhook' => array(
                'topic' => 'app/uninstalled', 
                'address' =>  getenv('WEBSITE_URL').'shop/redact?shop='.$params['shop'],
                'format' => 'json'
                )
                );  
        $webhook =  $this->shopify->shopify_call($access_token['access_token'], $shop,"/admin/api/2022-10/webhooks.json", $array, 'POST');
        $webhook = json_decode($webhook['response'], JSON_PRETTY_PRINT);

        $array = array(
                'webhook' => array(
                'topic' => 'shop/redact', 
                'address' =>  getenv('WEBSITE_URL').'shop/redact?shop='.$params['shop'],
                'format' => 'json'
                )
                );  
        $webhook =  $this->shopify->shopify_call($access_token['access_token'], $shop,"/admin/api/2022-10/webhooks.json", $array, 'POST');

        $webhook = json_decode($webhook['response'], JSON_PRETTY_PRINT);

            if(!isset($_GET['charge_id']))
                  {
                       
        // if you want to cretate multiple plan in  separate page for plan, you need to uncomment code below
     
        //  header("Location: " . "https://" .$params['shop'] . "/admin/apps/".getenv('AppNameSlug'));
        //     die();
        
       
                              
                       
            $array = array(
	                            'recurring_application_charge' => array(
		                        'name' => 'Basic',
	                            'test' =>   getenv('TEST_MODE'),  
		                        'price' =>  getenv('APP_PRICE'),
		                        "trial_days" =>3,
                                'return_url' => "https://" .$shop . "/admin/apps/".getenv('AppNameSlug')
	                        )
                            );
                            
                        $charge = $this
                            ->shopify
                            ->shopify_call($access_token['access_token'], $shop, "/admin/api/2023-10/recurring_application_charges.json", $array, 'POST');
                     
                        $charge = json_decode($charge['response'], JSON_PRETTY_PRINT);
                        $status = $charge["recurring_application_charge"]["status"];
                        if($status == "active"){
                               
                            header("Location: " . "https://" .$params['shop'] . "/admin/apps/".getenv('AppNameSlug')); 
                            die();  
                        }
                        else{
                        header("Location: " . $charge['recurring_application_charge']['confirmation_url']);
                            die();  
                            }
                                             
                    
        
        
        
        
        }

    }
        
        
        
    }
    
    
    
    
}
