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

class User extends CI_Controller {

    public function get_all_users(){
        header('Content-Type: application/json');
        $this->load->model('User_model');
        $this->load->library('Token');
        $headers = $this->input->request_headers();

		if ($this->token->token_post($headers)) {
        echo json_encode($this->User_model->get_all_users());
    }
    } 


    public function create_new_user(){
        header('Content-Type: application/json');
        $this->load->model('User_model');
        echo json_encode($this->User_model->insert_app_user());
    } 
    

    public function is_login(){
        header('Content-Type: application/json');
        $stream_clean = $this->security->xss_clean($this->input->raw_input_stream);
        $request = json_decode($stream_clean);
        $username = $request->login;
        $password = $request->password;
        $login_date = date("dmYhis");
        $data = $username." ".$password." ".$login_date;

        $this->load->model('User_model');
        $this->load->library('Token');
		$token = $this->token->token_get($data);

        $user = $this->User_model->get_logged_in_user($username,$password);
        if ($user==null){
            $productArray = ['code'=>'99', 'message'=>'Invalid Username or Password!', 'token'=>'', 'user'=>''];
            echo json_encode($productArray);
        }
        else{
            $productArray = ['code'=>'00', 'message'=>'User Logged In Successfully', 'token'=> $token, 'user' =>$user];
            echo json_encode($productArray); 
        }
	  } 
    

      public function get_user_by_id(){
        header('Content-Type: application/json');
		$productArray = [];
		$headers = $this->input->request_headers();	

        $id = $this->input->get('id',TRUE);
        $this->load->model('User_model');	
		$this->load->library('Token');

        $user = $this->user_model->get_user_by_id($id);

		if($this->token->token_post($headers))
			$productArray = ['code'=>'00', 'msg'=>'User Retrieved Successfully', 'user'=> $user ];
		else
			$productArray = ['code'=>'99', 'msg'=>'Invalid/Expired Token'];
		
		header('Content-Type: application/json');
		echo json_encode($productArray);
	  } 
    
      public function get_user_by_username(){
        header('Content-Type: application/json');
		$productArray = [];
		$headers = $this->input->request_headers();	

        $id = $this->input->get('username',TRUE);
        $this->load->model('User_model');	
		$this->load->library('Token');

        $user = $this->user_model->get_user_by_username($id);

		if($this->token->token_post($headers))
			$productArray = ['code'=>'00', 'msg'=>'User Retrieved Successfully', 'user'=>$user];
		else
			$productArray = ['code'=>'99', 'msg'=>'Invalid/Expired Token', 'user'=> null];
		
		header('Content-Type: application/json');
		echo json_encode($productArray);
	  } 

}

?>