<?php

class Admin_stat_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));
			 redirect($this->input->post('listUrl',true)); 
		 }
		 if($this->input->get('per_page',true))$this->page = (int)$this->input->get('per_page'); 
  	}
 
    
 	function get_country_chart_data($resType="list"){
 	    
 	    $this->db->select('COUNT(id) as total_c ,country_name');
        $this->db->from('visitor_log');
 		$this->db->where('is_deleted',0);
 		
		if($this->input->get('reportrange',true) && $this->input->get('reportrange',true)){
    	    $rangedate = $this->input->get('reportrange');
    	    $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('sub_link_id',true) ){
 		    $this->db->where('link_id', $this->input->get('sub_link_id',true)); 
 		}
        else if($this->input->get('link_id',true) ){
 		    $this->db->where('link_id', $this->input->get('link_id',true)); 
 		}
        
        $this->db->group_by('country_name');
        
  		$query = $this->db->get();
  		  		 

 		if($query->num_rows()){
 		    
 		    if($resType =="list"){
     		    return $query->result();
     		}else{
     		    return $query->num_rows();
     		}
 		}
		else return false;

 	}
 	
 	function get_device_chart_data(){
 	    
 	    $this->db->select('COUNT(id) as total_c ,os_group_name');
        $this->db->from('visitor_log');
 		$this->db->where('is_deleted',0);
 		
 		if($this->input->get('reportrange',true) && $this->input->get('reportrange',true)){
    	    $rangedate = $this->input->get('reportrange');
    	    $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('sub_link_id',true) ){
 		    $this->db->where('link_id', $this->input->get('sub_link_id',true)); 
 		}
        else if($this->input->get('link_id',true) ){
 		    $this->db->where('link_id', $this->input->get('link_id',true));
 		}
        
        $this->db->group_by('os_group_name');
        
       
  		$query = $this->db->get();
  		//  echo $this->db->last_query();

 		if($query->num_rows()){
 		    return $query->result();
 		    
 		}
		else return false;

 	}
 	
 	function get_click_count_by_id(){
 	    
 	    $this->db->select('COUNT(id) as total_c');
        $this->db->from('visitor_log');
 		$this->db->where('is_deleted',0);
 		
 		if($this->input->get('reportrange',true) && $this->input->get('reportrange',true)){
    	    $rangedate = $this->input->get('reportrange');
    	    $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('sub_link_id',true) ){
 		    $this->db->where('link_id', $this->input->get('sub_link_id',true)); 
 		}
        else if($this->input->get('link_id',true) ){
 		    $this->db->where('link_id', $this->input->get('link_id',true)); 
 		}

  		$query = $this->db->get();
  		//  echo $this->db->last_query();
 		if($query->num_rows()){
 		    $val = $query->row()->total_c;
 		    return $val ? $val:0;
 		}
		else return 0;

 	}
 	
 	
 	function get_destination_listdata($resType="list"){
 	    
 	    $this->db->select('COUNT(id) as total_c ,d_link');
        $this->db->from('destinations_data');
 		$this->db->where('is_deleted',0);
 		
		if($this->input->get('reportrange',true) && $this->input->get('reportrange',true)){
    	    $rangedate = $this->input->get('reportrange');
    	    $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('sub_link_id',true) ){
 		    $this->db->where('link_id', $this->input->get('sub_link_id',true)); 
 		}
        else if($this->input->get('link_id',true) ){
 		    $this->db->where('link_id', $this->input->get('link_id',true)); 
 		}
        
        $this->db->group_by('d_link');
        
  		$query = $this->db->get();
  		
 		if($query->num_rows()){
 		    if($resType =="list"){
     		    return $query->result();
     		}else{
     		    return $query->num_rows();
     		}
 		}
		else return false;

 	}
 	
 	
 	function get_visitlog_List($resType = 'list'){
	    
		$this->db->select('*');
		$this->db->from('visitor_log');
        $this->db->where('visitor_log.is_deleted',0);
        
        if($this->input->get('sub_link_id',true) ){
 		    $this->db->where('link_id', $this->input->get('sub_link_id',true)); 
 		}
        else if($this->input->get('link_id',true) ){
 		    $this->db->where('link_id', $this->input->get('link_id',true)); 
 		}
 		
 		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('reportrange',true) && $this->input->get('reportrange',true)){
    	    $rangedate = $this->input->get('reportrange');
    	    $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('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();
            //  echo $this->db->last_query();exit;

			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 get_installation_count(){
	    
        if($this->input->get('sub_link_id',true) ){
 		    $link_id = $this->input->get('sub_link_id',true);
 		}
        else if($this->input->get('link_id',true) ){
 		    $link_id = $this->input->get('link_id',true); 
 		}
 		else{
 		    $link_id='';
 		}
 		
 	    $Res_count['android']=0;
 	    $Res_count['ios']=0;
 		
 		if(!empty($link_id)){
 		    
 	    	$ol_row = $this->get_OneLink_Row($link_id);
 	    	
 	    	if(!empty($ol_row)){
 	    	    $target_type = isset($ol_row->target_type) && !empty($ol_row->target_type)?$ol_row->target_type:'';
 	    	    $android_url = isset($ol_row->android_play_store_url) && !empty($ol_row->android_play_store_url)?$ol_row->android_play_store_url:'';
     	        $ios_url = isset($ol_row->ios_apple_id) && !empty($ol_row->ios_apple_id)?$ol_row->ios_apple_id:'';
     	        $app_keyword = isset($ol_row->app_keyword) && !empty($ol_row->app_keyword)?$ol_row->app_keyword:'';
 	    	    if(strtolower($target_type) == 'device' ){
 	    	        
 	    	     //   $packge_name='';
 	    	     //   if(!empty($android_url)){
            //     	    $find_str="https://play.google.com/store/apps/details?id=";
            //             $resss = explode($find_str, $android_url);
            //             if(isset($resss[1])&&!empty($resss[1])){
            //                 $packge_name = $resss[1];
            //             }
 	    	     //   }
 	    	        
 	    	        if(!empty($app_keyword)){
 	    	            
     	                $this->db->select('max(id), device_type,COUNT(id) as total_count');
                		$this->db->from('utm_data');
                		
                        // $this->db->where('utm_content',$app_keyword);
                        $this->db->where('aref_key',$app_keyword);
                        // $this->db->where('package_name',$packge_name);
                        // $this->db->like('referer',$app_keyword);
                        $this->db->group_by('device_type');
                        
                        if($this->input->get('reportrange',true) && $this->input->get('reportrange',true)){
                    	    $rangedate = $this->input->get('reportrange');
                    	    $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."'");
                		}
                		
                		$query = $this->db->get();
                // 		echo $this->db->last_query();
                // 		exit;
            			if($query->num_rows()){
            				foreach($query->result() as $ssr){
            				    if( isset($ssr->device_type) && !empty($ssr->device_type =='android') ) {
            				        $Res_count['android'] = isset($ssr->total_count) && !empty($ssr->total_count) ?  $ssr->total_count:0;
            				    }
            				    
            				    if( isset($ssr->device_type) && !empty($ssr->device_type =='ios') ){
            				        $Res_count['ios'] = isset($ssr->total_count) && !empty($ssr->total_count) ? $ssr->total_count:0;
            				    }
            				}
            				
            			}
                    
 	    	        }
                    
 	    	    }
 	    	   
 	    	}
 	    	
 		}
 		
		return $Res_count;
		
	}
	
  	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;

 	}
	
   
	//sharelink ends
 	
 	
 	
 	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 A') ,'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;
	}
 
}
?>