<?php

class Admin_onelink_model extends CI_Model {
 	
 	var $limit = 20;
	var $page = 0;
	
	function __construct() {
		parent::__construct();
		
 		 if($this->input->cookie('perPage', TRUE)){
			 $this->limit = $this->input->cookie('perPage', TRUE);
 		 }
 		 if($this->input->post('perPage',true)){
			 setPageCookieMsg($this->input->post('perPage',true),'admin/one_link');
			 redirect($this->input->post('listUrl',true)); 
		 }
		 if($this->input->get('per_page',true))$this->page = (int)$this->input->get('per_page'); 
  	}
 
	
	//sharelink starts
	function addEdit_OneLink($id){
        
        $SHARE_LINK_BASE_URL = SHARE_LINK_BASE_URL;
        
        if($this->input->post('share_link', TRUE) ){
            $app_keyword = $this->input->post('share_link', TRUE);
        }else{
            $share_app_code = $this->uniqidReal(8);
            $app_keyword =  $share_app_code;
        }
        // $postfix_str='axe';
        $postfix_str='';

        $share_key_word = $app_keyword.$postfix_str;
        $share_link = $SHARE_LINK_BASE_URL.$share_key_word;
        
        
        if($this->input->post('target_type', TRUE)){
            $target_type = $this->input->post('target_type', TRUE);
        }else{
            $target_type='';
        }
        
        if($this->input->post('sub_link_flag', TRUE)){
            if(!empty($target_type) && $target_type =='Device' ){
                $sub_link_flag = $this->input->post('sub_link_flag', TRUE);
            }else{
                $sub_link_flag=0;
            }
        }else{
            $sub_link_flag=0;
        }
        if($this->input->post('utm_flag', TRUE)){
            $utm_flag = $this->input->post('utm_flag', TRUE);
        }else{
            $utm_flag=0;
        }
        
        $accData = array(
            'link_name' => $this->input->post('link_name', TRUE),
            'destination_default_link' => $this->input->post('destination_default_link', TRUE),
            'category_id' => $this->input->post('category_id', TRUE),
            'target_type' => $target_type,
            
			'android_play_store_url' => $this->input->post('android_play_store_url', TRUE),
			'ios_app_store_url' => $this->input->post('ios_app_store_url', TRUE),
            'website_url' => $this->input->post('website_url', TRUE),
            'sub_link_flag' => $sub_link_flag,
            'utm_flag'=>$utm_flag
   		);
        
     	if($id){
     	    
     	    $accData['updated_at'] = date('Y-m-d H:i:s');
    		$this->db->where('id',$id);
    		$this->db->update('app_share_link', $accData);
    		
     	}else{
            
     	    $accData['share_link'] = $share_link;
     	    $accData['app_keyword'] = $share_key_word;
     	    
    		$accData['created_at'] = date('Y-m-d H:i:s');
     		$this->db->insert('app_share_link', $accData);
    		$id =  $this->db->insert_id();
        
		}
        
        
        if($id){
            
            if(!empty($utm_flag) ){
                $this->addEdit_UTM_tags($id);
            }
            
            if(!empty($sub_link_flag) ){
                $this->addEdit_Sublinks($id);
            }
            
            if(!empty($target_type) && $target_type =='Country' ){
                //country list arr data insert,updations..
                $this->addEdit_country_redirects($id);
                
            }
            if(!empty($target_type) && $target_type =='Rotate' ){
                //rotate list arr data insert,updations..
                $this->addEdit_rotate_redirects($id);
            }
            if(!empty($target_type) && $target_type =='SEO' ){
                //rotate list arr data insert,updations..
                $this->addEdit_pageSEO($id);
            }
            
        }
        
 		return $id?true:false;
 		
 	}
 	
 	function addEdit_country_redirects($link_id){
	   
	   $country_code_Arr = array();$c_d_link_Arr = array();
	   
	   $id_Arr =  $this->input->post('id', TRUE);
	   
	   $country_code_Arr =  $this->input->post('country_code', TRUE);
	   $c_d_link_Arr =  $this->input->post('c_d_link', TRUE);
    
	   $accData = array();
	   $res_Update_Data = array();
	  
	   if(!empty($country_code_Arr)){
            $remp_incr = 0;$j=0;
            $id='';
            
            for($i = 0; $i < count($country_code_Arr); $i++){
                
                    $tempData = array();
                    $temp_Update_Data = array();
                    if(!empty($country_code_Arr[$i])){
                        $country_code = $country_code_Arr[$i];
                    }
                    else $country_code='';
                    
                    if(!empty($c_d_link_Arr[$i])){
                        $c_d_link = $c_d_link_Arr[$i];
                    }
                    else $c_d_link='';
                    
                    
                    if(!empty($id_Arr[$i])){
                        $id = $id_Arr[$i];
                    }
                    else $id='';
                    
                    if(!empty($id))
                    {
                        $temp_Update_Data = array(
                            'id' => $id,
            				'link_id'    => $link_id,
                            'country_code'  => $country_code,
            				'c_d_link'=> $c_d_link,
            				'updated_at'  => date('Y-m-d H:i:s'),
           			    );
           			    
                        array_push($res_Update_Data,$temp_Update_Data);
                    }
                    else
                    {
                         $tempData = array(
            				'link_id'    => $link_id,
                            'country_code'  => $country_code,
            				'c_d_link'      => $c_d_link,
            				'created_at'  => date('Y-m-d H:i:s'),
           			    );
                        array_push($accData,$tempData);
                        
                    }
               
                }
        }
	   
	   //echo '<br><br> add arra';
	    $res_Update_Data = array_filter($res_Update_Data);
        $accData = array_filter($accData);
        // print_r($accData);
        // exit;
        // echo PHP_EOL;
        // echo '<br><br> UPdate arra';
        // print_r($res_Update_Data);
        // echo '<br><br> end arra';
        
        if(!empty($id_Arr))
        {
            $this->db->select("id");
    		$this->db->from('country_redirects');
            $this->db->where('link_id',$link_id);
            $this->db->where_not_in('id',$id_Arr);
          
            $query = $this->db->get();
            // echo $this->db->last_query();exit;
            
            if($query->num_rows()){
                $res = $query->result();
 				foreach ($res as $ids){
                    $yourIDs[] = $ids->id; 
                }
                
                $neUPdata['is_deleted'] = '1';
                $neUPdata['updated_at'] = date('Y-m-d H:i:s');
                $this->db->where_in('id',$yourIDs);
                $this->db->update('country_redirects', $neUPdata);
			}
// 			else
// 			{
// 			    echo "no";
// 			}
        }
        
 
        if(!empty($accData))
        {
            $this->db->insert_batch('country_redirects', $accData);
		 //   $link_id =  $this->db->insert_id();
        }
        
        if(!empty($res_Update_Data))
        {
            $this->db->update_batch('country_redirects', $res_Update_Data,'id');
        }
 		
 		return true;
 	}
 	
 	function addEdit_rotate_redirects($link_id){
	    
	   //$country_code_Arr = array();
	   $r_link_Arr = array();
	   
	   $r_id_Arr =  $this->input->post('r_id', TRUE);
	   
	   //$country_code_Arr =  $this->input->post('country_code', TRUE);
	   $r_link_Arr =  $this->input->post('r_link', TRUE);
    
	   $accData = array();
	   $res_Update_Data = array();
	  
	   if(!empty($r_link_Arr)){
            $remp_incr = 0;$j=0;
            $r_id='';
            
            for($i = 0; $i < count($r_link_Arr); $i++){
                
                $tempData = array();
                $temp_Update_Data = array();
                
                if(!empty($r_link_Arr[$i])){
                    $r_link = $r_link_Arr[$i];
                }
                else $r_link='';
                
                if(!empty($r_id_Arr[$i])){
                    $r_id = $r_id_Arr[$i];
                }
                else $r_id='';
                
                if(!empty($r_id))
                {
                    $temp_Update_Data = array(
                        'r_id' => $r_id,
        				'link_id'    => $link_id,
        				'r_link'=> $r_link,
        				'updated_at'  => date('Y-m-d H:i:s'),
       			    );
       			    
                    array_push($res_Update_Data,$temp_Update_Data);
                }
                else
                {
                     $tempData = array(
        				'link_id'    => $link_id,
        				'r_link'      => $r_link,
        				'created_at'  => date('Y-m-d H:i:s'),
       			    );
                    array_push($accData,$tempData);
                }
            }
            
        }
	   
	   //echo '<br><br> add arra';
	    $res_Update_Data = array_filter($res_Update_Data);
        $accData = array_filter($accData);
        
        if(!empty($r_id_Arr))
        {
            $this->db->select("r_id");
    		$this->db->from('rotational_redirects');
            $this->db->where('link_id',$link_id);
            $this->db->where_not_in('r_id',$r_id_Arr);
          
            $query = $this->db->get();
            // echo $this->db->last_query();exit;
            
            if($query->num_rows()){
                $res = $query->result();
 				foreach ($res as $r_ids){
                    $yourIDs[] = $r_ids->r_id; 
                }
                
                $neUPdata['is_deleted'] = '1';
                $neUPdata['updated_at'] = date('Y-m-d H:i:s');
                $this->db->where_in('r_id',$yourIDs);
                $this->db->update('rotational_redirects', $neUPdata);
			}
// 			else
// 			{
// 			    echo "no";
// 			}
        }
        
 
        if(!empty($accData))
        {
            $this->db->insert_batch('rotational_redirects', $accData);
		 //   $link_id =  $this->db->insert_id();
        }
        
        if(!empty($res_Update_Data))
        {
            $this->db->update_batch('rotational_redirects', $res_Update_Data,'r_id');
        }
 		
 		return true;
 	}
 	
 	function addEdit_pageSEO($link_id){
 	    
 	    $id = trim($this->input->post('p_id', TRUE));
 	    $id = isset($id)&&!empty($id)?$id:false;
 	    
        $accData = array(
            'link_id'   => $link_id,
            'page_name'     => $this->input->post('page_name', TRUE),
            'page_title' => $this->input->post('page_title', TRUE),
            'page_slug'     => url_title( strtolower( trim($this->input->post('page_name', TRUE))) ),
			'meta_description' => $this->input->post('meta_description', TRUE),
			'promo_link' => $this->input->post('promo_link', TRUE),
            'page_content' =>  $this->input->post('page_content', FALSE),
   		);
        
     	if($id){
        
     	    $accData['updated_at'] = date('Y-m-d H:i:s');
    		$this->db->where('id',$id);
    		$this->db->update('links_page_seo', $accData);
    		
     	}else{
            
    		$accData['created_at'] = date('Y-m-d H:i:s');
     		$this->db->insert('links_page_seo', $accData);
    		$id =  $this->db->insert_id();

		}
        
 		return $id?true:false;
 	}
    
    function addEdit_Sublinks($link_id){
        
        $share_link_2_Arr = array();$sublink_name_Arr = array();
	   
	   $id_Arr =  $this->input->post('sl_id', TRUE);
	   
	   //var_dump($id_Arr);
	   //exit;
	   
	   $share_link_2_Arr =  $this->input->post('share_link_2', TRUE);
	   $sublink_name_Arr =  $this->input->post('sublink_name', TRUE);
    
	   $accData = array();
	   $res_Update_Data = array();
	    
        if($this->input->post('utm_flag', TRUE)){
            $utm_flag = $this->input->post('utm_flag', TRUE);
        }else{
            $utm_flag=0;
        }
        
	   if(!empty($share_link_2_Arr)){
            $remp_incr = 0;$j=0;
            $id='';
            
            for($i = 0; $i < count($share_link_2_Arr); $i++){
                
                    $tempData = array();
                    $temp_Update_Data = array();
                    $app_keyword = '';
                    if(!empty($share_link_2_Arr[$i])){
                        $share_link_2 = $share_link_2_Arr[$i];
                        $app_keyword_t = explode('https://axe.link/' , $share_link_2);
                        $app_keyword = $app_keyword_t[1];
                    }
                    else $share_link_2='';
                    
                    if(!empty($sublink_name_Arr[$i])){
                        $sublink_name = $sublink_name_Arr[$i];
                    }
                    else $sublink_name='';
                    
                    
                    if(!empty($id_Arr[$i])){
                        $id = $id_Arr[$i];
                    }
                    else $id='';
                    
                    if(!empty($id))
                    {
                        $temp_Update_Data = array(
                            'id' => $id,
                            'app_keyword' =>$app_keyword,
                            // 'link_name' => $this->input->post('link_name', TRUE).$sublink_name,
                            'destination_default_link' => $this->input->post('destination_default_link', TRUE),
                            'android_play_store_url' => $this->input->post('android_play_store_url', TRUE),
			                'ios_app_store_url' => $this->input->post('ios_app_store_url', TRUE),
                            'website_url' => $this->input->post('website_url', TRUE),
                            'target_type' => $this->input->post('target_type', TRUE),
            				'main_link_id'=> $link_id,
                            'share_link' => $share_link_2,
            				'sublink_name' => $sublink_name,
            				'utm_flag' => $utm_flag,
            				'updated_at' => date('Y-m-d H:i:s'),
           			    );
           			    
                        array_push($res_Update_Data,$temp_Update_Data);
                    }
                    else
                    {
                    
                        $tempData = array(
                            // 'link_name' => $this->input->post('link_name', TRUE).$sublink_name,
                            'destination_default_link' => $this->input->post('destination_default_link', TRUE),
                            'android_play_store_url' => $this->input->post('android_play_store_url', TRUE),
			                'ios_app_store_url' => $this->input->post('ios_app_store_url', TRUE),
                            'website_url' => $this->input->post('website_url', TRUE),
                            'target_type' => $this->input->post('target_type', TRUE),
            				'main_link_id'=> $link_id,
            				'app_keyword' => $app_keyword,
                            'share_link'  => $share_link_2,
            				'sublink_name'=> $sublink_name,
            				'utm_flag'  =>$utm_flag,
            				'created_at'  => date('Y-m-d H:i:s'),
           			    );
                        array_push($accData,$tempData);
                        
                    }
               
                }
        }
	   
	   //echo '<br><br> add arra';
	    $res_Update_Data = array_filter($res_Update_Data);
        $accData = array_filter($accData);
        // print_r($accData);
        // exit;
        // echo PHP_EOL;
        // echo '<br><br> UPdate arra';
        // print_r($res_Update_Data);
        // echo '<br><br> end arra';
        
        if(!empty($id_Arr))
        {
            $this->db->select("id");
    		$this->db->from('app_share_link');
            $this->db->where('main_link_id',$link_id);
            $this->db->where_not_in('id',$id_Arr);
          
            $query = $this->db->get();
            // echo $this->db->last_query();exit;

            if($query->num_rows()){
                $res = $query->result();
 				foreach ($res as $ids){
                    $yourIDs[] = $ids->id; 
                }
                
                $neUPdata['is_deleted'] = '1';
                $neUPdata['updated_at'] = date('Y-m-d H:i:s');
                $this->db->where_in('id',$yourIDs);
                $this->db->update('app_share_link', $neUPdata);
			}
			else
			{
			 //   echo "no";
			}
        }
        
 
        if(!empty($accData))
        {
            $this->db->insert_batch('app_share_link', $accData);
		 //   $link_id =  $this->db->insert_id();
        }
        
        if(!empty($res_Update_Data))
        {
            $this->db->update_batch('app_share_link', $res_Update_Data,'id');
        }
 		
 		return true;
    }
    
    function addEdit_UTM_tags($link_id){
        
        $utm_source = $this->input->post('utm_source', TRUE);
        $utm_medium = $this->input->post('utm_medium', TRUE);
        $utm_campaign = $this->input->post('utm_campaign', TRUE);
        $utm_term = $this->input->post('utm_term', TRUE);
        $utm_content = $this->input->post('utm_content', TRUE);
        
        $utm_id = $this->input->post('utm_id', TRUE);
        
        $accData = array(
            'link_id' => $link_id,
            'utm_source' => $utm_source,
            'utm_medium' => $utm_medium,
			'utm_campaign' => $utm_campaign,
			'utm_term' => $utm_term,
            'utm_content' => $utm_content,
   		);
   		
        if($utm_id){
            $accData['updated_at'] = date('Y-m-d H:i:s');
    		$this->db->where('utm_id',$utm_id);
    		$this->db->update('onelink_utm_tags', $accData);
        }else{
    		$accData['created_at'] = date('Y-m-d H:i:s');
     		$this->db->insert('onelink_utm_tags', $accData);
    		$utm_id =  $this->db->insert_id();
        }
        
        return $utm_id;
    }
    
    
    function isExist_pageSEO($page_name=false,$id=false){
        
		$this->db->select('id');
		$this->db->from('links_page_seo');
 		$this->db->where('is_deleted',0);

		if(!empty($page_name)){
			$this->db->where('page_name',$page_name);
		}
	    
		if(!empty($id)){
			$this->db->where('id !=',$id); 
		}
  		$query = $this->db->get();
  		// echo $this->db->last_query();exit;
  		if($query->num_rows()){return true;}
		else return false;

	}
	
 	function get_Country_List($resType = 'select'){
	    
		$this->db->select('iso,nicename');
		$this->db->from('country');
		$query = $this->db->get();
 		if($resType == 'select')
		{
		   if($query->num_rows()){
				// return $query->result();
				foreach($query->result() as $subblogRow){
            		$ARR_COUNTRY[$subblogRow->iso] = $subblogRow->nicename;
        	    }
        	    return $ARR_COUNTRY;
			}
			else return false;
		}
		else{
			
			return $query->num_rows();
		} 
	}
 	
 	//category start
    function doCategoryAction($action,$ids){
        		 
    		if($action == 'delete'){ 
     			$status = 'deleted';$logMsg = 'DeleteCategory';
    			$data = array( 'categoryDeleted' => '1' , 'categoryUpdated' => date('Y-m-d H:i:s') );
    			$successMsg= 'Category details deleted successfully!';
    			$this->db->where_in('categoryId', $ids); $this->db->update('categories', $data);
      		}else if($action == 'disable'){
     			$status = 'disabled';$logMsg = 'DisableCategory';
    			$data = array( 'categoryDisabled' =>1 , 'categoryUpdated' => date('Y-m-d H:i:s') );$successMsg= 'Category details disabled successfully!';
    			 $this->db->where_in('categoryId', $ids); $this->db->update('categories', $data);
      		}else if($action == 'enable'){
     			$status = 'enabled';$logMsg = 'EnableCategory';
    			$data = array( 'categoryDisabled' => 0 , 'categoryUpdated' => date('Y-m-d H:i:s'));$successMsg= 'Category details enabled successfully!';
    			 $this->db->where_in('categoryId', $ids); $this->db->update('categories', $data);
      		}
      	
     		return $successMsg;
    		
    	}
        	
    function getCategoryRow($category_id,$resType=null){
    
	    $this->db->select('*');
		$this->db->from('categories');
 		$this->db->where('categoryDeleted',0); 
		$this->db->where('categoryId',$category_id);
  		$query = $this->db->get();
  	
 		if($query->num_rows()){
    		 return $query->row();
 		}
		else return false;
     }
     
    function getCategoryList($resType = 'list'){ 
    
        if($resType == 'map'){
            $this->db->select('categories.categoryId,categories.categoryTitle')->from('categories');
        }
        else{
            $this->db->select('categories.*')->from('categories');
        }
        $this->db->where('categories.categoryDeleted',0);
        
 		if($this->input->get('searchKey',true) && $this->input->get('searchBy',true) && $this->input->get('searchBy')!='categoryId_m' ){
			$this->db->like($this->input->get('searchBy',true), trim($this->input->get('searchKey',true)));
		}
		
		//updated start admin users
		if($this->input->get('searchByadminuser',true) && $this->input->get('searchByadminuser',true) == 'all'){
 			// $this->db->where('questionUser',$this->input->get('searchByadminuser',true));
		}else if($this->input->get('searchByadminuser',true) && $this->input->get('searchByadminuser',true) != ''){
 			$this->db->where('categories.categoryUser',$this->input->get('searchByadminuser',true));
		}
		
		if($this->input->get('searchKey',true) && $this->input->get('searchBy',true) && $this->input->get('searchBy')=='categoryId_m' ){
 		    $quiz_id_m = $this->input->get('searchKey');
 		    $array = array_map('intval', explode(',', $quiz_id_m));
            $array = implode("','",$array);
            $this->db->where("categoryId IN ('".$array."')" );
		}
		
		if($this->input->get('searchStatus',true) && $this->input->get('searchStatus',true) == 'Enabled'){
 			$this->db->where('categories.categoryDisabled',0); 
		}else if($this->input->get('searchStatus',true) && $this->input->get('searchStatus',true) == 'Disabled'){
 			$this->db->where('categories.categoryDisabled',1); 
		}

		if($this->input->get('sortBy',true) && $this->input->get('sortOrder',true)){
 			$this->db->order_by($this->input->get('sortBy',true),$this->input->get('sortOrder',true)); 
		}else{
		  //  $this->db->order_by("categoryUpdated desc,categoryAdded desc");
		    $this->db->order_by('IF(categoryUpdated>categoryAdded, `categoryUpdated` , `categoryAdded`)', 'DESC' ,FALSE);
		}
			
		//updated start admin users
		if($this->input->get('searchByadminuser',true) && $this->input->get('searchByadminuser',true) == 'all'){
 			
		}else if($this->input->get('searchByadminuser',true) && $this->input->get('searchByadminuser',true) != ''){
 			$this->db->where('categoryUser',$this->input->get('searchByadminuser',true));
		}
		
		if($this->input->get('searchBycategoryLang',true) && $this->input->get('searchBycategoryLang',true) != ''){
 			$this->db->where('categoryLang',$this->input->get('searchBycategoryLang',true));
		}
		
		if($this->input->get('daterange_By',true) && $this->input->get('daterange_By',true)){
    	    $rangedate = $this->input->get('daterange_By');
    	    $date_Arr = explode(' - ',$rangedate);
    	    if(!empty($date_Arr)){
    	        $startDate = (date("Y-m-d", strtotime($date_Arr[0])).' 00:00:00');
                $endDate = (date("Y-m-d", strtotime($date_Arr[1])).' 23:59:00');
                $this->db->where("categories.categoryAdded BETWEEN '". $startDate . "' and '".  $endDate."'");
    	    }
		}
		
 		if($resType == 'list'){
			$arrSubCategories = array();
			if($this->page)$this->page = ($this->page-1);
			$this->db->limit($this->limit, ($this->page * $this->limit) ); 
			$query = $this->db->get();
			if($query->num_rows()){
				return $query->result();
			}
			else return false;	
		}
		else if($resType == 'map')
		{
	    	$this->db->limit(5000);
			$query = $this->db->get(); 
			if($query->num_rows()){
				return $query->result();
			}
			else return false;	
		}
		else{
			$query = $this->db->get();
			return $query->num_rows();
		} 
	}
     
    function isExistCategory($categoryRefId,$categoryId=false,$parantCategory = false){
		$this->db->select('*');
		$this->db->from('categories');
 		$this->db->where('categoryDeleted',0); 
		$this->db->where('categoryRefId',$categoryRefId);  	
		if($categoryId){
			$this->db->where('categoryId !=',$categoryId); 
		}
  		$query = $this->db->get();//echo $this->db->last_query();exit;
  		if($query->num_rows() >0){return $query->row();}
		else return false;
 	} 
 	
 	function addEditCategories($categoryId){
		
   		$accData = array(
				// 'parantCategory' => $this->input->post('parantCategory', TRUE),
				'categoryTitle' => $this->input->post('categoryTitle', TRUE),
				// 'categoryLang' => $this->input->post('categoryLang', TRUE),
				'categoryUser' => $this->admin_model->login_id,
				'categoryUrl' => url_title(strtolower($this->input->post('categoryTitle', TRUE))),
				'categoryRefId' => $this->input->post('categoryOrder', TRUE),
   			);

 		if($categoryId){ //var_dump($accData); exit;
			$this->db->where('categoryId',$categoryId);
			$accData['categoryUpdated'] = date('Y-m-d H:i:s');
			$time_milli = (int) round(microtime(true) * 1000);    // 1491536422147
			$accData['categoryUpdated_t'] = $time_milli;
			$this->db->update('categories', $accData);
 		}else{
			$accData['categoryAdded'] = date('Y-m-d H:i:s');
 			$this->db->insert('categories', $accData);
			$categoryId =  $this->db->insert_id();
		}		
 		return true;
 	}
     	
  	function getQuestionLanguageList(){
		$this->db->select('*');
		$this->db->from('question_languages');
 		$query = $this->db->get();
		$arrMenus = array();
		if($query->num_rows()){
			$arrSubMenus = $query->result(); 
 			return $arrSubMenus;
		}else return false;	
 	}
    //category end
 	
 	function uniqidReal($length = 8){
 	    
 	    // uniqid gives 13 chars, but you could adjust it to your needs.
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil($length / 2));
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil($length / 2));
        } else 
        {
            $bytes =uniqid();
            // throw new Exception("no cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $length);
 	}
 	
 	function get_OneLink_Row($id){
 	    
		$this->db->select('*');
        $this->db->from('app_share_link');
 		$this->db->where('is_deleted',0); 
        $this->db->where('id',$id); 
        
  		$query = $this->db->get();
 		if($query->num_rows()){return $query->row();}
		else return false;

 	}
 	
 	function get_OneLink_List($resType = 'list'){
	    
		$this->db->select('app_share_link.*, categories.categoryTitle');
		$this->db->from('app_share_link')->join('categories','categories.categoryId = app_share_link.category_id');
	
        $this->db->where('app_share_link.is_deleted',0);
        
        $this->db->where('app_share_link.main_link_id',null);
        
 		if($this->input->get('searchKey',true) && $this->input->get('searchBy',true)){
			$this->db->like($this->input->get('searchBy',true),$this->input->get('searchKey',true)); 
		}
		
		if($this->input->get('searchStatus',true) && $this->input->get('searchStatus',true) == 'Enabled'){
 			$this->db->where('app_share_link.is_active',0); 
		}else if($this->input->get('searchStatus',true) && $this->input->get('searchStatus',true) == 'Disabled'){
 			$this->db->where('app_share_link.is_active',1); 
		}
		
		if($this->input->get('daterange_By',true) && $this->input->get('daterange_By',true)){
    	    $rangedate = $this->input->get('daterange_By');
    	    $date_Arr = explode(' - ',$rangedate);
		    $startDate = (date("Y-m-d", strtotime($date_Arr[0])).' 00:00:00');
            $endDate = (date("Y-m-d", strtotime($date_Arr[1])).' 23:59:00');
            $this->db->where("created_at BETWEEN '". $startDate . "' and '".  $endDate."'");
		}

		if($this->input->get('sortBy',true) && $this->input->get('sortOrder',true)){
 			$this->db->order_by($this->input->get('sortBy',true),$this->input->get('sortOrder',true)); 
		}
		
		
		$this->db->order_by('IF(updated_at>created_at, `updated_at` , `created_at`)', 'DESC' ,FALSE);
		
 		if($resType == 'list'){
			$arrSubCategories = array();
			if($this->page)$this->page = ($this->page-1);
			$this->db->limit($this->limit, ($this->page * $this->limit) ); 
			$query = $this->db->get();
			if($query->num_rows()){
				return $query->result();
			}
			else return false;	
 		}
		else if($resType == 'select')
		{
		   $query = $this->db->get();
		   if($query->num_rows()){
				return $query->result();
			}
			else return false;	
		   
		}
		else{
			$query = $this->db->get();
			return $query->num_rows();
		} 
	}
	
  	function isExist_OneLink($app_keyword=false,$id=false,$link_name =false){
        
		$this->db->select('id');
		$this->db->from('app_share_link');
 		$this->db->where('is_deleted',0);
 		
 		if(!empty($app_keyword)){
			$this->db->where('app_keyword',$app_keyword);
		}
		
		if(!empty($link_name)){
			$this->db->where('link_name',$link_name);
		}
	    
		if(!empty($id)){
			$this->db->where('id !=',$id); 
		}
  		$query = $this->db->get();
  		// echo $this->db->last_query();exit;
  		if($query->num_rows()){return true;}
		else return false;

	}
	
    function do_OneLink_Action($action,$ids){
		 
    	if($action == 'delete'){ 
 			$status = 'deleted';
 			// $logMsg = 'DeleteSharelink';
			$data = array( 'is_deleted' => 1 , 'updated_at' => date('Y-m-d H:i:s') );
			$successMsg= 'Share link are deleted successfully';
			$this->db->where_in('id', $ids); $this->db->update('app_share_link', $data);
  		}else if($action == 'disable'){
 			$status = 'disabled';
 			// $logMsg = 'DisableSharelink';
			$data = array( 'is_active' =>1 , 'updated_at'=> date('Y-m-d H:i:s') );$successMsg= 'Share link are disabled successfully';
			 $this->db->where_in('id', $ids); $this->db->update('app_share_link', $data);
  		}else if($action == 'enable'){
 			$status = 'enabled';
 			// $logMsg = 'EnableSharelink';
			$data = array( 'is_active' => 0 , 'updated_at' => date('Y-m-d H:i:s'));$successMsg= 'Share link are enabled successfully';
		    $this->db->where_in('id', $ids); $this->db->update('app_share_link', $data);
  		}else{
  		    $successMsg= 'failed';
  		}
      	
 		return $successMsg;
    		
	}
	
	//sharelink ends
 	
 	function get_UTM_tags_Row($id){
		$this->db->select('*');
        $this->db->from('onelink_utm_tags');
        $this->db->where('is_active',0);
 		$this->db->where('is_deleted',0);
        $this->db->where('link_id',$id);
  		$query = $this->db->get();
 		if($query->num_rows()){return $query->row();}
		else return false;
 	}
 	
    function get_Country_Redi_list($link_id){
        
        $resARR= [];
        
        if(!empty($link_id)){
            
            $this->db->select('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();
     		}
        }
        
        return $resARR;
		
    }
    
    function get_Rotate_Redi_list($link_id){
        
        $resARR= [];
        
        if(!empty($link_id)){
            
            $this->db->select('r_id, r_link');
    		$this->db->from('rotational_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();
     		}
        }
        
        return $resARR;
    }
    
    
    function get_Sublink_list($link_id){
        
        $resARR= [];
        
        if(!empty($link_id)){
            
            $this->db->select('id, share_link,sublink_name,hits');
    		$this->db->from('app_share_link');
     		$this->db->where('is_deleted',0);
    		$this->db->where('main_link_id',$link_id);
    		
      		$query = $this->db->get();
      		// echo $this->db->last_query();exit;
     		if($query->num_rows()){
     		    $resARR =  $query->result();
     		}
        }
        
        return $resARR;
    }
    
    // function get_Sublink_Row($link_id){
        
    //     $resARR= [];
        
    //     if(!empty($link_id)){
            
    //         $this->db->select('id, share_link,sublink_name,hits');
    // 		$this->db->from('app_share_link');
    //  		$this->db->where('is_deleted',0);
    // 		$this->db->where('main_link_id',$link_id);
    		
    //   		$query = $this->db->get();
    //  		if($query->num_rows()){
    //  		    $resARR =  $query->row();
    //  		}
    //     }
        
    //     return $resARR;
    // }
    
    function get_Page_Seo_Row($id){
        
        $this->db->select('*');
        $this->db->from('links_page_seo');
 		$this->db->where('is_deleted',0); 
        $this->db->where('link_id',$id); 
        
  		$query = $this->db->get();
 		if($query->num_rows()){return $query->row();}
		else return false;
    }
    
    
 	function image_server_migrate($url)
	{ 
	    
	   // $url ='http://bibleall.net/examall_dev/assets/site/img/logical_r.png';
	    $this->db->select('*');
		$this->db->from('image_server_info');
        // $this->db->where('commentDeleted',0);
		$this->db->where('from_url',$url); 
  		$query = $this->db->get();
  		
  		$image_path_id='';
  		$result_path = '';
  		
 		if($query->num_rows() == 1 )
 		{
 		    $res = $query->row();
 		    $image_path_id= $res->id;
 		    $image_to_url= $res->to_url;
 		}
 	    
 	  //  var_dump($image_to_url);
 	  //  exit;
 		if(!empty($image_path_id))
 		{ 
 		    $result_path = $image_to_url;
 		 //   $msg='Success with Warning : Already exists url so pass relevant URL';
 		    //already another server path imge downloaded in our server 
 		    //so pass the path only
 		}
 		else
 		{ 
 		    //download image and move to our server 
 		    //then give the path
 		    $res = $this->parseUrl($url);
 		    $base_name = pathinfo($url, PATHINFO_FILENAME);
 		 //   var_dump($base_name); exit;
            $file_extension = pathinfo($url, PATHINFO_EXTENSION); 
            $file_domain = ($res['domain']); 
            //check its not our server
            $cur_host_name = host_name();
            if( ! strstr(parse_url($url,PHP_URL_HOST),$cur_host_name))
            {
                //  echo " match";
                $data = $this->file_get_contents_curl($url);
                $fp = 'uploads/icon_image/'.$base_name.'.'.$file_extension;
                
                if(file_put_contents( $fp, $data ))
                {
                    // echo "File downloaded!";
                    $result_path = base_url().$fp;
                    $msg='Success'; 
                    // var_dump($result_path); exit;
                    
                }
                else
                {
                    // echo "File download failed!";
                    //set as it is
                    $result_path = $url; 
                    $msg='Success with Error : Destination path will incorrect so put it as it is..';
                }
                
                // return $result_path;
                 //insert
     		    $data = array( 'from_url' => $url ,'from_domain_name' => $file_domain , 'to_url' => $result_path ,'created_at' => date('Y-m-d H:i:s') ,'msg'=>$msg);
    		    $this->db->insert('image_server_info', $data);
            }
            else
            {
                // echo "not match";
                // exit;
            }
 		}
 	
// 		echo "res".$result_path."end";
// 		exit;
	    if(!empty($result_path))
	    {
	        return $result_path;
	    }
	    else
	    {
	        return $url;
	    }
	    
	}

    
    function file_get_contents_curl($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    
    
    function parseUrl($url) 
    {
        $r  = "^(?:(?P<scheme>\w+)://)?";
        $r .= "(?:(?P<login>\w+):(?P<pass>\w+)@)?";
        $r .= "(?P<host>(?:(?P<subdomain>[\w\.]+)\.)?" . "(?P<domain>\w+\.(?P<extension>\w+)))";
        $r .= "(?::(?P<port>\d+))?";
        $r .= "(?P<path>[\w/]*/(?P<file>\w+(?:\.\w+)?)?)?";
        $r .= "(?:\?(?P<arg>[\w=&]+))?";
        $r .= "(?:#(?P<anchor>\w+))?";
        $r = "!$r!";                                                // Delimiters
       
        preg_match ( $r, $url, $out );
        return $out;
    }
 	
 	function file_Upload_2($file , $file_name , $filePrefix='img' )
	{
	    if($filePrefix == "m_img") $upload_path = './uploads/m_img';
		else $upload_path = './uploads/img';
			
	    $config['upload_path']          = $upload_path;
	    
        $config['allowed_types']        = 'gif|jpg|png|jpeg|webp|ico';
        
        // The maximum size (in kilobytes) that the file can be. 
        // Set to zero for no limit.
        // Note: Most PHP installations have their own limit, as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default.
        // $config['max_size']= 1024 * (BUILD_FILE_MAX_SIZE()); //50 mb
        
        
        $config['max_size']= 1024 * (25); //25 mb
        
        // $config['encrypt_name']= TRUE; 
        $config['file_name'] = $file_name;
        
        // $config['max_width']            = 1024;
        // $config['max_height']           = 768;
        
        $this->load->library('upload', $config);
        $this->upload->initialize($config);
        
        if ( ! $this->upload->do_upload($file))
        {
                $error = array('error' => $this->upload->display_errors());
                // $this->load->view('upload_form', $error);
                // print_r($error);
                return array('u_res'=>false, 'e_data'=>(string)$error['error']);
        }
        else
        {
                $data = array('upload_data' => $this->upload->data());
                // print_r($data);
                return array('u_res'=>true, 's_data'=>$data['upload_data']['file_name']);
                // $this->load->view('upload_success', $data);
        }
        exit;
	}
 
}

?>