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

class Home 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 function __construct(){
	    parent::__construct();
	}
    
	public function index($uniq_id = null)
	{
	    
	    $final_red_link ='https://link.downly.app/';
	    // var_dump($uniq_id);
	    // exit;
	    if(!empty($uniq_id)){
	        
	        $this->load->model('Home_model');
            $res_data = $this->Home_model->validate_uniq_id($uniq_id);
            // print_r($res_data);
            // exit;
            if(!empty($res_data))
            {
                
                $visit_log_data = $this->log_visitor_data($res_data->id);
                
                $res_red_link = $this->identify_link_dev($res_data, $visit_log_data);
                
                if(!empty($res_red_link)){
                    $final_red_link = $res_red_link;
                    //update this keyword
                    $update_arr['updated_at']= date('Y-m-d H:i:s');
                    $this->db->set('hits', 'hits+1', FALSE);
                    $this->db->where('id', $res_data->id);
                    $this->db->update('app_share_link', $update_arr);
                    
                }
            }
        
	    }
        else{
            // show_404();
        }
        
        
        //insert desstiny link
        $link_id = (int) isset($res_data->id)&&!empty($res_data->id) ? $res_data->id : 0;
        $res_destiny_log = $this->db->insert('destinations_data', ['link_id'=>$link_id ,'d_link'=>$final_red_link,'created_at'=> date('Y-m-d H:i:s') ]);
        
        
        redirect($final_red_link);
        
	}
	
	
	
	private function identify_link($res_data, $visit_log_data){
        
        $website_url = $res_data->website_url;
        $android_play_store_url = $res_data->android_play_store_url;
        $ios_app_store_url = $res_data->ios_app_store_url;

        $os_platform = isset($visit_log_data['os_group_name'])&&!empty($visit_log_data['os_group_name'])? $visit_log_data['os_group_name'] :"";
        
        define("BASE_PATH" ,"https://link.downly.app/");
        
        $share_app_url = '';
        // $android_playstore_link ="https://play.google.com/store/apps/details?id=";
        $android_playstore_link_redir ="https://play.app.goo.gl/?link=";
        $android_playstore_link_redir_2 ="https://play.app.goo.gl/?link=";
        
        // $launch = '';
        // $ios_appstore_link = "https://apps.apple.com/app/id" ;
        
        if(!empty($website_url)){
            $website_url_set = $website_url;
        }
        else{
            $website_url_set = BASE_PATH;
        }
        
        
        if($os_platform == "Android")
        {
            //redir to android 
            if(!empty($android_play_store_url)){
                $share_app_url = $android_playstore_link_redir.$android_play_store_url;
            }
            else{
               //android value is empty so redr to website
                $share_app_url = $website_url_set;
            }
        }else if($os_platform == "Windows"){
            $share_app_url = $website_url_set;
        }
        else if($os_platform == "iOS")
        {
            //redir to ios
            if(!empty($ios_app_store_url)){
                $share_app_url = $ios_app_store_url;
            }
            else{
               //ios value is empty so redr to website
                $share_app_url = $website_url_set;
            }
        }
        else {
            $share_app_url = $website_url_set;
        }
        
        return $share_app_url;
	}
    
    private function identify_link_dev($res_data, $visit_log_data){
        
        define("BASE_PATH" ,"https://link.downly.app/");
        
        $res_url ='';
        
        if(isset($res_data->target_type) && !empty($res_data->target_type) && isset($res_data->id) && !empty($res_data->id) && 
        isset($res_data->destination_default_link) && !empty($res_data->destination_default_link) ){
            
            $link_id = $res_data->id;
            $default_des_url = isset($res_data->destination_default_link) && !empty($res_data->destination_default_link) ? $res_data->destination_default_link:"";
            $res_temp_url='';
            
            
            //check is sublink
            // $sub_link_flag=false;
            $sl_main_link_id=0;
            if(isset($res_data->main_link_id) && !empty($res_data->main_link_id) ){
                $sl_main_link_id = $res_data->main_link_id;
            }
            
            
            $appd_utm_content = isset($res_data->app_keyword) && !empty($res_data->app_keyword)? $res_data->app_keyword:'';
            
            $res_utm_url ='';
            //append utm data
            if(isset($res_data->utm_flag) && !empty($res_data->utm_flag) ){
                ///get the utm tags
                //before that check sublink is thr then get utm data from mainlink id
                $ttemp_link_id=$link_id;
                if(!empty($sl_main_link_id)){
                    $ttemp_link_id = $sl_main_link_id;
                }
                // var_dump($ttemp_link_id);exit;
                $res_utm_url = $this->get_utm_url($ttemp_link_id,$appd_utm_content);
                if(!empty($res_utm_url)){
                    $res_utm_url = $res_utm_url;
                    // $res_temp_url .= $res_utm_url;
                }
                
                
            }
            // var_dump($res_utm_url);exit;
            
            
            if($res_data->target_type == 'None' || strtolower($res_data->target_type) == 'none'){
                //none type means return default desitna link
                $res_temp_url = isset($res_data->destination_default_link) && !empty($res_data->destination_default_link) ? $res_data->destination_default_link:"";
            }
            elseif($res_data->target_type == 'Device' || strtolower($res_data->target_type) == 'device'){
                
                //device type means check current req dev and set
                $os_platform = isset($visit_log_data['os_group_name'])&&!empty($visit_log_data['os_group_name'])? $visit_log_data['os_group_name'] :"";
                if(!empty($os_platform)){
            
                    $windows_url = isset($res_data->website_url)&&!empty($res_data->website_url)? $res_data->website_url :"";
                    $android_play_store_url = isset($res_data->android_play_store_url)&&!empty($res_data->android_play_store_url)? $res_data->android_play_store_url :"";
                    $ios_app_store_url = isset($res_data->ios_app_store_url)&&!empty($res_data->ios_app_store_url)? $res_data->ios_app_store_url :"";
                    
                    // $android_playstore_link_redir ="https://play.app.goo.gl/?link=";
                    // $android_playstore_link ="https://play.google.com/store/apps/details?id=";
                    $android_playstore_link_redir="";
                    
                    if($os_platform == "Android")
                    {
                        //redir to android
                        if(!empty($android_play_store_url)){
                            
                            // $res_temp_url = $android_playstore_link_redir.$android_play_store_url;
                            // $android_play_store_url = $this->convert_android_playstoreurl_into_makert_url($android_play_store_url);
                            // var_dump($android_play_store_url);exit;
                            $res_temp_url = $android_play_store_url;
                            if(!empty($res_utm_url)){
                                $res_temp_url .='&referrer='.urlencode($res_utm_url);
                            }
                            
                        }
                        
                    }else if($os_platform == "Windows"){
                        //redir to windows 
                        if(!empty($windows_url)){
                            $res_temp_url = $windows_url;
                        }
                        // var_dump($res_utm_url);exit;
                        if(!empty($res_utm_url)){
                            $res_temp_url .= '?' . ($res_utm_url);
                        }
                        
                    }
                    else if($os_platform == "iOS")
                    {
                        //redir to ios
                        if(!empty($ios_app_store_url)){
                            $res_temp_url = $ios_app_store_url;
                        }
                        
                        if(!empty($res_utm_url)){
                            $res_temp_url .= '?referrer='.urlencode($res_utm_url);
                        }
                    }
                    
                }
                
            }
            elseif($res_data->target_type == 'Country' || strtolower($res_data->target_type) == 'country'){
                
                //device type means check current req dev and set
                $country_code = isset($visit_log_data['country_code'])&&!empty($visit_log_data['country_code'])? $visit_log_data['country_code'] :"";
                if(!empty($country_code)){
                    $res_ctr_red = $this->Home_model->get_country_redirects_data($link_id, $country_code );
                    if(!empty($res_ctr_red)){
                        $res_temp_url = isset($res_ctr_red->c_d_link)&&!empty($res_ctr_red->c_d_link)? $res_ctr_red->c_d_link :"";
                    }
                }
            }
            elseif($res_data->target_type == 'Rotate' || strtolower($res_data->target_type) == 'rotate'){
                
                //rotate type means check ip and red roationally
                $ip = isset($visit_log_data['ip'])&&!empty($visit_log_data['ip'])? $visit_log_data['ip'] :"";
                if(!empty($ip)){
                    
                    // var_dump($link_id);exit;
                    $res_ctr_red_link = $this->Home_model->get_rotational_redirects_data($link_id, $ip );
                    if(!empty($res_ctr_red_link)){
                        // var_dump($res_ctr_red_link);exit;
                        $res_temp_url = $res_ctr_red_link;
                    }
                }
            }
            elseif($res_data->target_type == 'SEO' || strtolower($res_data->target_type) == 'seo'){
                
                $res_page_slug = $this->Home_model->get_seolink_page_data($link_id );
                if(!empty($res_page_slug)){
                    
                    $LINK_PAGE_SEO_BASE_PATH = 'https://link.downly.app/a/';
                    
                    // var_dump($res_ctr_red_link);exit;
                    $res_temp_url = $LINK_PAGE_SEO_BASE_PATH.$res_page_slug;
                }
                
            }
            else{
                //set default destinationsl link
                // $res_temp_url
            }
            
            
            
            if(!empty($res_temp_url)){
                $res_url = $res_temp_url;
            }
            else{
                $res_url = $default_des_url;
            }

        }
        
        if(!empty($res_url)){
            $res_url = $res_url;
        }
        else{
            $res_url = BASE_PATH;
        }
        
        
        return $res_url;
        
	}
    
    private function log_visitor_data($link_id){
	    
	    $ip = $this->get_ip_address();
	    
        $is_robot = $this->agent->is_robot();
        $is_mobile = $this->agent->is_mobile();
        $is_browser = $this->agent->is_browser();
        $is_referral = $this->agent->is_referral();
        $browser_with_version = $this->agent->browser()."version:". $this->agent->version();
        $os_platform = $this->agent->platform();
        $os_group_name = $this->get_os_group_name();
        
        $user_agent_str = $this->agent->agent_string();
        $user_agent = $this->get_user_agent();
	    $current_url = current_url();
	    $referrer_url = $this->agent->referrer();
        $request_time = $_SERVER['REQUEST_TIME'];
    
	    $ip_data = $this->get_ip_info_from_thirdparty($ip);
	    
	    $country_code="";$country_name="";
	    $region_name="";
	    $city_name="";
	    $postal="";
        if($ip_data->result == 'true'){
            // print_r($ip_data);
            // echo "</pre>";
            if(!empty($ip_data->country_code)){
                $country_name = $this->get_country_name($ip_data->country_code);
            }else{
                $country_name = $ip_data->country_code;
            }
            
            $country_code = !empty($ip_data->country_code) ? $ip_data->country_code : "";
            $region_name = !empty($ip_data->region_name) ? $ip_data->region_name : "";
            $city_name = !empty($ip_data->city_name) ? $ip_data->city_name : "";
            $postal = !empty($ip_data->postal) ? $ip_data->postal : "";
            
        }
    
	    $visit_log_data = array(
	        'link_id'       => $link_id,
			'ip'            => $ip,
			'log_url'       => $current_url,
            'user_agent_str'=> $user_agent_str,
            'user_agent'    => $user_agent,
            'os_platform'   => $os_platform,
            'os_group_name' => $os_group_name,
            'referer_url'   => $referrer_url,
            'request_time'  => $request_time,
            'iploc_data'    => json_encode($ip_data),
            'country_code'  => $country_code,
            'country_name'  => $country_name,
            'region_name'   => $region_name,
            'city_name'     => $city_name,
            'postal_code'   => $postal,
            
			'created_at'    => date('Y-m-d H:i:s')
		);
	    $res_log = $this->db->insert('visitor_log', $visit_log_data);
	    //unset value
	    unset($visit_log_data['iploc_data']);
	    unset($visit_log_data['request_time']);
	    
	    if($res_log){
	         $insert_id = $this->db->insert_id();
	         $visit_log_data['log_id'] = $insert_id;
	    }
	    else{
	        $visit_log_data['log_id'] = false;
	    }
	    
	    return $visit_log_data;
		    
	}
	
	private function get_os_group_name(){
        
        $user_agent = $this->agent->agent_string();
        $os_platform  = "Unknown OS Platform";

        $os_array     = array(
          '/windows nt 10/i'      =>  'Windows 10',
          '/windows nt 6.3/i'     =>  'Windows 8.1',
          '/windows nt 6.2/i'     =>  'Windows 8',
          '/windows nt 6.1/i'     =>  'Windows 7',
          '/windows nt 6.0/i'     =>  'Windows Vista',
          '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
          '/windows nt 5.1/i'     =>  'Windows XP',
          '/windows xp/i'         =>  'Windows XP',
          '/windows nt 5.0/i'     =>  'Windows 2000',
          '/windows me/i'         =>  'Windows ME',
          '/win98/i'              =>  'Windows 98',
          '/win95/i'              =>  'Windows 95',
          '/win16/i'              =>  'Windows 3.11',
          '/macintosh|mac os x/i' =>  'Mac OS X',
          '/mac_powerpc/i'        =>  'Mac OS 9',
          '/linux/i'              =>  'Linux',
          '/ubuntu/i'             =>  'Ubuntu',
          '/iphone/i'             =>  'iPhone',
          '/ipod/i'               =>  'iPod',
          '/ipad/i'               =>  'iPad',
          '/android/i'            =>  'Android',
          '/blackberry/i'         =>  'BlackBerry',
          '/webos/i'              =>  'Mobile'
        );

        foreach ($os_array as $regex => $value)
            if (preg_match($regex, $user_agent))
                $os_platform = $value;
        
        
        $windows_os_array = array('Windows 10','Windows 8.1', 'Windows 8', 'Windows 7', 'Windows Vista', 'Windows Server 2003/XP x64', 'Windows XP', 'Windows XP',
                                'Windows 2000', 'Windows ME', 'Windows 98', 'Windows 95', 'Windows 3.11');
        
        $ios_os_array = array('Mac OS X','Mac OS 9', 'iPhone', 'iPod', 'iPad');
        $android_os_array = array('Android','Mobile');
        $ubuntu_os_array = array('Linux','Ubuntu');
        $blackberry_os_array = array('BlackBerry');
                
        if(in_array($os_platform , $windows_os_array))
        {
            $os_platform = 'Windows';
        }
        else if(in_array($os_platform , $ios_os_array))
        {
            $os_platform = 'iOS';
        }
        else if(in_array($os_platform , $android_os_array))
        {
            $os_platform = 'Android';
        }
        else if(in_array($os_platform , $ubuntu_os_array))
        {
            $os_platform = 'Ubuntu';
        }
        else if(in_array($os_platform , $blackberry_os_array))
        {
            $os_platform = 'BlackBerry';
        }
        else 
        {
            $os_platform = 'Unknown Platform';
        }
        
        return $os_platform;
    }
    
	private function get_country_name($country_code){
	    
	    if(!empty($country_code)){
	        
	        $res = $this->db->select('nicename')->from('country')->where('iso',$country_code)->get()->row()->nicename;
    	    if(!empty($res)){
    	        return $res;
    	    }else{
    	        return "";
    	    }
	    }
	    else return "";
	    
	}
	
	
	private function get_utm_url($link_id,$appd_utm_content){
	    
	    $res_str_url = '';
	    
	    $res_utm = $this->Home_model->get_utm_row($link_id);
	   // var_dump($res_utm);
	   // exit;
	    //before the linkid was check its sublinks
	   // $res_sublinks = $this->Home_model->get_utm_row($link_id);
	    
        if(!empty($res_utm)){
            $url_arr = array();
            $url_arr['utm_source'] = isset($res_utm->utm_source)&&!empty($res_utm->utm_source) ? $res_utm->utm_source :'';
            $url_arr['utm_medium'] = isset($res_utm->utm_medium)&&!empty($res_utm->utm_medium) ? $res_utm->utm_medium :'';
            $url_arr['utm_campaign'] = isset($res_utm->utm_campaign)&&!empty($res_utm->utm_campaign) ? $res_utm->utm_campaign :'';
            $url_arr['utm_term'] = isset($res_utm->utm_term)&&!empty($res_utm->utm_term) ? $res_utm->utm_term :'';
            $url_arr['utm_content'] = isset($res_utm->utm_content)&&!empty($res_utm->utm_content) ? $res_utm->utm_content :'';
            
            //add custom key
            if($appd_utm_content){
                $url_arr['aref_key'] = $appd_utm_content;
            }else{
                $url_arr['aref_key'] = '';
            }
            
            $url_arr = array_filter($url_arr);
            if(!empty($url_arr)){
                $res_str_url = http_build_query($url_arr);
            }
        }
        return $res_str_url;
	}
	
	private function convert_android_playstoreurl_into_makert_url($andr_url){
	    
	    $ressend = $andr_url;
	    $find_str="https://play.google.com/store/apps/details?id=";
        $replac_str = "market://details?id=";
        // $replac_str = "http://market.android.com/details?id=";
        $res = str_replace($find_str, $replac_str, $andr_url);
        if(!empty($res)){
        	$ressend=$res;
        }
        
        return $ressend;
	}
	
	
	private function get_user_agent(){    
        
        if ($this->agent->is_browser()){
            $agent = $this->agent->browser().' '.$this->agent->version();
        }
        elseif ($this->agent->is_robot()){
            $agent = $this->agent->robot();
        }
        elseif ($this->agent->is_mobile()){
            $agent = $this->agent->mobile();
        }
        else{
            $agent = 'Unidentified User Agent';
        }

        return $agent;
    }
    
    private static function get_ip_address(){		
		$ip = getenv('HTTP_CLIENT_IP')?:
			getenv('HTTP_X_FORWARDED_FOR')?:
			getenv('HTTP_X_FORWARDED')?:
			getenv('HTTP_FORWARDED_FOR')?:
			getenv('HTTP_FORWARDED')?:
			getenv('REMOTE_ADDR');		
		return $ip;
	}
	
	private function get_ip_info_from_thirdparty($ip_address)
    {
        
        $resArr['result'] =false;
        $resArr['latitude'] ="";
        $resArr['longitude'] ="";
        $resArr['timezone'] ="";
        $resArr['country_code'] ="";
        $resArr['region_name'] ="";
        $resArr['city_name'] ="";
        $resArr['postal'] ="";
        
        if($resArr['result'] == false ){
            
            if(1){
                //case 1
                // $access_token = 'a77a5851e8bb68';
                $URL="http://ipinfo.io/".$ip_address."/json?token=a77a5851e8bb68";
                $ip_datas =  $this->curl_get_file_contents($URL);
                
                if(!empty($ip_datas)){
                    $ip_datas = json_decode($ip_datas);
                    // print_r($ip_datas);
                    // exit;
                    
                    if(!empty($ip_datas->ip))
                    {   
                        $resArr['result']=true;
                        if(isset($ip_datas->loc)&&!empty($ip_datas->loc) ){
                            $loca_arr = explode(",",$ip_datas->loc);
                            $resArr['latitude'] = isset($loca_arr[0])&&!empty($loca_arr[0]) ? $loca_arr[0] :"";
                            $resArr['longitude'] = isset($loca_arr[1])&&!empty($loca_arr[1]) ? $loca_arr[1] :"";
                        }
                        
                        $resArr['timezone'] = isset($ip_datas->timezone)&&!empty($ip_datas->timezone) ? $ip_datas->timezone :"";
                        $resArr['country_code'] = isset($ip_datas->country)&&!empty($ip_datas->country) ? $ip_datas->country :"";
                        $resArr['region_name'] = isset($ip_datas->region)&&!empty($ip_datas->region) ? $ip_datas->region :"";
                        $resArr['city_name'] = isset($ip_datas->city)&&!empty($ip_datas->city) ? $ip_datas->city :"";
                        $resArr['postal'] = isset($ip_datas->postal)&&!empty($ip_datas->postal) ? $ip_datas->postal :"";
                        
                    }
                }
            }
        }
        
        
        if($resArr['result'] == false ){
            
            if(1){
        
                //case 2
                $URL = "https://api.freegeoip.app/json/".$ip_address."?apikey=ca2308d0-aa77-11ec-86cc-752248878f40";
                $ip_datas = $this->curl_get_file_contents($URL);
                
                if(!empty($ip_datas)){
                    
                    $ip_datas = json_decode($ip_datas);
                    
                    // print_r($ip_datas);
                    // exit;
                    if(!empty($ip_datas->ip))
                    {
                        $resArr['result']=true;
                        $resArr['latitude'] = isset($ip_datas->latitude)&&!empty($ip_datas->latitude) ? $ip_datas->latitude :"";
                        $resArr['longitude'] = isset($ip_datas->longitude)&&!empty($ip_datas->longitude) ? $ip_datas->longitude :"";
                        $resArr['timezone']= isset($ip_datas->time_zone)&&!empty($ip_datas->time_zone) ? $ip_datas->time_zone :"";
                        $resArr['country_code'] = isset($ip_datas->country_code)&&!empty($ip_datas->country_code) ? $ip_datas->country_code :"";
                        $resArr['region_name']= isset($ip_datas->region_name)&&!empty($ip_datas->region_name) ? $ip_datas->region_name :"";
                        $resArr['city_name']= isset($ip_datas->city)&&!empty($ip_datas->city) ? $ip_datas->city :"";
                        $resArr['postal']= isset($ip_datas->zip_code)&&!empty($ip_datas->zip_code) ? $ip_datas->zip_code :"";
                    }
                }
            }
            
        }
        
        
        if($resArr['result'] == false ){
            
            if(1){
        
                //case 3
                $URL="http://www.geoplugin.net/json.gp?ip=".$ip_address;
                $ip_datas = $this->curl_get_file_contents($URL);
                $ip_datas = json_decode($ip_datas);
                // print_r($ip_datas);
                // exit;
                if($ip_datas->geoplugin_status == "200")
                {
                    $resArr['result']=true;
                    $resArr['latitude'] = isset($ip_datas->geoplugin_latitude)&&!empty($ip_datas->geoplugin_latitude) ? $ip_datas->geoplugin_latitude :"";
                    $resArr['longitude'] = isset($ip_datas->geoplugin_longitude)&&!empty($ip_datas->geoplugin_longitude) ? $ip_datas->geoplugin_longitude :"";
                    $resArr['timezone']= isset($ip_datas->geoplugin_timezone)&&!empty($ip_datas->geoplugin_timezone) ? $ip_datas->geoplugin_timezone :"";
                    $resArr['country_code'] = isset($ip_datas->geoplugin_countryCode)&&!empty($ip_datas->geoplugin_countryCode) ? $ip_datas->geoplugin_countryCode :"";
                    $resArr['region_name']= isset($ip_datas->geoplugin_region)&&!empty($ip_datas->geoplugin_region) ? $ip_datas->geoplugin_region :"";
                    $resArr['city_name']= isset($ip_datas->geoplugin_city)&&!empty($ip_datas->geoplugin_city) ? $ip_datas->geoplugin_city :"";
                    $resArr['postal']= "";
                }
            }
        }
        
        
        // print_r($resArr);
        // exit;
        
        return (object)$resArr;
        
    }
	
	private static function curl_get_file_contents($URL)
    {
        
        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_HEADER, FALSE);
        curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($c, CURLOPT_URL, $URL);
        $contents = curl_exec($c);
        curl_close($c);

        if ($contents) return $contents;
        else return FALSE;
    }
    
}
