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

class Pasien extends CI_Controller
{
    // CONSTRUCT
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->model('M_user');
        $this->load->model('M_Pendaftaran');
        $this->load->helper('url');

        if (!$this->session->userdata('username')) {
            redirect('login');
        }
    }

    public function pasien()
    {
        // ---------------------------------------------------------------------
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        // ---------------------------------------------------------------------
        $data['suku'] = $this->M_Pendaftaran->suku()->result_array();
        $data['religi'] = $this->M_Pendaftaran->religi()->result_array();
        $data['edu'] = $this->M_Pendaftaran->edu()->result_array();
        $data['prof'] = $this->M_Pendaftaran->prof()->result_array();
        $data['tipe'] = $this->M_Pendaftaran->tipe()->result_array();
        // $data['']
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pasien/pasien', $data);
        $this->load->view('properti/footer', $data);
    }

    public function cari()
    {
        extract($_GET);
        if ($jenis == 1) {
            redirect('pasien/detailPasien/' . $pencarian);
        } else if ($jenis == 2) {
            $data['cari'] = $this->M_Pendaftaran->cariNamaDepan($pencarian)->result_array();
        } else if ($jenis == 3) {
            $data['cari'] = $this->M_Pendaftaran->cariNamaBelakang($pencarian)->result_array();
        } else if ($jenis == 4) {
            $data['cari'] = $this->M_Pendaftaran->cariTanggal($pencarian)->result_array();
        } else if ($jenis == 5) {
            $data['cari'] = $this->M_Pendaftaran->cariNik($pencarian)->result_array();
        } else if ($jenis == 6) {
            $data['cari'] = $this->M_Pendaftaran->cariBpjs($pencarian)->result_array();
        }
        // ---------------------------------------------------------------------
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        // ---------------------------------------------------------------------
        // =================================================================================== 
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pasien/listpasien', $data);
        $this->load->view('properti/footer', $data);
    }

    public function CariDaftar()
    {
        extract($_GET);
        // ---------------------------------------------------------------------
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        // ---------------------------------------------------------------------
        $data['mr'] = $this->M_Pendaftaran->mr($nomr)->row_array();
        $data['countMr'] = $this->M_Pendaftaran->mr($nomr)->num_rows();
        $data['company'] = $this->M_Pendaftaran->company();
        $data['perusahaan'] = $this->M_Pendaftaran->perusahaan()->result_array();
        $data['doctor'] = $this->M_Pendaftaran->doctor()->result_array();
        $data['daftarPoli'] = $this->M_Pendaftaran->daftarPoli()->result_array();
        $data['perujuk'] = $this->M_Pendaftaran->daftarPerujuk()->result_array();
        // =================================================================================== 

        $datapasien = $this->db->query("SELECT * FROM Patient WHERE PatientCode = '$nomr' ")->row_array();
        $nokartu = $datapasien['EmployeeID'];
        //====================================================================================
        
        $datapeserta = $this->M_Pendaftaran->datapeserta($nokartu);
        $data['getpeserta'] = $datapeserta['response'];
        $data['cekpeserta'] = $datapeserta['metaData']['code'];
        $data['messagepeserta'] = $datapeserta['metaData']['message'];
        // =================================================================================== 
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pendaftaran/pendaftaran', $data);
        $this->load->view('properti/footer', $data);
    }


    public function detailPasien($id)
    {
        // ---------------------------------------------------------------------
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        // ---------------------------------------------------------------------
        // =================================================================================== 
        $data['detail'] = $this->M_Pendaftaran->detail($id)->row_array();
        // =================================================================================== 
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pasien/detailPasien', $data);
        $this->load->view('properti/footer', $data);
    }

    public function hapusPasien($id)
    {
        $this->db->query("
            DELETE FROM Patient WHERE PatientCode = '$id'
        ");
        $this->session->set_flashdata("success", "Ok !");
        redirect('pasien/pasien');
    }

    public function cancel()
    {
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        //===================================================================
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pasien/cancel', $data);
        $this->load->view('properti/footer', $data);
    }

    public function cancelaction()
    {
        $case_id = $this->input->post('case_id');
        $note = $this->input->post('note');
        $del_sep = $this->input->post('hapus_sep');

        $cekViewCharge = $this->db->query("SELECT * FROM VTotalCharge WHERE [Case ID] = '$case_id'")->num_rows();
        if ($cekViewCharge > 0) {
            $this->session->set_flashdata("error", "Oppss !!! Case ID ini sudah ada transaksi, hapus terlebih dahulu transaksi sebelum anda membatalkan kunjungan !");
            redirect($_SERVER['HTTP_REFERER']);
        } else {

            $status = $this->cancelpatient($case_id, $note);
            if ($del_sep == 1)
                $this->deletesep($case_id);

            if ($status) {
                $this->session->set_flashdata('message', '<div class="alert alert-warning" role="alert"> Cancel Berhasil.</div>');
                redirect($_SERVER['HTTP_REFERER']);
            } else {
                echo 'Cancel Gagal!';
            }
        }
    }

    private function cancelpatient($case_id, $note)
    {
        $status = $this->db->query(
            "UPDATE Cases SET
            [Case Status] = 'CANCEL',
            Note='$note' WHERE [Case ID] = '$case_id'"
        );
        
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $intakeTime = date('H:i');
         // INSERT TLOG
         if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $user = $this->session->userdata('username');
        $this->db->query("INSERT INTO TLOG (sKey,sTableName,sAction,dDate,sTime,sUser,sCompName) VALUES ('$case_id','Cases','CANCEL','$tgl','$intakeTime','web-$user','$hostname')");
        return $status;
    }

    private function deletesep($case_id)
    {
        $status = $this->db->query(
            "UPDATE Cases SET
            NoSEP = NULL
            WHERE [Case ID] = '$case_id'"
        );
        return $status;
    }

    public function searchpatient()
    {
        $case_id = $this->input->get('case_id');
        $pasien = $this->db->query(
            "SELECT * FROM Cases WHERE [Case ID]='$case_id'"
        )->row_array();
        echo json_encode($pasien);
        exit(0);
    }

    public function editIdentitas($id)
    {
        extract($_GET);
        // ---------------------------------------------------------------------
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        // ===================================================================================
        $data['pasien'] = $this->M_Pendaftaran->pasien($id)->row_array();
        $data['suku'] = $this->M_Pendaftaran->suku()->result_array();
        $data['religi'] = $this->M_Pendaftaran->religi()->result_array();
        $data['bahasa'] = $this->M_Pendaftaran->bahasa()->result_array();
        $data['edu'] = $this->M_Pendaftaran->edu()->result_array();
        $data['prof'] = $this->M_Pendaftaran->prof()->result_array();
        $data['tipe'] = $this->M_Pendaftaran->tipe()->result_array();

        $datapasien = $this->db->query("SELECT * FROM Patient WHERE PatientCode = '$id' ")->row_array();
        $nokartu = $datapasien['EmployeeID'];
        //====================================================================================
        
        $datapeserta = $this->M_Pendaftaran->datapeserta($nokartu);
        $data['getpeserta'] = $datapeserta['response'];
        $data['cekpeserta'] = $datapeserta['metaData']['code'];
        $data['messagepeserta'] = $datapeserta['metaData']['message'];

        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pendaftaran/editIdentitas', $data);
        $this->load->view('properti/footer', $data);
    }

    public function updateIdentitas($id)
    {
        $NIK = $this->input->post('NIK');
        $FirstName = $this->input->post('FirstName');
        $DOBPlace = $this->input->post('DOBPlace');
        $Nationality = $this->input->post('Nationality');
        $Religion = $this->input->post('Religion');
        $Education = $this->input->post('Education');
        $PatientType = $this->input->post('PatientType');
        $Bahasa = $this->input->post('Bahasa');
        $Sex = $this->input->post('Sex');
        $LastName = $this->input->post('LastName');
        $DOB = $this->input->post('DOB');
        $SukuBangsa = $this->input->post('SukuBangsa');
        $Status = $this->input->post('Status');
        $Profession = $this->input->post('Profession');
        $EmployeeID = $this->input->post('EmployeeID');
        $Password = $this->input->post('Password');
        $isOnline = $this->input->post('isOnline');

        $this->db->query("
            UPDATE Patient SET
            NIK = '$NIK',
            FirstName = '$FirstName',
            DOBPlace = '$DOBPlace',
            Nationality = '$Nationality',
            Religion = '$Religion',
            Education = '$Education',
            PatientType = '$PatientType',
            Bahasa = '$Bahasa',
            Sex = '$Sex',
            LastName = '$LastName',
            DOB = '$DOB',
            SukuBangsa = '$SukuBangsa',
            Status = '$Status',
            Profession = '$Profession',
            EmployeeID = '$EmployeeID',
            Password = '$Password',
            isOnline = '$isOnline'
            WHERE PatientCode = '$id'
        ");
        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Berhasil.</div>');
        redirect('pasien/detailPasien/' . $id);
    }

    public function editAsuransi($id)
    {
        extract($_GET);
        // ---------------------------------------------------------------------
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        // ---------------------------------------------------------------------
        
        // ===================================================================================
        $data['pasien'] = $this->M_Pendaftaran->pasien($id)->row_array();
        $data['asuransi'] = $this->M_Pendaftaran->asuransi()->result_array();
        $data['perusahaan'] = $this->M_Pendaftaran->perusahaan()->result_array();
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pasien/editAsuransi', $data);
        $this->load->view('properti/footer', $data);
    }

    public function updateAsuransi($id)
    {
        $CompanyCode = $this->input->post('CompanyCode');
        $perusahaan = $this->input->post('perusahaan');
        $CellPhone = $this->input->post('CellPhone');
        $this->db->query("
            UPDATE Patient SET
            CompanyCode = '$CompanyCode',
            [NAMA PERUSAHAAN] = '$perusahaan',
            CellPhone = '$CellPhone'
            WHERE PatientCode = '$id'
        ");
        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Berhasil.</div>');
        redirect('pasien/detailPasien/' . $id);
    }


    public function formsimpan()
    {
        date_default_timezone_set("Asia/Jakarta");
        $FirstName = $this->input->post('FirstName');
        $DOBPlace = $this->input->post('DOBPlace');
        $alamat = $this->input->post('alamat');
        $telpon = $this->input->post('telpon');
        $Sex = $this->input->post('Sex');
        $Company = $this->input->post('Company');
        $tujuan = $this->input->post('tujuan');
        $dokter = $this->input->post('dokter');
        $intakeTime = date('H:i');
        $tgl = date('Y-m-d');
        $tglCreate = date('Y-m-d H:i:s');

        $patientStatus = $this->db->get_where('Company', ['CompanyCode' => $Company])->row_array();
        $statusPatient = $patientStatus['Group'];

        // $jumlahCases = $this->db->get_where('Cases', ['CompanyCode' => $Company])->num_rows();
        // if ($jumlahCases > 1) {
        //     $RegStatus = "OLD";
        // } else {
        //     $RegStatus = "NEW";
        // }

        //CASE ID BARU
        $RegStatus = "NEW-NOMR";
        $getCase = $this->db->query("SELECT * FROM SystemNo WHERE SystemName = 'Case'")->row_array();
        $dbInit = $this->db->query("SELECT TOP 1 * FROM Utama")->row_array();
        if ($dbInit['Initial'] == "KALIDERES") {
            $case = $getCase['NoNumeric'];
            $cases = $getCase['NoNumeric'] + 1;
        } else {
            $cases = $getCase['NoNumeric'] + 1;
          //$prefix = $getCase['Prefix'];
            $case = $cases;
        }

        $this->db->query("UPDATE SystemNo SET NoNumeric = '$cases' WHERE SystemName = 'Case'");

        //Insert Cases
        $this->db->query("INSERT INTO Cases ([Case ID], [Description], [Category], [Case Status], [Intake Date], [Intake Time], Class, CompanyCode, [Patient Status], DateCreated, RegStatus, DoctIncharge, CaseDetail) 
        VALUES ('$case', '$FirstName', 'OP', 'OPEN', '$tgl', '$intakeTime', 'OP', '$Company','$statusPatient','$tglCreate', '$RegStatus', '$dokter', '0')");

        //Insert CaseAdmin
        $this->db->query("INSERT INTO CaseAdmin ([Case ID], Unit, [DoctorID]) VALUES ('$case', '$tujuan', '$dokter')");

        //Insert NonPatient
        $this->db->query("INSERT INTO NonPatient ([Case ID], Address1, Sex, Age, HP) VALUES ('$case', '$alamat', '$Sex', '$DOBPlace', '$telpon')");

        $this->session->set_flashdata("success", "Oke Data Tersimpan !");
        redirect('pasien/pasien');
    }

    public function viewnomr()
    {
        // ---------------------------------------------------------------------
        $data['judul'] = 'Klinik Abdul Radjak sudirman';
        // ---------------------------------------------------------------------
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['datapasien'] = $this->M_Pendaftaran->viewnomr()->result_array();
        // $data['']
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pasien/viewnomr', $data);
        $this->load->view('properti/footer', $data);
    }

    public function editPenjaminCase($id)
    {
        // ---------------------------------------------------------------------
        $data['judul'] = 'Klinik Abdul Radjak';
        // ---------------------------------------------------------------------
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['datapasien'] = $this->M_Pendaftaran->viewnomr()->result_array();
        // ===================================================================================
        $data['company'] = $this->M_Pendaftaran->company();
        $data['id'] = $this->db->query("SELECT [Case ID], [Description], CompanyCode FROM Cases WHERE [Case ID] = '$id'")->row_array();
        // ===================================================================================
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pasien/editPenjaminCase', $data);
        $this->load->view('properti/footer', $data);
    }

    public function updatePenjamin($id)
    {
        $company = $this->input->post('company');
        $this->db->query("UPDATE Cases SET CompanyCode = '$company' WHERE [Case ID] = '$id'");
        $this->session->set_flashdata("success", "Ok!");
        redirect('pendaftaran/detailCaseUmum?case=' . $id);
    }

}

?>
