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

class Ewasap extends CI_Controller {

	public $data = array();

	public function __construct() {

		parent::__construct();
		
		// Load library mobile detect
		$this->load->library('Mobile_Detect');

		// Load User-Agent library
		$this->load->library('user_agent');

		// Load Model
		$this->load->model('ewasap_model');

	}

	public function index()
	{
		// Detect what OS
		$detect = new Mobile_Detect();
		$currentOS = "";

		if($detect->isiOS()) {
			$currentOS = 'iOS';
		} else if ($detect->isAndroidOS()) {
			$currentOS = 'Android';
		} else {
			$currentOS = 'Others';
		}


		if ($this->agent->is_referral()) {
    		$referrer = $this->agent->referrer();
		}

		// Get subdomain name
		$firstValue = explode('.', $_SERVER['HTTP_HOST']);

		// Query for the correct link
		$linkResult = $this->ewasap_model->get_link_details($firstValue[0],$firstValue[1]);

		
		// When query is correct
		if($linkResult) {

			// Update count
			$data = array(
				'LinkID' => $linkResult->ID,
				'IPAddress' => $this->_getRealIpAddr(),
				'ClickTime' => date('Y-m-d H:i:s'),
				'OperatingSystem' => $currentOS,
				'Referrer' => isset($referrer) ? $referrer : null
			);

			$this->db->insert('click_log',$data);

			// Redirect the link
			$whatsappLink = "https://api.whatsapp.com/send?phone=";
			$whatsappLink .= $linkResult->PhoneNumber;
			$whatsappLink .= "&text=";
			$whatsappLink .= $linkResult->Text;

			redirect($whatsappLink,'refresh');
			

		} else {
			$this->load->view('error');
		}
		
	}

	function _getRealIpAddr()
	{
	    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
	    {
	      $ip=$_SERVER['HTTP_CLIENT_IP'];
	    }
	    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
	    {
	      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	    }
	    else
	    {
	      $ip=$_SERVER['REMOTE_ADDR'];
	    }
	    return $ip;
	}

}
