<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*------------------------------------------------------*/
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
 
	if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: POST, POST, OPTIONS");         
 
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
 
    exit(0);
}
/* -----------------------------------------------------*/

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
 
	if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, GET, OPTIONS");         
 
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); 
 
    exit(0);
} 
/* -----------------------------------------------------*/ 
require APPPATH . 'perutions/REST_Controller.php';
require APPPATH . 'perutions/Format.php';
use Restserver\Libraries\REST_Controller;
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
class Api extends REST_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->library('phppass/passwordhash');
        
        // Load these helper to create JWT tokens
        $this->load->helper(['jwt', 'authorization']);    
        $this->load->library('email');
    }

    private function verify_request()
	{
	    // Get all the headers
	    $headers = $this->input->request_headers();
	    // Extract the token
	    $token = $headers['Authorization'];
	    // Use try-catch
	    // JWT library throws exception if the token is not valid
	    try {
	        // Validate the token
	        // Successfull validation will return the decoded user data else returns false
	        $data = AUTHORIZATION::validateToken($token);
	        if ($data === false) {
	            $status = parent::HTTP_UNAUTHORIZED;
	            $response = ['status' => $status, 'msg' => 'Unauthorized Access!'];
	            $this->response($response, $status);
	            exit();
	        } else {
	            return $data;
	        }
	    } catch (Exception $e) {
	        // Token is invalid
	        // Send the unathorized access message
	        $status = parent::HTTP_UNAUTHORIZED;
	        $response = ['status' => $status, 'msg' => 'Unauthorized Access! '];
	        $this->response($response, $status);
	    }
	}
    
    public function hello_get()
    {
        $tokenData = 'Hello World!';
        
        // Create a token
        $token = AUTHORIZATION::generateToken($tokenData);
        // Set HTTP status code
        $status = parent::HTTP_OK;
        // Prepare the response
        $response = ['status' => $status, 'token' => $token];
        // REST_Controller provide this method to send responses
        $this->response($response, $status);
    }

    public function get_get() {
        $status = parent::HTTP_OK;
        $response = ['status' => $status, 'login' => '2'];
        $this->response($response, $status);
    }
    
    
    public function generatetoken_post()
	{
	   $id=$this->post('id'); // Get device id
       $userid= $this->post('userid');
        if($userid){
            $sql = "SELECT * from account where userid=".$userid;
            $query = $this->db->query($sql);
            $count = $query->result_array();
             
            if($count){
                  foreach($count as $row) {
                      $accountid=$row['id'];
                      $token=$row['token'];
                  }
    
            } else {
                  $qry="insert into account(userid,deviceid) values(".$userid.",'".$id."')";
                  $query = $this->db->query($qry);
                  $insert_id = $this->db->insert_id();
    
                  $token = AUTHORIZATION::generateToken($insert_id);
                  $qryt= "update account set token='".$token."' where id=".$insert_id;
                  $query=$this->db->query($qryt);
    
            } 
    
        } else {
    
            $sql = "SELECT * from account where deviceid='".$id."'";
            $query = $this->db->query($sql);
            $count = $query->result_array();
             
            if($count){
    
                foreach($count as $row) {
                    $accountid=$row['id'];
                    $token=$row['token'];
                }              
    
            } else {
    
                $qry="insert into account(userid,deviceid) values('','".$id."')";
                $query = $this->db->query($qry);
                $insert_id = $this->db->insert_id();
    
                $token = AUTHORIZATION::generateToken($insert_id);
                $qryt= "update account set token='".$token."' where id=".$insert_id;
            
                $query=$this->db->query($qryt);
    
            }
        }
        
        $status = parent::HTTP_OK;
        $response = ['status' => $status,'token' => $token, $userid='', 'msg' => 'Token generated'];
        $this->response($response, $status); 
    	}
    	
	/*Staff Api*/

	
	public function staffstatus_post()
	{

	    // Extract user data from POST request
	    $userid = $this->post('userid');
        $sql = "SELECT * from staff where id='".$userid."' and status>-1";
        $query = $this->db->query($sql);
        $user = $query->result_array();
        if($user) {
            $nstatus="1";
        } else {
            $nstatus="-1";
        }
        
        $status = parent::HTTP_OK ;
        $response = ['status' => $status, 'login' => $nstatus];
        $this->response($response, $status); 
	}

	 public function signin12_post()
	{

	    // Extract user data from POST request
	    $username = $this->post('mobile');
	    $password = $this->post('password');
	    $pushtoken = $this->post('pushtoken');
        $sql = "SELECT * from ecom_doctors where doctor_mobile='".$username."' and doctor_password='".$password."'";
        $query = $this->db->query($sql);
        $user = $query->result_array();
        if($user) {
            foreach($user as $row) {
                $userid=$row['id_user'];
            }
            
            // Create a token from the user data and send it as reponse
    		$token = AUTHORIZATION::generateToken(['id' => $userid]);
    		// Prepare the response
    		
    		$status = parent::HTTP_OK;
    		$response = ['httpstatus' => $status, 'status' => 'success' ,'token' => $token, 'data' => $user];
    		$this->response($response, $status);

        } else {
        	$status = parent::HTTP_OK ;
	        $response = ['httpstatus' => $status, 'status' => 'failed', 'token' => '', 'msg' => 'Invalid mobile or password!'];
	        $this->response($response, $status);
        }


	}
		
	public function signup12_post()
	{
        // Extract user data from POST request
	    $fname = $this->post('firstname');
	    $lname = $this->post('lastname');
	    $phone = $this->post('phone');
	    $email = $this->post('email');
	    $address=$this->post('address');
	    $country = $this->post('country');
	    $city = $this->post('city');
	    $password=$this->post('password');
	    $qry="select * from ecom_doctors where doctor_mobile='".$phone."'";
	    $query=$this->db->query($qry);
	    $count=$query->result_array();
        if ($count) {
            $status = parent::HTTP_OK;
            $response = ['httpstatus' => $status, 'status' => 'failed', 'msg' => 'Health Worker with this mobile already exists'];
    		$this->response($response, $status);
        } 
        $qry="select * from ecom_doctors where doctor_email='".$email."'";
	    $query=$this->db->query($qry);
	    $count=$query->result_array();
        if ($count) {
            $status = parent::HTTP_OK;
            $response = ['httpstatus' => $status, 'status' => 'failed', 'msg' => 'Health Worker with this email already exists'];
    		$this->response($response, $status);
        } 
        //$input = ['doctor_fname'=>$name, 'doctor_mobile'=>$phone, 'doctor_email'=>$email, 'doctor_city'=>$country,'doctor_city'=>$city,'password'=>$password, 'status'=> '1'];
        //$this->db->insert('ecom_doctor', $input);
        
        $qry="insert into ecom_doctors(doctor_fname,doctor_lname,doctor_mobile,doctor_email,doctor_country,doctor_city,doctor_password,status) values('".$fname."','".$lname."','".$phone."','".$email."','".$country."','".$city."','".$password."',1)";
	    $query=$this->db->query($qry);
        $insertId = $this->db->insert_id();
        if($insertId>0) {
            $qry="select * from ecom_doctors where doctor_id='".$insertId."'";
    	    $query=$this->db->query($qry);
    	    $data=$query->result_array();
            
            $token = AUTHORIZATION::generateToken(['id' => $insertId]);
            
            $status = parent::HTTP_OK;
    		$response = ['httpstatus' => $status, 'status' => 'success', 'msg' => "Thank you for Registration", 'token' => $token, 'data' => $data];
    		$this->response($response, $status);
        } else {
            $status = parent::HTTP_OK;
            $response = ['httpstatus' => $status, 'status' => 'failed', 'msg' => 'Something went wrong with the registration. Please try again.'];
    		$this->response($response, $status);
        }

	}
	
	public function addpatient11_post() {
	    
	    $doctor=$this->post('doctorid');
	    $name=$this->post('name');
	    $mobile=$this->post('mobile');
	    $alternativenumber=$this->post('alternativenumber');
	    $dob=$this->post('dob');
	    $age=$this->post('age');
	    $gender=$this->post('gender');
	    $maritalstatus=$this->post('maritalstatus');
	    $occupation=$this->post('occupation');
	    $address=$this->post('address');
	    $city=$this->post('city');
	    
	    $sql="insert into ecom_patients(doctor_id,patient_name,patient_mobile,alternative_number,patient_dob,patient_age,gender,marital_status,occupation,patient_address,patient_city) values(".$doctor.",'".$name."','".$mobile."','".$alternativenumber."','".$dob."','".$age."','".$gender."','".$maritalstatus."','".$occupation."','".$address."','".$city."')";
	    $query=$this->db->query($sql);
	    
	    $insertId = $this->db->insert_id();
	    $qry="select * from ecom_patients where patient_id='".$insertId."'";
	    $query=$this->db->query($qry);
	    $data=$query->result_array();
	    
	    $status = parent::HTTP_OK;
        $response = ['httpstatus' => $status, 'status' => 'Success', 'msg' => 'Patient registered Successfully', 'data' => $data];
        $this->response($response, $status);
	}
     
    public function editpatient11_post()
	{
	    $doctor=$this->post('doctorid');
	    $name=$this->post('name');
	    $mobile=$this->post('mobile');
	    $alternativenumber=$this->post('alternativenumber');
	    $dob=$this->post('dob');
	    $age=$this->post('age');
	    $gender=$this->post('gender');
	    $maritalstatus=$this->post('maritalstatus');
	    $occupation=$this->post('occupation');
	    $address=$this->post('address');
	    $city=$this->post('city');
	    $patientid=$this->post('patientid');
        
	    $sql="update ecom_patients set patient_name='".$name."',patient_mobile='".$mobile."',alternative_number='".$alternativenumber."',patient_dob='".$dob."',patient_age='".$age."',gender='".$gender."',marital_status='".$maritalstatus."',occupation='".$occupation."',patient_address='".$address."',patient_city='".$city."' where patient_id='".$patientid."'";
	    $query=$this->db->query($sql);
	    
	    $status = parent::HTTP_OK;
        $response = ['httpstatus' => $status, 'status' => 'Success', 'msg' => 'Patient Updated Successfully'];
        $this->response($response, $status);
	}
	
	public function getfaqs_post()
	{
	    $qry="select * from ecom_faq";
	    $query=$this->db->query($qry);
	    $data=$query->result_array();
	    
	    $status = parent::HTTP_OK;
        $response = ['httpstatus' => $status, 'status' => 'Success', 'data' => $data];
        $this->response($response, $status);
	}
    
}


/* End of file Api.php */