<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');  


ini_set('display_errors', 1);
// New Shopify Api
use Osiset\BasicShopifyAPI\BasicShopifyAPI;
use Osiset\BasicShopifyAPI\Options;
use Osiset\BasicShopifyAPI\Session;


class FunnelController 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->get('shop')??$this->input->cookie('shop'); 
                $this->shopData =$this->adminModel->get_row("app_record",array("shop_address"=>$this->shop));
                if(!$this->shop || !$this->shopData){
                        echo "404 not found";
                        die();
                }
        }

        function saveFunnel(){
               $msg="Error! Please try again.";
                if($this->input->post("funnelName") && !empty($this->input->post("funnelName"))){
                        $details = $this->input->post();


                        $language=[
                                "title"=>mb_convert_encoding($details['lanTitle'], 'HTML-ENTITIES', "UTF-8"),
                                "save"=>$details['lanSave'],
                                "buyNowButton"=>$details['lanBuyNow'],
                                "freeShipping"=>$details["lanFreeShipping"],
                                'timer'=>$details['lanTimer'],
                                'freeProduct'=>$details['lanFreeProduct'],
                                'decline'=>$details['lanDecline']
                                
                        ];

                        $design=[
                                'hdTextColor'=>$details['desHdTextColor'],
                                'prTextColor'=>$details['desPrTextColor'],
                                'bnBgColor'=>$details['desBnBgColor'],
                                'bnTextColor'=>$details['desBnTextColor'],
                                "proBgColor"=>$details['desProBgColor'],
                                "proBorderColor"=>$details['desProBorderColor'],
                                "priceColor"=>$details['desPriceColor'],
                                "discountPriceColor"=>$details['desDiscountPriceColor'],
                        ];
                        $settings=[
                                "linkOfferTitle"=>$details['linkOfferTitle'],
                                "hideOutOfStock"=>$details['hideOutOfStock']
                        ];
                        $offerProduct='';
                        if(isset($details['selectedOfferProducts'])){
                                foreach ($details['selectedOfferProducts'] as $key) {
                                        $offerProduct .= ($offerProduct)?','.$key['id']:$key['id'];
                                }
                        }        

                        
                        // Offer Products details
                        $offer=[
                                "minValue"=>$details["minValue"],
                                "minQty"=>$details['minQty'],
                                'discountValue'=>$details['discountValue'],
                                'discount'=>$details['discount'],
                                "offerProduct"=>$offerProduct,
                        ];
                        $recommendedProduct='';
                        if(isset($details['selectedTriggerProducts']) && $details['selectedTriggerProducts']!=''){
                                foreach ($details['selectedTriggerProducts'] as $key) {
                                        $recommendedProduct .= ($recommendedProduct)?','.$key['id']:$key['id'];
                                }
                        } 

                        $insertFunnel=[
                                "shop_name"=>$this->shop,
                                "funnelName"=>$details['funnelName'],
                                "location"=>$details['location'],
                                "position"=>"left",
                                "triggerOn"=>$details['triggerOn'],
                                "offer"=>json_encode($offer),
                                "design"=>json_encode($design),
                                "settings"=>json_encode($settings),
                                "language"=>json_encode($language),
                               
                                "status"=>($details["funnelStatus"]=="true")?1:0
                        ];
                        if($recommendedProduct){
                            $insertFunnel["recommendedProduct"]=$recommendedProduct;  
                        }
                        if(isset($details['position'])){
                                $insertFunnel["position"]=$details['position'];
                        }

                        if(isset($details['minValue'])){
                              $insertFunnel['minValue'] =$details['minValue']; 
                        }

                       
                        if($details["funnelId"]){
                                $this->adminModel->insert_and_update_data('funnels',$insertFunnel,['id'=>$details["funnelId"]]);
                                echo json_encode(array("error"=>false,"msg"=>"Success! Funnel Successfuly Updated."));
                        }else{
                               
                                $this->adminModel->insert_and_update_data('funnels',$insertFunnel);
                                
                                echo json_encode(array("error"=>false,"msg"=>"Success! Funnel Successfuly Created."));
                        }        
                        die();
                }else{
                        $msg="Please Insert Funnel Name";
                }


                echo json_encode(array("error"=>true,"msg"=>$msg));
        }

        // New funnel setting 
        function saveFunnelSettings(){
                $msg="Error! Please try again.";
                if($this->input->post("funnelName")){
                        $details = $this->input->post();

                        $layout=[
                               "type"=>$details['layoutType']
                        ];

                        $language=[
                                "title"=>mb_convert_encoding($details['lanTitle'], 'HTML-ENTITIES', "UTF-8"),
                                "save"=>$details['lanSave'],
                                "buyNowButton"=>$details['lanBuyNow'],
                                "freeShipping"=>$details["lanFreeShipping"],
                                'timer'=>$details['lanTimer'],
                                'freeProduct'=>$details['lanFreeProduct'],
                                'decline'=>$details['lanDecline']
                        ];

                        $design=[
                                'hdTextColor'=>$details['desHdTextColor'],
                                'prTextColor'=>$details['desPrTextColor'],
                                'bnBgColor'=>$details['desBnBgColor'],
                                'bnTextColor'=>$details['desBnTextColor'],
                                "proBgColor"=>$details['desProBgColor'],
                                "proBorderColor"=>$details['desProBorderColor'],
                                "priceColor"=>$details['desPriceColor'],
                                "discountPriceColor"=>$details['desDiscountPriceColor'],
                        ];
                        $settings=[
                                "linkOfferTitle"=>$details['linkOfferTitle'],
                                "hideOutOfStock"=>$details['hideOutOfStock']
                        ];
                        $offerProduct='';
                        if(isset($details['selectedOfferProducts'])){
                                foreach ($details['selectedOfferProducts'] as $key) {
                                        $offerProduct .= ($offerProduct)?','.$key['id']:$key['id'];
                                }
                        }        

                        
                        // Offer Products details
                        $offer=[
                                "minValue"=>$details["minValue"],
                                "minQty"=>$details['minQty'],
                                'discountValue'=>$details['discountValue'],
                                'discount'=>$details['discount'],
                                "offerProduct"=>$offerProduct,
                        ];
                        $recommendedProduct='';
                        if(isset($details['selectedTriggerProducts']) && $details['selectedTriggerProducts']!=''){
                                foreach ($details['selectedTriggerProducts'] as $key) {
                                        $recommendedProduct .= ($recommendedProduct)?','.$key['id']:$key['id'];
                                }
                        } 

                      
                        $insertFunnel=[
                                "shop_name"=>$this->shop,
                                "funnelName"=>$details['funnelName'],
                                "location"=>$details['location'],
                                "position"=>"left",
                                "triggerOn"=>$details['triggerOn'],
                                "customCss"=>$details['customCss'],
                                "offer"=>json_encode($offer),
                                "design"=>json_encode($design),
                                "settings"=>json_encode($settings),
                                "language"=>json_encode($language),
                                "recommendedProduct"=>$recommendedProduct,
                                "layout"=>json_encode($layout),
                                "status"=>($details["funnelStatus"]=="true")?1:0
                        ];
                     
                        if(isset($details['position'])){
                                $insertFunnel["position"]=$details['position'];
                        }

                        if(!empty($details['triggerOnType'])){
                                $insertFunnel["triggerOnType"]=$details['triggerOnType'];
                        }
                        if(!empty($details['lineItemTitle'])){
                                $insertFunnel["productTitle"]=$details['lineItemTitle'];
                        }

                        if(isset($details['minValue'])){
                              $insertFunnel['minValue'] =$details['minValue']; 
                        }
                         
                     
                        if($details["funnelId"]){
                                $this->adminModel->insert_and_update_data('funnels',$insertFunnel,['id'=>$details["funnelId"]]);
                                echo json_encode(array("error"=>false,"msg"=>"Success! Funnel Successfuly Updated."));
                        }else{
                                $this->adminModel->insert_and_update_data('funnels',$insertFunnel);
                                echo json_encode(array("error"=>false,"msg"=>"Success! Funnel Successfuly Created."));
                        }        
                        die();
                }else{
                        $msg="Please Insert Funnel Name";
                }


                echo json_encode(array("error"=>true,"msg"=>$msg));
        }

        function funnelList()
        {
                // code...
                $filter=["shop_name"=>$this->shop];
               
                $getFunnels= $this->adminModel->get_data("funnels",$filter);
              
                $funnels= $getFunnels?$this->getList($getFunnels):[];
                $funnelData=["draw"=>$this->input->post("draw"), "recordsTotal"=>count($funnels),
                "recordsFiltered"=> count($funnels),"data"=>$funnels];
                echo json_encode($funnelData);
        }

        public function funnelDetails($id)
        {
                // code...
                $token = $this->shopData->shop_token??'';
                $this->api->setSession(new Session($this->shop, $token));
                $filter=["shop_name"=>$this->shop,"id"=>$id];
                $getFunnels= $this->adminModel->get_row("funnels",$filter);

                if($getFunnels->recommendedProduct){
                        $getFilter=["fields"=>"id,title,images,variants,handle","ids"=>$getFunnels->recommendedProduct];
                
                        $getProducts = $this->api->rest('GET', '/admin/api/products.json',$getFilter);
                        $products=$this->adminModel->getBodyContainer($getProducts,"products");
                        $getFunnels->recommendedProduct=$products;
                }
                
                $getFunnels->design=json_decode($getFunnels->design);
                $getFunnels->language=json_decode($getFunnels->language);
                $getFunnels->language->title= html_entity_decode($getFunnels->language->title);
                $getFunnels->layout=json_decode($getFunnels->layout);

                $getFunnels->offer=json_decode($getFunnels->offer);
                if($getFunnels->offer){
                        $getOfferFilter=["fields"=>"id,title,images,variants,handle","ids"=>$getFunnels->offer->offerProduct];
                
                        $getOfferProducts = $this->api->rest('GET', '/admin/api/products.json',$getOfferFilter);
                        $products=$this->adminModel->getBodyContainer($getOfferProducts,"products");
                        $getFunnels->offer->offerProduct=$products;
                }
                $getFunnels->settings=json_decode($getFunnels->settings);

                unset($getFunnels->total_revenue);
                unset($getFunnels->shop_name);
                unset($getFunnels->id);
                echo json_encode($getFunnels);
        }

        function funnelDelete($id){
                $delete=["shop_name"=>$this->shop,"id"=>$id];
                $status=$this->adminModel->deleterows("funnels",$delete);
                if($status){
                        echo json_encode(array("error"=>false,"msg"=>"Funnel Successfuly Delete."));
                }else{
                        echo json_encode(array("error"=>true,"msg"=>"Error! Please try again."));
                }
                
        }

        function products(){
                $search=$this->input->post("search");
                $paging=$this->input->post("paging");
                $show=10;
                $token = $this->shopData->shop_token??'';
                $this->api->setSession(new Session($this->shop, $token));
                $getFilter=["limit"=>10,"fields"=>"id,title,images,variants,handle"];
                if($paging){
                     $getFilter["page_info"]=$paging;   
                }
                if($search){
                     $getFilter["title"]=$search;   
                    
                }

               
                $getProducts = $this->api->rest('GET', '/admin/api/products.json',$getFilter);
                $products=$this->adminModel->getBodyContainer($getProducts,"products"); 
                $link=["next"=>'',"previous"=>''];

                if(!empty($getProducts["link"])){
                        $link=$getProducts["link"]->container;
                }
                echo json_encode(["products"=>$products,"link"=>$link]);
        }

        private function getList($data){
                $funnelData=[];
                $i=1;
                foreach ($data as $key) {
                        // code...
                        $status=$key->status?'<div class="badge bg-success">Active</div>':'<div class="badge bg-primary">Deactive</div>';
                        $button='<div class="d-grid gap-2 d-md-block">
                                  <a href="'.base_url("admin/funnel/setting/".$key->id."?".getQueryStringParameters()).'" class="btn btn-icon btn-outline-primary waves-effect waves-float waves-light" type="button"><i class="fa-solid fa-pen-to-square"></i></a>
                                  <button class="btn btn-icon btn-outline-danger waves-effect waves-float waves-light deleteFunnel" type="button" data-href="'.base_url("admin/api/funnel/delete/".$key->id."/?".getQueryStringParameters()).'"><i class="fa-solid fa-trash-can"></i></button>
                                </div>';
                        $funnelData[]=["no"=>$i,"title"=>$key->funnelName,"impression"=>"","status"=>$status,"revenue"=>$key->total_revenue,"action"=>$button];
                        $i++;
                }
                return $funnelData;
        }


        private function sendMessage(){
                if($this->input->post()){

                }
                        
                echo json_encode(array("error"=>true,"msg"=>"Error! Please try again."));
                
        }

        
}    