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


/**
 * User class.
 * 
 * @extends REST_Controller
 */
require(APPPATH.'/libraries/REST_Controller.php');
use Restserver\Libraries\REST_Controller;


class User extends REST_Controller {

	/**
	 * __construct function.
	 * 
	 * @access public
	 * @return void
	 */
	public function __construct() {
		parent::__construct();
		$this->load->library('Authorization_Token');
		$this->load->model('user_model');
		$this->load->model('club_model');
	}



	/**
	 * login function.
	 * 
	 * @access public
	 * @return void
	 */
	public function login_post() {
		
		$input_data = json_decode($this->input->raw_input_stream, true);
		$final = array();

		// set validation rules
		$this->form_validation->set_data($input_data);
		$this->form_validation->set_rules('hp', 'hp', 'required|alpha_numeric');
		$this->form_validation->set_rules('password', 'Password', 'required');
		if ($this->form_validation->run() == true) {
//			$hp = $input_data["hp"];
			$hp = cek_format_HP($input_data["hp"]);
			$password = $input_data["password"];

			// echo $hp;			
			if ($this->user_model->resolve_user_login($hp, $password)) {
				
				$cust_id = $this->user_model->get_user_id_from_hp($hp);
				$cust    = $this->user_model->get_user($cust_id);
				$paket_club = $this->club_model->get_paket($cust->id_club);

				if ($paket_club != "FREE") {
				// set session user datas
					$_SESSION['user_id']      = (int)$cust->id;
					$_SESSION['hp']     = (string)$cust->hp;
					$_SESSION['nama']     = (string)$cust->nama;
					$_SESSION['logged_in']    = (bool)true;

				// user login ok
					$token_data['uid'] = $cust_id;
					$token_data['hp'] = $cust->hp; 
					$token_data['nama'] = $cust->nama; 
					$tokenData = $this->authorization_token->generateToken($token_data);

					$final['status'] = true;
					$final['message'] = 'Login success!';
					$final['note'] = 'You are now logged in.';
					$final['access_token'] = $tokenData;
					$final['data'] = $cust;

					$this->response($final, REST_Controller::HTTP_OK); 					
				} else {
				// Paket Club failed
					$final['status'] = false;
					$final['message'] = 'Akses ditolak! - Hanya khusus Club PREMIUM atau PRO';
					$this->response($final, REST_Controller::HTTP_OK); 				
				}
				
			} else {				
				// login failed
				$final['status'] = false;
				$final['message'] = 'HP atau Password SALAH!';
				$this->response($final, REST_Controller::HTTP_OK); 				
			}
		} else {			
			// validation not ok, send validation errors to the view
			$final['status'] = false;
			$final['message'] = 'Validation rules violated';
			$this->response($final, REST_Controller::HTTP_OK); 			
		}		
	}



	/**
	 * loginBiometric function.
	 * 
	 * @access public
	 * @return void
	 */
	public function loginBiometric_post() {
		
		$input_data = json_decode($this->input->raw_input_stream, true);
		$final = array();

		// set validation rules
		$this->form_validation->set_data($input_data);
		$this->form_validation->set_rules('hp', 'hp', 'required|alpha_numeric');		
		if ($this->form_validation->run() == true) {
//			$hp = $input_data["hp"];
			$hp = cek_format_HP($input_data["hp"]);

			$cust_id = $this->user_model->get_user_id_from_hp($hp);
			if (!empty($cust_id)) {
				$cust    = $this->user_model->get_user($cust_id);

			// set session user datas
				$_SESSION['user_id']      = (int)$cust->id;
				$_SESSION['hp']     = (string)$cust->hp;
				$_SESSION['nama']     = (string)$cust->nama;
				$_SESSION['logged_in']    = (bool)true;

			// user login ok
				$token_data['uid'] = $cust_id;
				$token_data['hp'] = $cust->hp; 
				$token_data['nama'] = $cust->nama; 
				$tokenData = $this->authorization_token->generateToken($token_data);

				$final['status'] = true;
				$final['message'] = 'Login success!';
				$final['note'] = 'You are now logged in.';
				$final['access_token'] = $tokenData;
				$final['data'] = $cust;

				$this->response($final, REST_Controller::HTTP_OK); 				
			} else {
				$final['status'] = false;
				$final['message'] = 'Nomor HP tidak terdaftar!';
				$this->response($final, REST_Controller::HTTP_OK); 				
			}

		} else {			
			// validation not ok, send validation errors to the view
			$final['status'] = false;
			$final['message'] = 'Validation rules violated';
			$this->response($final, REST_Controller::HTTP_OK); 			
		}		
	}	
	


	/**
	 * loginBiometric function.
	 * 
	 * @access public
	 * @return void
	 */
	public function index_get($id = 0) {
		
		$final = array();
		$headers = $this->input->request_headers(); 
		if (isset($headers['Authorization'])) {
			$decodedToken = $this->authorization_token->validateToken($headers['Authorization']);
			if ($decodedToken['status']) {

                // ------- Main Logic part -------

				// set validation rules
				$input_validation['id'] = $id;
				$this->form_validation->set_data($input_validation);
				$this->form_validation->set_rules('id', 'id', 'required|alpha_numeric');
				if ($this->form_validation->run() == true) {
					$cust    = $this->user_model->get_user($id);
					$final['status'] = true;
					$final['message'] = 'Data confirmed';
					$final['data'] = $cust;
				} else {			
					// validation not ok, send validation errors to the view
					$final['status'] = false;
					$final['message'] = 'Validation rules violated';
				}		
			}
			else {
				$final = $decodedToken;
			}
		}
		else {
			$final['status'] = false;
			$final['message'] = 'Authentication failed';      					
		}

		$this->response($final, REST_Controller::HTTP_OK); 			
	}




    /**
     * UPDATE | PUT method.
     *
     * @return Response
    */
    public function updateProfile_put($id)
    {
    	$headers = $this->input->request_headers(); 
    	$final = array();
    	if (isset($headers['Authorization'])) {
    		$decodedToken = $this->authorization_token->validateToken($headers['Authorization']);
    		if ($decodedToken['status']) {

                // ------- Main Logic part -------
    			$input_data = json_decode($this->input->raw_input_stream, true);
    			$input_validation['id'] = $id;
    			$this->form_validation->set_data($input_validation);
    			$this->form_validation->set_rules('id', 'id', 'required|alpha_numeric');

    			if ($this->form_validation->run() == true) {
    				$response = $this->user_model->update($input_data, $id);
    				if($response>0) {
    					$final['status'] = true;
    					$final['message'] = 'Profile updated successfully.'; 
    				} else {
    					$final['status'] = false;
    					$final['message'] = 'Not updated';      					
    				}
                // ------------- End -------------

    			} else {
    				$final['status'] = false;
    				$final['message'] = 'Validation rules violated';
    			}
    		}
    		else {
    			$final = $decodedToken;
    		}
    	}
    	else {
    		$final['status'] = false;
    		$final['message'] = 'Authentication failed';      					
    	}
    	$this->response($final, REST_Controller::HTTP_OK); 			
    }



	/**
	 * logout function.
	 * 
	 * @access public
	 * @return void
	 */
	public function logout_post() {

		if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
			
			// remove session datas
			foreach ($_SESSION as $key => $value) {
				unset($_SESSION[$key]);
			}
			
			// user logout ok
			$final['status'] = true;
			$final['message'] = 'Logout success!';
			$this->response($final, REST_Controller::HTTP_OK); 
		} else {
			$final['status'] = false;
			$final['message'] = 'There was a problem. Please try again.';
			$this->response($final, REST_Controller::HTTP_OK); 
		}
		
	}


	/**
	 * isPhoneExist_post function.
	 * 
	 * @access public
	 * @return void
	 */
	public function isPhoneExist_get() {

		$input_data = json_decode($this->input->raw_input_stream, true);
		$final = array();

		// set validation rules
		$this->form_validation->set_data($input_data);
		$this->form_validation->set_rules('hp', 'hp', 'required|alpha_numeric');		
		if ($this->form_validation->run() == true) {
//			$hp = $input_data["hp"];
			$hp = cek_format_HP($input_data["hp"]);

			$data['cust_id'] = $this->user_model->get_user_id_from_hp($hp);
			if($data['cust_id'] != null && $data['cust_id'] > 0) {
				$final['status'] = true;
				$final['message'] = 'Data exist';
				$final['data'] = $data;				
			} else {
				$final['status'] = false;
				$final['message'] = 'Data not exist';
			}
		} else {			
			// validation not ok, send validation errors to the view
			$final['status'] = false;
			$final['message'] = 'Validation rules violated';
		}		
		$this->response($final, REST_Controller::HTTP_OK); 
	}		


    /**
     * UPDATE | PUT method.
     *
     * @return Response
    */
    public function changePassword_put($id)
    {
    	$final = array();

                // ------- Main Logic part -------
    	$input_data = json_decode($this->input->raw_input_stream, true);
    	$input_validation['id'] = $id;
    	$input_validation['password'] = $input_data['password'];
    	$this->form_validation->set_data($input_validation);
    	$this->form_validation->set_rules('id', 'id', 'required|alpha_numeric');
    	$this->form_validation->set_rules('password', 'password', 'required');

    	if ($this->form_validation->run() == true) {
    		$response = $this->user_model->update_password($id,$input_data['password']);
    		if($response>0) {
    			$final['status'] = true;
    			$final['message'] = 'Password updated successfully.'; 
    		} else {
    			$final['status'] = false;
    			$final['message'] = 'Not updated';      					
    		}
                // ------------- End -------------

    	} else {
    		$final['status'] = false;
    		$final['message'] = 'Validation rules violated';
    	}
    	$this->response($final, REST_Controller::HTTP_OK); 			
    }


    /**
     * UPDATE | PUT method.
     *
     * @return Response
    */
    public function insertLog_post()
    {
    	$headers = $this->input->request_headers(); 
    	$final = array();
    	if (isset($headers['Authorization'])) {
    		$decodedToken = $this->authorization_token->validateToken($headers['Authorization']);
    		if ($decodedToken['status']) {

                // ------- Main Logic part -------
    			$input_data = json_decode($this->input->raw_input_stream, true);
    			$response = $this->user_model->insert_log($input_data);
    			if($response>0) {
    				$final['status'] = true;
    				$final['message'] = 'Log Inserted successfully.'; 
    			} else {
    				$final['status'] = false;
    				$final['message'] = 'Not updated';      					
    			}
                // ------------- End -------------
    		}
    		else {
    			$final = $decodedToken;
    		}
    	}
    	else {
    		$final['status'] = false;
    		$final['message'] = 'Authentication failed';			
    	}
    	$this->response($final, REST_Controller::HTTP_OK); 			
    }



}



function cek_format_HP($nohp) {
	$hp=trim($nohp);
	if(!preg_match("/[^+0-9]/",$hp)){
            // cek apakah no hp karakter ke 1 dan 2 adalah angka 62
		if(substr(trim($nohp), 0, 2)=="62"){
			$hp=trim($nohp);
		}
            // cek apakah no hp karakter ke 1 adalah angka 0
		else if(substr(trim($nohp), 0, 1)=="0"){
			$hp="62".substr(trim($nohp), 1);
		}
	}    	
	return $hp; 
}

