<?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 Signup 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');
        $this->load->model('Patientmodel');
    }
    
    public function userRegistration_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_countryid,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 t1.*,t2.country as countryname from ecom_doctors t1,currency t2 where t1.doctor_countryid=t2.id and t1.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 Login_post()
	{

	    // Extract user data from POST request
	    $username = $this->post('mobile');
	    $password = $this->post('password');
	    $pushtoken = $this->post('pushtoken');
        $sql = "SELECT t1.*,t2.country as countryname from ecom_doctors t1,currency t2 where t1.doctor_countryid=t2.id and t1.doctor_mobile='".$username."' and t1.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 UpdateProfile_post()
    {

            $inputData['UserId'] = $this->input->post('UserId', TRUE);
            $inputData['FName'] = $this->input->post('FName', TRUE);
            $inputData['LName'] = $this->input->post('LName', TRUE);
            $inputData['Email'] = $this->input->post('Email', TRUE);
            $inputData['ProfilePic'] = $this->input->post('ProfilePic', TRUE);
            $inputData['Country'] = $this->input->post('Country', TRUE);
            $inputData['City'] = $this->input->post('City', TRUE);
            
            $inputData['UserId'] = $this->post('UserId');
            $inputData['FName'] = $this->post('FName');
            $inputData['LName'] = $this->post('LName');
            $inputData['Email'] = $this->post('Email');
            $inputData['ProfilePic'] =$this->post('ProfilePic');
            $inputData['Country'] = $this->post('Country');
            $inputData['City'] = $this->post('City');
            
  
            
            if (!empty($inputData['UserId'])) {
                if ($inputData['ProfilePic']) {
                    $finalImage = base64_decode($inputData['ProfilePic']);
                    $uploadFolder = "upload/profilepic/";
                    if (!is_dir($uploadFolder)) {
                        mkdir($uploadFolder);
                        chmod($uploadFolder, 777);
                    }
                    $finalImageName = $inputData['FName'] . "_profile_pic_" . time() . ".png";
                    file_put_contents($uploadFolder . "/" . $finalImageName, $finalImage);

                    $imgData['ProfilePic'] = base_url() . 'upload/profilepic/' . $finalImageName;

                    $inputData['ProfilePic'] = $imgData['ProfilePic'];
                    $qry="update ecom_doctors set profile_image='".$inputData['ProfilePic']."',doctor_fname='".$inputData['FName']."',doctor_lname='".$inputData['LName']."',doctor_email='".$inputData['Email']."',doctor_countryid='".$inputData['Country']."',doctor_city='".$inputData['City']."' where doctor_id=".$inputData['UserId'];
	                $query=$this->db->query($qry);
                } else {
                    $inputData['ProfilePic'] = '';
                    $qry="update ecom_doctors set doctor_fname='".$inputData['FName']."',doctor_lname='".$inputData['LName']."',doctor_email='".$inputData['Email']."',doctor_countryid='".$inputData['Country']."',doctor_city='".$inputData['City']."' where doctor_id=".$inputData['UserId'];
	                $query=$this->db->query($qry);
                }
                
                $result['Success'] = "True";
                $result['Message'] = "Update Successfully!";
                $result['Result'] = $data;
                die(json_encode($result));
                
            } else {
                echo json_encode(array('Success' => "FALSE", 'Message' => 'wrong key', 'Result' => array()));
                exit;
            }

    }

    public function ForgotPassword()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['Mobile'] = $this->input->post('MobileNo', TRUE);

            $input_data = json_decode($json, TRUE);
            if (!$inputData['Mobile'] && isset($input_data['MobileNo'])) {
                $inputData['Mobile'] = $input_data['MobileNo'];
            }

            if (!empty($inputData['Mobile'])) {
                if ($checkMobileExist = $this->Signupmodel->checkMobileExist($inputData)) {
                    $inputData['Otp'] = rand(100000, 999999);
                    $inputData['Otp'] = 123456;
                    $arr = array(
                        'otp' => $inputData['Otp'],
                    );
                    $this->Signupmodel->UpdateDoctor($arr, $checkMobileExist->doctor_id);
                    $result['Success'] = "True";
                    $result['Message'] = "Otp sent successfully!";
                    $result['Result'] = $checkMobileExist;

                    $mobileNo = $inputData['Mobile'];
                    $msg = 'Hi your forgot password OTP : ' . $inputData['Otp'];
                    $smsText = str_replace(" ", "%20", $msg);
                    sendSMS($mobileNo, $smsText);
                    die(json_encode($result));
                } else {
                    $result['Success'] = "FALSE";
                    $result['Message'] = "Record not found try again!";
                    die(json_encode($result));
                }
            } else {
                echo json_encode(array('Success' => "FALSE", 'Message' => 'wrong key', 'Result' => array()));
                exit;
            }
        } else {
            echo json_encode(array('Success' => "FALSE", 'Message' => 'Incorrect parameters', 'Result' => array()));
            exit;
        }
    }

    public function ResetPassword()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['Mobile'] = $this->input->post('MobileNo', TRUE);
            $inputData['Password'] = $this->input->post('Password', TRUE);

            $input_data = json_decode($json, TRUE);
            if (!$inputData['Mobile'] && isset($input_data['MobileNo'])) {
                $inputData['Mobile'] = $input_data['MobileNo'];
            }
            if (!$inputData['Password'] && isset($input_data['Password'])) {
                $inputData['Password'] = $input_data['Password'];
            }

            if (!empty($inputData['Mobile'] && !empty($inputData['Password']))) {
                if ($checkMobileExist = $this->Signupmodel->checkMobileExist($inputData)) {
                    $arr = array(
                        'doctor_password' => md5($inputData['Password']),
                    );
                    $this->Signupmodel->UpdateDoctor($arr, $checkMobileExist->doctor_id);
                    $result['Success'] = "True";
                    $result['Message'] = "Your password updated successfully!";
                    $result['Result'] = $checkMobileExist;
                    die(json_encode($result));
                } else {
                    $result['Success'] = "FALSE";
                    $result['Message'] = "Record not found try again!";
                    die(json_encode($result));
                }
            } else {
                echo json_encode(array('Success' => "FALSE", 'Message' => 'wrong key', 'Result' => array()));
                exit;
            }
        } else {
            echo json_encode(array('Success' => "FALSE", 'Message' => 'Incorrect parameters', 'Result' => array()));
            exit;
        }
    }

    public function Help()
    {
        $json = trim(file_get_contents('php://input'));
        if (!empty($json)) {
            $inputData['UserId'] = $this->input->post('UserId', TRUE);
            $inputData['Question'] = $this->input->post('Question', TRUE);
            $inputData['Rating'] = $this->input->post('Rating', TRUE);
            $inputData['Comment'] = $this->input->post('Comment', TRUE);
            $input_data = json_decode($json, TRUE);
            if (!$inputData['UserId'] && isset($input_data['UserId'])) {
                $inputData['UserId'] = $input_data['UserId'];
            }
            if (!$inputData['Question'] && isset($input_data['Question'])) {
                $inputData['Question'] = $input_data['Question'];
            }
            if (!$inputData['Rating'] && isset($input_data['Rating'])) {
                $inputData['Rating'] = $input_data['Rating'];
            }
            if (!$inputData['Comment'] && isset($input_data['Comment'])) {
                $inputData['Comment'] = $input_data['Comment'];
            }

            // print_r($inputData);die;
            if (!empty($inputData['UserId'])) {
                $userTable = [
                    'doctor_id' => $inputData['UserId'],
                    'doc_question' => $inputData['Question'],
                    'doc_rating' => $inputData['Rating'],
                    'doc_comment' => $inputData['Comment'],
                ];
                $res = $this->Signupmodel->submitDoctorHelp($userTable);
                if ($res) {

                    $result['Success'] = "TRUE";
                    $result['Message'] = 'Submitted successfully.';
                    $result['Result'] = $res;
                    die(json_encode($result));
                } else {
                    $result['Success'] = "False";
                    $result['Message'] = 'Failed to submit try again!';
                    die(json_encode($result));
                }
            } else {

                $result['Success'] = "False";
                $result['Message'] = 'Invalid given request!';
                die(json_encode($result));
            }
        } else {

            $result['Success'] = "False";
            $result['Message'] = 'Invalid request!';
            die(json_encode($result));
        }
    }
	
	public function getCountries_post()
    {

                $qry="select * from currency order by country";
	            $query=$this->db->query($qry);
	            $coun=$query->result_array();

                $result['Success'] = "True";
                $result['countries'] = $coun;
                die(json_encode($result));


    }
    
}