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

class Index extends CI_Controller
{

   /*Function to set JSON output*/
	public function output($Return=array()){
		/*Set response header*/
		header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		/*Final JSON response*/
		exit(json_encode($Return));
	}
	
	public function __construct()
     {
          parent::__construct();
          $this->load->library('session');
          $this->load->helper('form');
          $this->load->helper('url');
          $this->load->helper('html');
          $this->load->database();
          $this->load->library('form_validation');
          //load the login model
          $this->load->model('Login_model');
		  $this->load->model('Xin_model');
     }
	 
	public function login() {
	    
	    function get_client_ip() {
            $ipaddress = '';
            if (getenv('HTTP_CLIENT_IP'))
                $ipaddress = getenv('HTTP_CLIENT_IP');
            else if(getenv('HTTP_X_FORWARDED_FOR'))
                $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
            else if(getenv('HTTP_X_FORWARDED'))
                $ipaddress = getenv('HTTP_X_FORWARDED');
            else if(getenv('HTTP_FORWARDED_FOR'))
                $ipaddress = getenv('HTTP_FORWARDED_FOR');
            else if(getenv('HTTP_FORWARDED'))
               $ipaddress = getenv('HTTP_FORWARDED');
            else if(getenv('REMOTE_ADDR'))
                $ipaddress = getenv('REMOTE_ADDR');
            else
                $ipaddress = 'UNKNOWN';
            return $ipaddress;
        }
        
        $user_ip = get_client_ip();
	    
		$this->form_validation->set_rules('iusername', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('ipassword', 'Password', 'trim|required|xss_clean');
		$Return = array('result'=>'', 'error'=>'');
		
		$username = trim($this->input->post('iusername',TRUE));
		$password = trim($this->input->post('ipassword',TRUE));
		/* Define return | here result is used to return user data and error for error message */
		$Return = array('result'=>'', 'error'=>'');
		
		/* Server side PHP input validation */
		if($username==='') {
			$Return['error'] = "Username field is required.";
		} elseif($password===''){
			$Return['error'] = "Password field is required.";
		}
		if($Return['error']!=''){
			$this->output($Return);
		}
		
		$query = $this->Xin_model->read_user_info_byemail($username);
		$q_result = $query->result();
		if($q_result){
		    $salt = $q_result[0]->password_salt;
    		$pw_hash = sha1($salt.$password);
    		
    		$data = array(
    			'username' => $username,
    			'sec_pass' => $pw_hash,
    			);
    			//print_r($salt);exit();
    		    $result = $this->Login_model->login($data);	
    		    
		}else{
		    $result = 0;
		}
		//print_r($result);exit();
		
		
		if ($result == TRUE) {
			    
				$result = $this->Login_model->read_user_information_login($username,$pw_hash);
				$session_data = array(
				'user_id' => $result[0]->id,
				'root_id' => 1,
				'email' => $result[0]->email,
				);
				
				$cookie_name = $this->Xin_model->get_cookie_name();
				// Add user data in session
				$this->session->set_userdata($cookie_name, $session_data);
				$Return['result'] = 'Logged In Successfully.';
				// update last login info
				$ipaddress = $this->input->ip_address();
				  
				 $last_data = array(
					'last_login_date' => date('d-m-Y H:i:s'),
					'last_login_ip' => $ipaddress,
					'is_logged_in' => '1'
				); 
				
				$id = $result[0]->id; // user id 
				
                $cookie_value = $session_data;
                
                setcookie($cookie_name, serialize($cookie_value), time() + (86400 * 30), "/"); // 86400 = 1 day
				  
				//$this->Tools_model->update_login_record($last_data, $id);
				$this->output($Return);
				
			} else {
				$Return['error'] = "Invalid Login Credential.";
				/*Return*/
				$this->output($Return);
			}
		}
} 
?>