<?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');

        $this->load->library('cors');
        $this->cors->handle();
	}



    public function cors_options($id = 0)
    {
    	$final = array();

   		$final['status'] = true;
   		$final['message'] = 'Validation OK';
    	$this->response($final, REST_Controller::HTTP_OK); 			
    }


	/**
	 * 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)) {
				
				$user_id = $this->user_model->get_user_id_from_hp($hp);
				$user    = $this->user_model->get_user($user_id);
				$paket_club = $this->club_model->get_paket($user->id_club);

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

				// user login ok
					$token_data['uid'] = $user_id;
					$token_data['hp'] = $user->hp; 
					$token_data['nama'] = $user->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'] = $user;

					$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"]);

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

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

			// user login ok
				$token_data['uid'] = $user_id;
				$token_data['hp'] = $user->hp; 
				$token_data['nama'] = $user->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'] = $user;

				$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); 			
		}		
	}	
	


	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) {
					$user    = $this->user_model->get_user($id);
					$final['status'] = true;
					$final['message'] = 'Data confirmed';
					$final['data'] = $user;
				} 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( $hp_input = 0 ) {

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


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

			$data['user_id'] = $this->user_model->get_user_id_from_hp($hp);
			if($data['user_id'] != null && $data['user_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'] = 'New Password Not updated';      					
    			// $final['message'] = 'Not updated utk password='.$input_data['password'].' ID='.$id;      					
    		}
                // ------------- 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; 
}

