<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class One_link 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 http://codeigniter.com/user_guide/general/urls.html
	 */
	 public function __construct(){
		parent::__construct();
		$this->load->model(array('admin/admin_model','admin/admin_onelink_model'));
		
		if(true){
    	    $this->db->select("*");
    		$this->db->from('site_config');
            $this->db->where('product_code','MBX-OL-001-SDRQAP');
           
            $query = $this->db->get();
            // echo $this->db->last_query();exit;
            
            if($query->num_rows()){
                
                $rowRec = $query->row();
                $verified = $rowRec->verified;
                if(empty($verified)){
                    $prodactivationkey = $rowRec->product_activation_key;
                    if(!empty($prodactivationkey)){
                        
                        // print_r($rowRec);
                        // exit;
                        $curl = curl_init();

                        curl_setopt_array($curl, array(
                          CURLOPT_URL => 'https://saveigm.com/services/api/api/verify_purchase_code',
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_ENCODING => '',
                          CURLOPT_MAXREDIRS => 10,
                          CURLOPT_TIMEOUT => 0,
                          CURLOPT_FOLLOWLOCATION => true,
                          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                          CURLOPT_CUSTOMREQUEST => 'POST',
                          CURLOPT_POSTFIELDS => 'prodkey='.$prodactivationkey,
                          CURLOPT_HTTPHEADER => array(
                            'Content-Type: application/x-www-form-urlencoded'
                          ),
                        ));
                        
                        $response = curl_exec($curl);
                
                        curl_close($curl);
                        // echo $response;exit;
                        $res = json_decode($response);
                        if(isset($res->status) && $res->status == true){
                            
                            $accData['verified'] = 1;
                            $accData['updated_at'] = date('Y-m-d H:i:s');
                            $this->db->where('id',$rowRec->id);
			                $this->db->update('site_config', $accData);
			                
                            $arr = ['status'=>true,'msg'=>"Product Activation success!"];
                        }else{
                            $arr = ['status'=>false,'msg'=>"Product Activation Failed! Activation Key Invalid"];
                        }
                    }else{
                        $arr = ['status'=>false,'msg'=>"Product Activation Failed! Activation Key Invalid"];
                    }
                }else{
                    $arr = ['status'=>true,'msg'=>"already verified"];
                }
            }else{
                $arr = ['status'=>false,'msg'=>"Product Activation Failed! Activation Key Missing"];
            }
		}
		
		
// 		print_r($arr);exit;
		if($arr['status'] == false){
		    $this->session->set_flashdata('errMsg',$arr['msg']);
		    redirect('admin', 'refresh');
		}
		
    }
    
    
	function index()
	{
 		$data = array();  
		$data['categoryFor'] = 'one_link';
		$data['categoryForPage'] = 'One Link';
		
		if($this->input->post('doAction',true) && $this->input->post('ids',true)){
			$doAction = $this->input->post('doAction',true);
            $this->admin_model->checkAdminPrivilage($doAction=='delete'?'DELETE':'UPDATE','admin/one_link');
            $successMsg = $this->admin_onelink_model->do_OneLink_Action($this->input->post('doAction',true),$this->input->post('ids',true));
            $this->session->set_flashdata('successMsg',$successMsg);
            $redirectUrl = 'admin/one_link';
            if($this->input->post('listUrl',true) && $this->input->post('doAction',true) != 'delete')
                $redirectUrl =$this->input->post('listUrl',true);
            redirect($redirectUrl);exit;
		}

  		$this->load->view('admin/onelink_list',$data);
	}
	
    
	function manager($action='add',$id=false )
	{
		$this->admin_model->checkAdminPrivilage($action=='add'?'INSERT':'UPDATE','admin/one_link');
		if($action == 'view')$this->admin_model->checkAdminPrivilage('VIEW','admin/one_link');
 		$data = array('action'=>$action,'id'=>$id);
		if($id){
			$blogRow = $this->admin_onelink_model->get_OneLink_Row($id); 
			if($blogRow === false){
				$this->session->set_flashdata('errMsg','Invalid URI');
				redirect('admin/one_link');exit;
			}
			$data['blogRow'] = $blogRow;
			
			$data['country_redi_list'] = [];
			if(!empty($id)){
			    $countryRow = $this->admin_onelink_model->get_Country_Redi_list($id); 
    			if(!empty($countryRow)){
    				$data['country_redi_list'] = $countryRow;
    			}
			}
			
			$data['rotate_redi_list'] = [];
			if(!empty($id)){
			    $rotateRow = $this->admin_onelink_model->get_Rotate_Redi_list($id); 
    			if(!empty($rotateRow)){
    				$data['rotate_redi_list'] = $rotateRow;
    			}
			}
			
			$data['pageSeoRow'] = [];
			if(!empty($id)){
			    $pageSeoRow = $this->admin_onelink_model->get_Page_Seo_Row($id); 
    			if(!empty($pageSeoRow)){
    				$data['pageSeoRow'] = $pageSeoRow;
    			}
			}
			$data['sub_link_list'] = [];
			if(!empty($id)){
			    $sub_link_listRow = $this->admin_onelink_model->get_Sublink_list($id); 
    			if(!empty($sub_link_listRow)){
    				$data['sub_link_list'] = $sub_link_listRow;
    			}
			}
			
			$data['utm_tags_row'] = [];
			if(!empty($id)){
			    $utm_tags_rowRow = $this->admin_onelink_model->get_UTM_tags_Row($id);
    			if(!empty($utm_tags_rowRow)){
    				$data['utm_tags_row'] = $utm_tags_rowRow;
    			}
			}
			
			if( $data['action'] == 'duplicate' ){
			    $data['id'] = false;
			}
 		}
 		
 		
   		if($this->input->post('menuBtn',TRUE)) {
            
            $this->form_validation->set_rules('destination_default_link', 'destination_default_link', 'trim|xss_clean|required');
            $this->form_validation->set_rules('link_name', 'link_name', 'trim|xss_clean|required');
            
            $this->form_validation->set_rules('target_type', 'target_type', 'trim|xss_clean|required');
            
            $this->form_validation->set_rules('share_link', 'share_link', 'trim|xss_clean');
            
			$this->form_validation->set_rules('android_play_store_url', 'android_play_store_url', 'trim|xss_clean');
			$this->form_validation->set_rules('ios_app_store_url', 'ios_app_store_url', 'trim|xss_clean');
			$this->form_validation->set_rules('website_url', 'website_url', 'trim|xss_clean');

			if ($this->form_validation->run() == TRUE) {
				$app_keyword = $this->input->post('share_link', TRUE);
			
  				$planRow = $this->admin_onelink_model->isExist_OneLink($app_keyword, $id);
  				if($planRow){
					$this->form_validation->set_rules('share_link', 'share_link', 'callback__custom_required[app_keywordAlreadyExists]');	
				}
				
				$link_name = $this->input->post('link_name', TRUE);
				$planRow = $this->admin_onelink_model->isExist_OneLink(false, $id, $link_name);	
  				if($planRow){
					$this->form_validation->set_rules('link_name', 'link_name', 'callback__custom_required[link_namedAlreadyExists]');	
				}
                
				$target_type = $this->input->post('target_type', TRUE);
				if($target_type == 'SEO'){
				    $page_name = $this->input->post('page_name', TRUE );
				    $p_id = $this->input->post('p_id', TRUE );
    				$planRow = $this->admin_onelink_model->isExist_pageSEO($page_name, $p_id);
      				if($planRow){
    					$this->form_validation->set_rules('page_name', 'page_name', 'callback__custom_required[page_namedAlreadyExists]');	
    				}
				}
				
			}
			
		    if ($this->form_validation->run() == TRUE) {
				$result  = $this->admin_onelink_model->addEdit_OneLink($id);
				if($result){
					if($id){
						$this->session->set_flashdata('successMsg','One Link updated successfully!');
					}else{
						$this->session->set_flashdata('successMsg','One Link created successfully!');
					}
					redirect('admin/one_link');exit;
				}
			}
	    }
	    
		$data['categoryFor'] = 'one_link';
		$data['categoryForPage'] = 'One Link';
		$data['base_url_set'] = SHARE_LINK_BASE_URL ?? base_url();
		
		$this->load->view('admin/onelink_manager',$data);
	}
    
 	function category()
	{
 		$data = array();  
		$data['categoryFor'] = 'one_link';
		$data['categoryForPage'] = 'One Link'; 
		if($this->input->post('doAction',true) && $this->input->post('categoryIds',true)){
			$doAction = $this->input->post('doAction',true);
			 $this->admin_model->checkAdminPrivilage($doAction=='delete'?'DELETE':'UPDATE','admin/one_link/category');
 			 $successMsg = $this->admin_onelink_model->doCategoryAction($this->input->post('doAction',true),$this->input->post('categoryIds',true));
				$this->session->set_flashdata('successMsg',$successMsg);
				$redirectUrl = 'admin/one_link/category';
				if($this->input->post('listUrl',true) && $this->input->post('doAction',true) != 'delete')$redirectUrl =$this->input->post('listUrl',true);
				redirect($redirectUrl);exit;
		}
  		$this->load->view('admin/category_list',$data);
	}
	
	function category_manager($action='add',$categoryId=false ) 
	{
 		$this->admin_model->checkAdminPrivilage($action=='add'?'INSERT':'UPDATE','admin/one_link/category');
		if($action == 'view')$this->admin_model->checkAdminPrivilage('VIEW','admin/one_link/category');
 		$data = array('action'=>$action,'categoryId'=>$categoryId); 
		$data['categoryFor'] = 'one_link'; 
		$data['categoryForPage'] = 'One Link';
		$resourceFor = 0;if($categoryId){
			$categoryRow = $this->admin_onelink_model->getCategoryRow($categoryId); 
			if($categoryRow === false){
				$this->session->set_flashdata('errMsg','Invalid URI');
				redirect('admin/one_link/category');exit;
			}
			$data['categoryRow'] = $categoryRow;
 		}
   		if($this->input->post('iconBtn',TRUE)) {
			$this->form_validation->set_rules('categoryTitle', 'title', 'trim|xss_clean|required');
   			$catRow = false;
			if ($this->form_validation->run() == TRUE) {
				$categoryRefId = $this->input->post('categoryOrder', TRUE);
				 
  				$catRow = $this->admin_onelink_model->isExistCategory($categoryRefId,$categoryId,false);	
  				if($catRow){
					$this->form_validation->set_rules('categoryOrder', 'categoryOrder', 'callback__custom_required[catrefidAlreadyExists]');	
				}
			}
  			 if ($this->form_validation->run() == TRUE) {
   					$result  = $this->admin_onelink_model->addEditCategories($categoryId); //var_dump($result); exit;
 					if($result === true){
						if($categoryId){
							$this->session->set_flashdata('successMsg','Category updated successfully!');
						}else{
							$this->session->set_flashdata('successMsg','Category created successfully!');
						}
						redirect('admin/one_link/category');exit;
					}
  			} 
 		 }
 		$this->load->view('admin/category_manager',$data);
	}
	
    function get_c_list_data(){
        
        $resARR= [];
        
        if($this->input->post('link_id',true) && $this->input->post('get_c_list_data') == 'caknsd$^%&^8yidnaiAd8^SbndunkJHSYD' ){
            
            $link_id = $this->input->post('link_id',true);
            
            $this->db->select('id, link_id, country_code, c_d_link');
    		
    		$this->db->from('country_redirects');
     		$this->db->where('is_deleted',0);
    		$this->db->where('link_id',$link_id);
    		
      		$query = $this->db->get();
      		// echo $this->db->last_query();exit;
     		if($query->num_rows()){
     		    $resARR =  $query->result();
     		}
        }
        
        echo json_encode($resARR);
        
		exit;
		
    }
    
    function get_c_list_dropd(){
        
        $dropdownstr = '';
        
        if($this->input->post('country_code',true) && $this->input->post('get_c_dd') == 'caknsd$^%&dvdk72Ad8^SbndunkJHSYD' ){
            
            $country_code = $this->input->post('country_code',true);
            $country_Data = $this->admin_onelink_model->get_Country_List();
            
            if(!empty($country_Data)){
                foreach($country_Data as $ck=>$cv){
                    if($ck == $country_code) $selected='selected';
                    else $selected='';
                    $dropdownstr .= (string) '<option value="'.$ck.'" '.$selected.'>'.$cv.'</option>';
                }
            }
        }
        echo ($dropdownstr);
		exit;
    }
    
    
	function statistics($action='add', $link_id=false )
	{
	    $sub_link_id='';
	    if($this->input->get('link_id',true) ){
 		    $link_id = $this->input->get('link_id',true);
 		    
 	        if($this->input->get('sub_link_id',true) ){
 		        $sub_link_id = $this->input->get('sub_link_id',true);
 	        }
 		}
        else{
            $link_id = '';
        }
        
	    $this->load->model('admin/Admin_stat_model');
	    
		$this->admin_model->checkAdminPrivilage($action=='add'?'INSERT':'UPDATE','admin/one_link');
		if($action == 'view')$this->admin_model->checkAdminPrivilage('VIEW','admin/one_link');
 		$data = array('action'=>$action,'link_id'=>$link_id,'sub_link_id'=>$sub_link_id);
		
		if($link_id){
			$blogRow = $this->admin_onelink_model->get_OneLink_Row($link_id); 
			if($blogRow === false){
				$this->session->set_flashdata('errMsg','Invalid URI');
				redirect('admin/one_link');exit;
			}
			$data['blogRow'] = $blogRow;
			
			$data['sublinkRow'] = [];
			$sublinkRow = $this->admin_onelink_model->get_OneLink_Row($sub_link_id); 
			if(!empty($sublinkRow)){
			    $data['sublinkRow'] = $sublinkRow;
			}
			
 		}
 		
	    
   		if($this->input->get('reportrange',true)){
   		    
            // $start = $this->input->get('start',true);
            // $end = $this->input->get('end',true);
            
        }else{
            
            // $prevmonth = date('M Y', strtotime("last month"));
            // $start = date('F d,Y', strtotime("last month"));
            $start = date('F d,Y', strtotime("last year"));
            $end = date('F d,Y');
            if($data['blogRow'] && $data['blogRow']->created_at) {
                //start value set from link created_at time
                $start = date('F d,Y', strtotime($data['blogRow']->created_at));
            }
            
            $query_str ='?';
            $query_str .= !empty($link_id)? 'link_id='.$link_id :'';
            $query_str .= !empty($start)? '&reportrange='.$start.'+-+'.$end :'';
            
            if($this->input->get('sub_link_id',true)){
                $query_str .= '&sub_link_id='.$this->input->get('sub_link_id',true);
            }
            
            
            // echo "asd";
            // exit;
            redirect('admin/one_link/statistics'.$query_str);
        }
	    
	    
		$data['categoryFor'] = 'one_link';
		$data['categoryForPage'] = 'One Link'; 
		
// 		print_r($data);exit;
		
		$this->load->view('admin/onelink_statistics',$data);
	}
    
    
    function isExist_onelink(){
        
        $resARR['res']= false;
        $resARR['msg']= 'not_exists';
        
        if($this->input->post('url',true) && $this->input->post('test_url_k') == 'msdkyiNCys5@eShdbs^iAd8^SbndunkJmc3s2' ){
            
            $url = $this->input->post('url',true);
            if(!empty($url) ){
                
                $Row = $this->admin_onelink_model->isExist_OneLink($url);	
      			if($Row){
					$resARR['res']= true;
                    $resARR['msg']= 'exists';
    			}
            }
        }
        
        echo json_encode($resARR);
		exit;
		
    }
    
	function ping_url()  
    {
        
        $resARR['res']= false;
        $resARR['code']= 503;
        
        if($this->input->post('url',true) && $this->input->post('test_url_k') == 'm&knsd$^%&^8yiNCys5@&Shdbs^iAd8^SbndunkJmc&s2' ){
            
            $url = $this->input->post('url',true);
            if(!empty($url) ){
                
                $ch = curl_init($url);  
                curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $data = curl_exec($ch);
                $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                if($httpcode>=200 && $httpcode<300){
                    $resARR['res']= true;$resARR['code']= $httpcode;
                }
                else if($httpcode>=300 && $httpcode<400){
                    $resARR['res']= true;$resARR['code']= $httpcode;
                }
                else {
                    $resARR['res']= false;$resARR['code']= $httpcode;
                }
            }
        }
        
        echo json_encode($resARR);
		exit;
        
    }
    
    
    function ckeditor_upload(){
            
        
        if(isset($_FILES['upload']['name']))
        {
           
            $file = $_FILES['upload']['tmp_name'];
            $file_name = $_FILES['upload']['name'];
            $file_name_array = explode(".", $file_name);
            $extension = end($file_name_array);
            $new_image_name = rand() . '.' . $extension;
            // chmod('upload', 0777);
            $allowed_extension = array("jpg", "gif", "png","jpeg", "mp4", "mp3" , "webp" , "jif");
            
            $function_number = $_GET['CKEditorFuncNum'];
            $upload_path = "./uploads/ckeditor_tmp_files/";
            
            $base_path = base_url() ."uploads/ckeditor_tmp_files/";
            
            if(in_array($extension, $allowed_extension))
            {
                move_uploaded_file($file, $upload_path . $new_image_name);
                
                $url = $base_path . $new_image_name;
                $message = '';
                echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction('$function_number','$url', '$message');</script>";
            }
            else
            {
                $url = 'uploads/ckeditor_tmp_files/' . $new_image_name;
                $message = 'Invalid File format';
                echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction('$function_number','$url', '$message');</script>";
            }
        }
        
    }
    
    
 	function _custom_required($str, $func) {
         switch($func) {
            case 'app_keywordAlreadyExists':
                $this->form_validation->set_message('_custom_required', 'Keyword already exists!');
                return FALSE;
                break;
            case 'link_namedAlreadyExists':
                $this->form_validation->set_message('_custom_required', 'Link Name already exists!');
                return FALSE;
                break;
            case 'page_namedAlreadyExists':
                $this->form_validation->set_message('_custom_required', 'Page Name already exists!');
                return FALSE;
                break;
                
 			default: return TRUE;	
         }
    }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */