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

require_once 'vendor/autoload.php';

class Wsbpjsjkn extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('data_menu');
		// Load these helper to create JWT tokens
		$this->load->helper(['jwt', 'authorization', 'toolkit']);
		$this->load->library('Libhttprequest');

		//if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
			//AUTHORIZATION::ThrowUnMethodNotAllowed('Method Not Allowed');
		//}
		//yang belum create custom error

	}

	public function Auth()
	{
	    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			AUTHORIZATION::ThrowUnMethodNotAllowed('Method Not Allowed');
		}
	    
		// Get all the headers
		$headers = $this->input->request_headers();
		$this->CreateLogFile(json_encode($headers),'AUTH');
		//print_r($headers);exit();
		
		
		if(isset($headers['x-username'])){
            $username = $headers['x-username'];
	    	$password = $headers['x-password'];
        }else{
	    	$password = $headers['X-Password'];
            $username = $headers['X-Username'];
        }

		if (empty($username) || empty($password)) {
			AUTHORIZATION::ThrowUnAuthorizedRequest('UnAuthorized');
		}

		$obj = array(
			"username" => $username,
			"password" => $password
		);
	

		$accessDb =	$this->HttpRequest($obj, 'GetAccess');
		//print_r($accessDb);exit();
		
		$accessDb = json_decode($accessDb, true);
		if (empty($accessDb)) {
			AUTHORIZATION::ThrowUnAuthorizedRequest('Username atau Password Tidak Sesuai');
		}
		$myUsername = $accessDb[0]['xUsername'];
		$myPassword = $accessDb[0]['xPassword'];

		// Check if valid user
		if ($username != $myUsername && $password != $myPassword) {
			AUTHORIZATION::ThrowUnAuthorizedRequest('Username atau Password Tidak Sesuai');
		}

		$issuedat_claim = time();
		$notbefore_claim = $issuedat_claim + 10;
		$expire_claim = $issuedat_claim + 3600;
		$token = array(
			"iat" => $issuedat_claim,
			"nbf" => $notbefore_claim,
			"exp" => $expire_claim,
			"data" => [
				'username' => $myUsername,
				'password' => $myPassword
			]
		);

		// Create a token from the user data and send it as reponse
		$token = AUTHORIZATION::generateToken($token);

		// sPrepare the response
		$status = AUTHORIZATION::HTTP_CODE_SUCCESS();
		$response = [
			'token' => $token
		];
		$array = [
			'response' => $response,
			'metadata' => [
				'message' => 'Ok',
				'code' => $status
			]
		];
		echo json_encode($array);
		exit();
	}

	public function StatusAntrean()
	{
		try {

			//Validasi Token And Username
			AUTHORIZATION::TokenValidation();

			$json = file_get_contents('php://input');
			$obj = json_decode($json);
            $this->CreateLogFile($json ,__FUNCTION__);
			$kodePoli = 'kode poli';
			$kodeDokter = 'kode dokter';
			$tanggalPeriksa = 'tanggal periksa';
			$jamPraktek = 'jam praktek';

			//check json post object and validasi object value is null / empty
			$kodePoli = $this->GetJsonObject($obj->{$this->Replace($kodePoli)}, $kodePoli);
			$kodeDokter = $this->GetJsonObject($obj->{$this->Replace($kodeDokter)}, $kodeDokter);
			$tanggalPeriksa = $this->GetJsonObject($obj->{$this->Replace($tanggalPeriksa)}, $tanggalPeriksa);
			$jamPraktek = $this->GetJsonObject($obj->{$this->Replace($jamPraktek)}, $jamPraktek);
			
			$param = array(
    			"poli" => $kodePoli
		    );
	
	    	$checkPoli = $this->HttpRequest($param, 'GetPoli');
	    	$checkPoli = json_decode($checkPoli, true);

	    	if (empty($checkPoli)) {
				AUTHORIZATION::ThrowBadRequest('Poli Tidak Ditemukan');
			}

			if ($tanggalPeriksa < date("Y-m-d")) {
				AUTHORIZATION::ThrowBadRequest('Tanggal Periksa Tidak Berlaku Mundur.');
			}

			if (!TOOLKIT::isDateValid($tanggalPeriksa)) {
				AUTHORIZATION::ThrowBadRequest('Format Tanggal Tidak Sesuai, Format Yang Benar adalah yyyy-mm-dd.');
			}

			echo $this->HttpRequest($obj, __FUNCTION__);
			exit();
		} catch (Exception $e) {
			AUTHORIZATION::ThrowInternalServerError($e->getMessage());
		}
	}

	public function AmbilAntrean()
	{
		try {

			//Validasi Token And Username
			AUTHORIZATION::TokenValidation();

			$json = file_get_contents('php://input');
			$obj = json_decode($json);
            $this->CreateLogFile($json ,__FUNCTION__);

			

			echo $this->HttpRequest($obj, __FUNCTION__);
			exit();
		} catch (Exception $e) {
			AUTHORIZATION::ThrowInternalServerError($e->getMessage());
		}
	}

	public function SisaAntrean()
	{
		try {

			//Validasi Token And Username
			AUTHORIZATION::TokenValidation();

			$json = file_get_contents('php://input');
			$obj = json_decode($json);
            $this->CreateLogFile($json ,__FUNCTION__);
			$kodeBooking = 'kode booking';

			//check json post object and validasi object value is null / empty
			$kodeBooking = $this->GetJsonObject($obj->{$this->Replace($kodeBooking)}, $kodeBooking);
			
			$param = array(
    			"kodebooking" => $kodeBooking
		    );
		    
		    $check = $this->HttpRequest($param, 'GetKodeBooking');
	    	$check = json_decode($check, true);
		    
		    //if (empty($check)) {
			//	AUTHORIZATION::ThrowBadRequest('Antrean Tidak Ditemukan');
			//}
	
	    

			echo $this->HttpRequest($obj, __FUNCTION__);
			exit();
		} catch (Exception $e) {
			AUTHORIZATION::ThrowInternalServerError($e->getMessage());
		}
	}

	public function BatalAntrean()
	{
		try {

			//Validasi Token And Username
			AUTHORIZATION::TokenValidation();

			$json = file_get_contents('php://input');
			$obj = json_decode($json);
            $this->CreateLogFile($json ,__FUNCTION__);
			$kodeBooking = 'kode booking';
			$keterangan = 'keterangan';

			//check json post object and validasi object value is null / empty
			$kodeBooking = $this->GetJsonObject($obj->{$this->Replace($kodeBooking)}, $kodeBooking);
			$keterangan = $this->GetJsonObject($obj->{$this->Replace($keterangan)}, $keterangan);
			
			$param = array(
    			"kodebooking" => $kodeBooking
		    );
		    
		    $check = $this->HttpRequest($param, 'GetKodeBooking');
		    //print_r($check);exit();
	    	$check = json_decode($check, true);
	    	
		    
		    
		    if (empty($check)) {
				AUTHORIZATION::ThrowBadRequest('Antrean Tidak Ditemukan');
			}
			
			
			
			if ($check[0]['Panggil'] == 1 ) {
				AUTHORIZATION::ThrowBadRequest('Pasien sudah dilayani,antrean tidak dapat dibatalkan');
			}
			
			if ($check[0]['isBatal'] == 1 ) {
				AUTHORIZATION::ThrowBadRequest('Antrian pasien sudah dibatalkan');
			}
			
	

			echo $this->HttpRequest($obj, __FUNCTION__);
			exit();
		} catch (Exception $e) {
			AUTHORIZATION::ThrowInternalServerError($e->getMessage());
		}
	}

	public function CheckInAntrean()
	{
		try {

			//Validasi Token And Username
			AUTHORIZATION::TokenValidation();

			$json = file_get_contents('php://input');
			$obj = json_decode($json);
            $this->CreateLogFile($json ,__FUNCTION__);
			$kodeBooking = 'kode booking';
			$waktu = 'waktu';

			//check json post object and validasi object value is null / empty
			$kodeBooking = $this->GetJsonObject($obj->{$this->Replace($kodeBooking)}, $kodeBooking);
			$waktu = $this->GetJsonObject($obj->{$this->Replace($waktu)}, $waktu);

			echo $this->HttpRequest($obj, __FUNCTION__);
			exit();
		} catch (Exception $e) {
			AUTHORIZATION::ThrowInternalServerError($e->getMessage());
		}
	}

	public function InfoPasienBaru()
	{
		try {

			//Validasi Token And Username
			AUTHORIZATION::TokenValidation();

			$json = file_get_contents('php://input');
			$obj = json_decode($json);
            $this->CreateLogFile($json ,__FUNCTION__);
			$nomorkartu = "nomor kartu";
			$nik = "nik";
			$nomorKk = "nomor kk";
			$nama = "nama";
			$jenisKelamin = "jenis kelamin";
			$tanggalLahir = "tanggal lahir";
			$noHp = "no hp";
			$alamat = "alamat";
			$kodeProp = "kode prop";
			$namaProp = "nama prop";
			$kodeDati2 = "kodedati2";
			$namaDati2 = "nama dati2";
			$kodeKec = "kode kec";
			$namaKec = "nama kec";
			$kodeKel = "kode kel";
			$namaKel = "nama kel";
			$rw = "rw";
			$rt = "rt";

			//check json post object and validasi object value is null / empty
			$nomorkartu = $this->GetJsonObject($obj->{$this->Replace($nomorkartu)}, $nomorkartu);
			$nik = $this->GetJsonObject($obj->{$this->Replace($nik)}, $nik);
			$nomorKk = $this->GetJsonObject($obj->{$this->Replace($nomorKk)}, $nomorKk);
			$nama = $this->GetJsonObject($obj->{$this->Replace($nama)}, $nama);
			$jenisKelamin = $this->GetJsonObject($obj->{$this->Replace($jenisKelamin)}, $jenisKelamin);
			$tanggalLahir = $this->GetJsonObject($obj->{$this->Replace($tanggalLahir)}, $tanggalLahir);
			$noHp  = $this->GetJsonObject($obj->{$this->Replace($noHp)}, $noHp);
			$alamat = $this->GetJsonObject($obj->{$this->Replace($alamat)}, $alamat);
			$kodeProp = $this->GetJsonObject($obj->{$this->Replace($kodeProp)}, $kodeProp);
			$namaProp = $this->GetJsonObject($obj->{$this->Replace($namaProp)}, $namaProp);
			$kodeDati2 = $this->GetJsonObject($obj->{$this->Replace($kodeDati2)}, $kodeDati2);
			$namaDati2  = $this->GetJsonObject($obj->{$this->Replace($namaDati2)}, $namaDati2);
			$kodeKec = $this->GetJsonObject($obj->{$this->Replace($kodeKec)}, $kodeKec);
			$namaKec = $this->GetJsonObject($obj->{$this->Replace($namaKec)}, $namaKec);
			$kodeKel = $this->GetJsonObject($obj->{$this->Replace($kodeKel)}, $kodeKel);
			$namaKel = $this->GetJsonObject($obj->{$this->Replace($namaKel)}, $namaKel);
			$rw = $this->GetJsonObject($obj->{$this->Replace($rw)}, $rw);
			$rt = $this->GetJsonObject($obj->{$this->Replace($rt)}, $rt);
			
			if(strlen($nomorkartu) != 13 ){
			    AUTHORIZATION::ThrowBadRequest('Format Nomor Kartu Tidak Sesuai');
			}
			
			if(strlen($nik) != 16 ){
			    AUTHORIZATION::ThrowBadRequest('Format NIK Tidak Sesuai');
			}

			if (!TOOLKIT::isDateValid($tanggalLahir)) {
				AUTHORIZATION::ThrowBadRequest('Format Tanggal Lahir Tidak Sesuai, Format Yang Benar adalah yyyy-mm-dd.');
			}
			
			

			echo $this->HttpRequest($obj, __FUNCTION__);
			exit();
		} catch (Exception $e) {
			AUTHORIZATION::ThrowInternalServerError($e->getMessage());
		}
	}

	public function JadwalOperasiRs()
	{
		try {

			//Validasi Token And Username
			AUTHORIZATION::TokenValidation();

			$json = file_get_contents('php://input');
			$obj = json_decode($json);
            $this->CreateLogFile($json ,__FUNCTION__);
			$tanggalAwal = 'tanggal awal';
			$tanggalAkhir = 'tanggal akhir';

			//check json post object and validasi object value is null / empty
			$tanggalAwal  = $this->GetJsonObject($obj->{$this->Replace($tanggalAwal)}, $tanggalAwal);
			$tanggalAkhir  = $this->GetJsonObject($obj->{$this->Replace($tanggalAkhir)}, $tanggalAkhir);

			if (!TOOLKIT::isDateValid($tanggalAwal) || !TOOLKIT::isDateValid($tanggalAkhir)) {
				AUTHORIZATION::ThrowBadRequest('Format Tanggal Tidak Sesuai, Format Yang Benar adalah yyyy-mm-dd.');
			}

			echo $this->HttpRequest($obj, __FUNCTION__);
			exit();
		} catch (Exception $e) {
			AUTHORIZATION::ThrowInternalServerError($e->getMessage());
		}
	}

	public function JadwalOperasiPasien()
	{
		try {

			//Validasi Token And Username
			AUTHORIZATION::TokenValidation();

			$json = file_get_contents('php://input');
			$obj = json_decode($json);
            $this->CreateLogFile($json ,__FUNCTION__);
			$noPeserta = 'no peserta';
			
			

			//check json post object and validasi object value is null / empty
			$noPeserta  = $this->GetJsonObject($obj->{$this->Replace($noPeserta)}, $noPeserta);
			if(strlen($noPeserta) != 13 ){
			    AUTHORIZATION::ThrowBadRequest('Format No Peserta Kartu Tidak Sesuai');
			}
			echo $this->HttpRequest($obj, __FUNCTION__);
			exit();
		} catch (Exception $e) {
			AUTHORIZATION::ThrowInternalServerError($e->getMessage());
		}
	}


	public function HttpRequest($params, $endPoint)
	{
	    $this->Libhttprequest = new Libhttprequest();
		return $this->Libhttprequest->HitPostJson($params, $endPoint);
	}


	function GetJsonObject($obj, $objName)
	{
		$objValue = isset($obj) ? $obj : "";
		if (empty($objValue)) {
			AUTHORIZATION::ThrowBadRequest($objName . ' Belum diisi');
		}
		return $objValue;
	}

	function Replace($text)
	{
		return str_replace(' ', '', $text);
	}
	
	function CreateLogFile($json,$function)
	{
		//write log
		file_put_contents('jkn_log.txt', "*** Logs $function ***\r\n", FILE_APPEND | LOCK_EX);
		file_put_contents('jkn_log.txt', "PARAM : " . $json. "\r\n", FILE_APPEND | LOCK_EX);
		file_put_contents('jkn_log.txt', "\r\n***************************\r\n\r\n", FILE_APPEND | LOCK_EX);
		file_put_contents('jkn_log.txt', "*** " . date("Y-m-d H:i:s") . " ***\r\n", FILE_APPEND | LOCK_EX);
	}
}
