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

    require APPPATH . 'third_party/REST_Controller.php';
    require APPPATH . 'third_party/Format.php';

    use Restserver\Libraries\REST_Controller;

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, PUT");

    class antrean extends REST_Controller {
        public function __construct($config = 'rest') {
            parent::__construct($config);
            $this->load->database();
            
            // Load these helper to create JWT tokens
            $this->load->helper(['jwt', 'authorization', 'url']); 
        }

    
    public function status_get()
    {
        // Get all the headers
        $headers = $this->input->request_headers();

        // Extract the token
        $user = $headers['x-username'];
        $token = $headers['x-token'];
        $decode = JWT::decode($token);

        // Use try-catch
        // JWT library throws exception if the token is not valid
        try {

			$kodepoli = $this->uri->segment('3');
            $tanggalperiksa = $this->uri->segment('4');

            $dataPoli = $this->db->query("SELECT COUNT(Jenis) as Jumlah from Antrian Where KodePoli = '$kodepoli'")->result();
            foreach ($dataPoli as $row){
                $poli = [
                    'Poli' => $row->Jumlah
                ];
            }

            // 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;
                $array = [
					'metadata' => [
						'message' => 'Username atau Password Tidak Sesuai', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(time() > $decode->exp){
                $status = parent::HTTP_UNAUTHORIZED;
                $array = [
					'metadata' => [
						'message' => "Token Sudah Expired", 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif($poli['Poli'] == 0){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Poli Tidak Ditemukan', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$tanggalperiksa) == 0){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Format Tanggal Tidak Sesuai, Format Yang Benar adalah yyyy-mm-dd.', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
 	   elseif($tanggalperiksa < date("Y-m-d")){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Tanggal Periksa Tidak Berlaku Mundur.', 
						'code' =>  201
					]
				];
                $this->response($array, $status);
                exit();
            }
            else {
                
                $this->db->where('kodepoli', $kodepoli);
                //$this->db->where('tanggalperiksa', $tanggalperiksa);
				$antri = $this->db->get('Antrian')->result();
        
                foreach($antri as $row){
                    $response = [
                        'namapoli' => $row->Jenis,
                        'totalantrean' => strval($row->No_Akhir),
                        'sisaantrean' => strval($row->No_Akhir - $row->No_Panggil),
                        'antreanpanggil' => $row->Alias . '.' . strval($row->No_Panggil),
                        'keterangan' => ""
                    ];
                }

                $status = parent::HTTP_OK;
                $array = [
					'response' => $response, 
					'metadata' => [
						'message' => 'Ok', 
						'code' => $status
					]
				];
                $this->response($array, $status);
            }

        } catch (Exception $e) {
            // Token is invalid
            // Send the unathorized access message
            $status = parent::HTTP_UNAUTHORIZED;
            $response = [
                'status' => $status,
                'metadata' => [
                    'message' => 'Unauthorized Access!', 
                    'code' => $status
                ]
            ];
            $this->response($response, $status);
        }
    }

    public function sisapeserta_get()
    {
        // Get all the headers
        $headers = $this->input->request_headers();

        // Extract the token
        $user = $headers['x-username'];
        $token = $headers['x-token'];
        $decode = JWT::decode($token);

        // Use try-catch
        // JWT library throws exception if the token is not valid
        try {

            $nomorkartu = $this->uri->segment('3');
			$kodepoli = $this->uri->segment('4');
            $tanggalperiksa = $this->uri->segment('5');

            $duplicate = $this->db->query("SELECT COUNT ([Case ID]) as Jumlah from BPJS_Antrian where kodepoli ='$kodepoli' and tanggalperiksa = '$tanggalperiksa' and nomorkartu = '$nomorkartu'")->result();
            foreach ($duplicate as $data) {
                $doubleantrian = [
                    'Jumlah' => $data->Jumlah
                ];
            }

            // 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;
                $array = [
					'metadata' => [
						'message' => 'Username atau Password Tidak Sesuai', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(time() > $decode->exp){
                $status = parent::HTTP_UNAUTHORIZED;
                $array = [
					'metadata' => [
						'message' => "Token Sudah Expired", 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif($doubleantrian['Jumlah'] == 0){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Antrean Tidak Ditemukan', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            else {
                
                $antri = $this->db->query("Select B.nomorantrean, B.namapoli, A.No_Akhir, A.No_Panggil, B.angkaantrean, 
                                            A.Alias From BPJS_Antrian B Inner Join Antrian A ON B.KodePoli=A.KodePoli 
                                            Where B.kodepoli ='$kodepoli' and tanggalperiksa = '$tanggalperiksa' and 
                                            nomorkartu = '$nomorkartu'")->result();
        
                foreach($antri as $row){
                    $response = [
                        'nomorantrean' => $row->nomorantrean,
                        'namapoli' => $row->namapoli,
                        'sisaantrean' => strval($row->angkaantrean - $row->No_Panggil),
                        'antreanpanggil' => $row->Alias . "." .  strval($row->No_Panggil),
                        'keterangan' => ""
                    ];
                }

                $status = parent::HTTP_OK;
                $array = [
					'response' => $response, 
					'metadata' => [
						'message' => 'Ok', 
						'code' => $status
					]
				];
                $this->response($array, $status);
            }

        } catch (Exception $e) {
            // Token is invalid
            // Send the unathorized access message
            $status = parent::HTTP_UNAUTHORIZED;
            $response = [
                'status' => $status,
                'metadata' => [
                    'message' => 'Unauthorized Access!', 
                    'code' => $status
                ]
            ];
            $this->response($response, $status);
        }
    }

    public function batal_put()
    {
        // Get all the headers
        $headers = $this->input->request_headers();

        // Extract the token
        $user = $headers['x-username'];
        $token = $headers['x-token'];
        $decode = JWT::decode($token);

        // Use try-catch
        // JWT library throws exception if the token is not valid
        try {

            $nomorkartu = $this->put('nomorkartu');
			$kodepoli = $this->put('kodepoli');
            $tanggalperiksa = $this->put('tanggalperiksa');

            $duplicate = $this->db->query("SELECT COUNT ([Case ID]) as Jumlah from BPJS_Antrian where kodepoli ='$kodepoli' and tanggalperiksa = '$tanggalperiksa' and nomorkartu = '$nomorkartu'")->result();
            foreach ($duplicate as $data) {
                $doubleantrian = [
                    'Jumlah' => $data->Jumlah
                ];
            }

            $antri = $this->db->query("Select B.nomorantrean, B.namapoli, A.No_Akhir, A.No_Panggil, B.angkaantrean, 
                                    A.Alias, B.keterangan From BPJS_Antrian B Inner Join Antrian A ON B.KodePoli=A.KodePoli 
                                    Where B.kodepoli ='$kodepoli' and tanggalperiksa = '$tanggalperiksa' and 
                                    nomorkartu = '$nomorkartu'")->result();

                                    foreach($antri as $row){
                                        $response = [
                                            'angkaantrean' => $row->angkaantrean,
                                            'antreanpanggil' => $row->No_Panggil,
                                            'keterangan' => $row->keterangan
                                        ];
                                    }

            // 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;
                $array = [
					'metadata' => [
						'message' => 'Username atau Password Tidak Sesuai', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(time() > $decode->exp){
                $status = parent::HTTP_UNAUTHORIZED;
                $array = [
					'metadata' => [
						'message' => "Token Sudah Expired", 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif($doubleantrian['Jumlah'] == 0){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Antrean Tidak Ditemukan', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif($response['angkaantrean'] < $response['antreanpanggil']){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Antrean Sudah Dipanggil. Tidak Dapat Dibatalkan', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif($response['keterangan'] == 'batal'){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Antrean sudah dibatalkan sebelumnya.', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            else {
                $data = array(
                    'keterangan' => 'batal'
                );

                $this->db->where('nomorkartu', $nomorkartu);
                $this->db->where('kodepoli', $kodepoli);
                $this->db->where('tanggalperiksa', $tanggalperiksa);
				$antri = $this->db->update('BPJS_Antrian', $data);
        
                if ($antri) {
                $status = parent::HTTP_OK;
                $array = [
					'response' => $antri, 
					'metadata' => [
						'message' => 'Ok', 
						'code' => $status
					]
				];
                $this->response($array, $status);
                }
            }

        } catch (Exception $e) {
            // Token is invalid
            // Send the unathorized access message
            $status = parent::HTTP_UNAUTHORIZED;
            $response = [
                'status' => $status,
                'metadata' => [
                    'message' => 'Unauthorized Access!', 
                    'code' => $status
                ]
            ];
            $this->response($response, $status);
        }
    }

    public function index_post()
    {
        // Get all the headers
        $headers = $this->input->request_headers();

        // Extract the token
        $user = $headers['x-username'];
        $token = $headers['x-token'];
        $decode = JWT::decode($token);
        // Use try-catch
        // JWT library throws exception if the token is not valid
        try {

			$nomorkartu = $this->post('nomorkartu');
			$nik = $this->post('nik');
			$kodepoli = $this->post('kodepoli');
            $tanggalperiksa = $this->post('tanggalperiksa');
            $userID = $user;
            
            $duplicate = $this->db->query("SELECT COUNT ([Case ID]) as Jumlah from BPJS_Antrian where kodepoli ='$kodepoli' and tanggalperiksa = '$tanggalperiksa' and nomorkartu = '$nomorkartu'")->result();
            foreach ($duplicate as $data) {
                $doubleantrian = [
                    'Jumlah' => $data->Jumlah
                ];
            }

            $time = date("H:i:s");
            $this->db->select('Jam_Awal, Jam_Akhir');
	    $this->db->where('KodePoli', $kodepoli);
	    $jam = $this->db->get('Antrian')->result();
            foreach ($jam as $data) {
				$jamlayanan = [
					'Awal' => $data->Jam_Awal,
					'Akhir' => $data->Jam_Akhir
				];
            }

            $patient = $this->db->query("SELECT COUNT(PatientCode) as Jumlah from Patient Where EmployeeID = '$nomorkartu'")->result();
            foreach ($patient as $row){
                $dataPatient = [
                    'Pasien' => $row->Jumlah
                ];
            }
            
            // 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;
                $array = [
					'metadata' => [
						'message' => 'Username atau Password Tidak Sesuai', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(time() > $decode->exp){
                $status = parent::HTTP_UNAUTHORIZED;
                $array = [
					'metadata' => [
						'message' => "Token Sudah Expired", 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(empty($nomorkartu)){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Nomor Kartu Tidak Boleh Kosong.', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(empty($nik)){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'NIK Tidak Boleh Kosong.', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(empty($kodepoli)){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Kode Poli Tidak Boleh Kosong.', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(empty($tanggalperiksa)){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Tanggal Tidak Boleh Kosong.', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(is_int($nomorkartu) or strlen((string)$nomorkartu)!= 13) {
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Format Nomor Kartu Tidak Sesuai.', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(is_int($nik) or strlen((string)$nik)!= 16) {
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Format NIK Tidak Sesuai.', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif($tanggalperiksa < date("Y-m-d")){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Tanggal Periksa Tidak Berlaku Mundur.', 
						'code' =>  201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$tanggalperiksa) == 0){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Format Tanggal Tidak Sesuai, Format Yang Benar adalah yyyy-mm-dd.', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif($doubleantrian['Jumlah'] > 0){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Nomor Antrean Hanya Dapat Diambil 1 Kali Pada Tanggal dan Poli Yang Sama', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif($time < $jamlayanan['Awal'] || $time > $jamlayanan['Akhir']){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => "Maaf Jam Pelayanan Poli ini adalah $jamlayanan[Awal] sampai $jamlayanan[Akhir]", 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
             elseif($dataPatient['Pasien'] == 0){
                $status = parent::HTTP_BAD_REQUEST;
                $array = [
					'metadata' => [
						'message' => 'Data pasien ini tidak ditemukan, silahkan Melakukan Pendaftaran ke Klinik Langsung', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            else {
                $result = $this->db->query("Exec BPJS_GetAntrian '$nomorkartu', '$nik', '$kodepoli', '$tanggalperiksa', '$userID'");
			    if (!$result) {
				    $sp = FALSE;
			    }
			    else
			    {
				    $sp = TRUE;
                };

                $this->db->where('kodepoli', $kodepoli);
                $this->db->where('tanggalperiksa', $tanggalperiksa);
                $this->db->where('nomorkartu', $nomorkartu);
				$antri = $this->db->get('BPJS_Antrian')->result();
        
                foreach($antri as $row){
                    $response = [
                        'nomorantrean' => $row->nomorantrean,
                        'angkaantrean' => strval($row->angkaantrean),
                        'namapoli' => $row->namapoli,
                        'sisaantrean' => strval($row->sisaantrean),
                        'antreanpanggil' => $row->antreanpanggil,
                        'keterangan' => $row->keterangan
                    ];
                }

                $status = parent::HTTP_OK;
                $array = [
					'response' => $response, 
					'metadata' => [
						'message' => 'Ok', 
						'code' => $status
					]
				];
                $this->response($array, $status);
            }
        } catch (Exception $e) {
            // Token is invalid
            // Send the unathorized access message
            $status = parent::HTTP_UNAUTHORIZED;
            $response = [
				'status' => $status,
				'metadata' => [
					'message' => 'Unauthorized Access!', 
					'code' => $status
				]
			];
            $this->response($response, $status);
        }
        
    }

	
	public function pasienBaru_post()
    {
        // Get all the headers
        $headers = $this->input->request_headers();

        // Extract the token
   		if(isset($headers['x-token'])){
            $token = $headers['x-token'];
            $user = $headers['x-username'];
        }else{
            $token = $headers['X-Token'];
            $user = $headers['X-Username'];
        }
        $decode = JWT::decode($token);

        // Use try-catch
        // JWT library throws exception if the token is not valid
        try {

            $nomorkartu = $this->put('nomorkartu');
			$kodepoli = $this->put('kodepoli');
            $tanggalperiksa = $this->put('tanggalperiksa');
			
			$this->CreateLogFile('nomor kartu '.$nomorkartu.' - '.'kodepoli '.$kodepoli . ' - tanggal : '.$tanggalperiksa.' |X| '. json_encode($headers) ,__FUNCTION__);
			
			// 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;
                $array = [
					'metadata' => [
						'message' => 'Username atau Password Tidak Sesuai', 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }
            elseif(time() > $decode->exp){
                $status = parent::HTTP_UNAUTHORIZED;
                $array = [
					'metadata' => [
						'message' => "Token Sudah Expired", 
						'code' => 201
					]
				];
                $this->response($array, $status);
                exit();
            }           
            else {
               
	               
                $status = parent::HTTP_OK;
                $array = [
					'metadata' => [
						'message' => 'Ok', 
						'code' => $status
					]
				];
				$this->CreateLogFile(json_encode( $array) ,__FUNCTION__);
                $this->response($array, $status);
                
            }

        } catch (Exception $e) {
            // Token is invalid
            // Send the unathorized access message
            $status = parent::HTTP_UNAUTHORIZED;
            $response = [
                'status' => $status,
                'metadata' => [
                    'message' => 'Unauthorized Access!', 
                    'code' => $status
                ]
            ];
            $this->response($response, $status);
        }
    }
	
	

}
    /* End of file Api.php */
