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

class Pendaftaran 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->model('M_anamnesa');
        $this->load->model('M_rekamMedis');
        $this->load->model('M_Utama');
        $this->load->model('M_BpjsID');
        $this->load->helper('url');

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


    public function index()
    {
        $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['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();
        $data['asuransi'] = $this->M_Pendaftaran->asuransi()->result_array();
        $data['perusahaan'] = $this->M_Pendaftaran->perusahaan()->result_array();
        $data['provinsi'] = $this->M_Pendaftaran->provinsi()->result_array();

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

    public function NoBpjs()
    {
        extract($_GET);
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        //==================================================================
        $getNoBpjs = $this->M_Pendaftaran->getNobpjs();
        $data['getNoBpjs'] = @$getNoBpjs['response']['list'];
        $data['countNik'] = $getNoBpjs['metaData']['code'];
        $data['messageNik'] = $getNoBpjs['metaData']['message'];
        //=================================================================
        $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();
        $data['asuransi'] = $this->M_Pendaftaran->asuransi()->result_array();
        $data['perusahaan'] = $this->M_Pendaftaran->perusahaan()->result_array();
        $data['provinsi'] = $this->M_Pendaftaran->provinsi()->result_array();

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

    public function homecity()
    {
        $a = $this->input->post('nprovinsi');
        $query = $this->db->query("SELECT * FROM City WHERE PROVINCE = '$a' ORDER BY City ASC")->result();
        echo json_encode($query);
    }
    public function kecamatan()
    {
        $a = $this->input->post('nkabupaten');
        $query = $this->db->query("SELECT * FROM Kecamatan WHERE City = '$a' ORDER BY City ASC")->result();
        echo json_encode($query);
    }
    public function kelurahan()
    {
        $a = $this->input->post('nkabupaten');
        $b = $this->input->post('nkecamatan');
        $query = $this->db->query("SELECT * FROM Kelurahan WHERE City = '$a' AND Kecamatan = '$b' ORDER BY City ASC")->result();
        echo json_encode($query);
    }

    public function simpanpasien()
    {
        $NIK = $this->input->post('NIK');
        $FirstName = str_replace("'", "", $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');
        $Sex = $this->input->post('Sex');
        $LastName = str_replace("'", "", $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');
        $Bahasa = $this->input->post('Bahasa');
        // =================================================================================== 
        $HomeProvince = $this->input->post('HomeProvince');
        $HomeCity = $this->input->post('HomeCity');
        $Kecamatan = $this->input->post('Kecamatan');
        $Kelurahan = $this->input->post('Kelurahan');
        $HomeAddress1 = $this->input->post('HomeAddress1');
        $HomeAddress2 = $this->input->post('HomeAddress2');
        // =================================================================================== 
        $CompanyCode = $this->input->post('CompanyCode');
        $perusahaan = $this->input->post('perusahaan');
        $kode = $this->input->post('kode');
        $CellPhone = $this->input->post('CellPhone');
        // =================================================================================== 
        $tgll = date('Y-m-d', strtotime(@$DOB));
        $tanggal_lahir = new DateTime($tgll);
        $sekarang = new DateTime("today");
        if ($tanggal_lahir > $sekarang) {
            $thn = "0";
            $bln = "0";
            $tgl = "0";
        }
        $thn = $sekarang->diff($tanggal_lahir)->y;
        // =================================================================================== 

        $penomoran = $this->db->query("SELECT * FROM Penomoran WHERE ModulAktivitas = 'Pasien'")->row_array();
        $noMRBaru = $penomoran['NoUrut'] + 1;

        $var = $noMRBaru;
        $digit = strlen($var);
        if ($digit > 5) {
            $addMr = $noMRBaru;
        } else {
            $addMr = '0' . $noMRBaru;
        }

        $this->db->query("INSERT INTO Patient (PatientCode,FirstName,LastName,DOB,DOBPlace,Sex,Nationality,Religion,CompanyCode,HomeProvince,HomeCity,Kecamatan,Kelurahan,HomeAddress1,HomeAddress2,EmployeeID,CellPhone,Age, [Status],Education,PatientType,[NAMA PERUSAHAAN],KODE,Profession,SukuBangsa,NIK,Bahasa) VALUES ('$addMr','$FirstName','$LastName','$DOB','$DOBPlace','$Sex','$Nationality','$Religion','$CompanyCode','$HomeProvince','$HomeCity','$Kecamatan','$Kelurahan','$HomeAddress1','$HomeAddress2','$EmployeeID','$CellPhone', '$thn', '$Status','$Education','$PatientType','$perusahaan','$kode','$Profession','$SukuBangsa','$NIK','$Bahasa')");
        $this->db->query("UPDATE Penomoran SET NoUrut = '$noMRBaru' WHERE ModulAktivitas = 'Pasien'");

        $this->session->set_flashdata("success", "Ok!");
        redirect('pasien/detailPasien/' . $addMr);
    }

    public function pendaftaran()
    {
        extract($_GET);
        date_default_timezone_set("Asia/Jakarta");
        // ---------------------------------------------------------------------
        $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['diagnosa'] = $this->M_Pendaftaran->diagnosa();
        $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 getApiPeserta()
    {
        $nik = $this->input->post('nik');
        $noka = $this->input->post('noka');
        //echo $nik;exit();
        $datapeserta = array();
        if (!empty($nik)) {
            //echo 'nik';exit();
            $datapeserta = $this->M_Pendaftaran->pesertaNik($nik);
        } else if (!empty($noka)) {
            //echo 'noka';exit();
            $datapeserta = $this->M_Pendaftaran->peserta($noka);
        }

        $data['getpeserta'] = $datapeserta['response']['list'];
        $data['cekpeserta'] = $datapeserta['metaData']['code'];
        $data['messagepeserta'] = $datapeserta['metaData']['message'];
        echo json_encode($data['getpeserta']);
    }

    public function prosesdaftar()
    {
        date_default_timezone_set("Asia/Jakarta");
        $cekPasien = $this->input->post('cekPasien');
        $jns = $this->input->post('jns');
        $tgl = $this->input->post('tgl');
        $PatientCode = $this->input->post('PatientCode');
        $Description = str_replace("'", "", $this->input->post('Description'));
        $kategori = $this->input->post('kategori');
        $company = $this->input->post('company');
        $perusahaan = $this->input->post('perusahaan');
        $tujuan = $this->input->post('tujuan');
        $doctor = $this->input->post('doctor');
        $kelas = $this->input->post('kelas');
        $intakeTime = date('H:i');
        $catatan = $this->input->post('catatan');
        $user = $this->input->post('user');
        $RefferedCode = $this->input->post('refferedFrom');
        $nokartu = $this->input->post('nokartu');
        // $room = $this->input->post('room');
        $cekTujuan = count($tujuan);

        // CEK OPEN
        if ($cekPasien > 0) {
            $this->session->set_flashdata("error", "Data Pasien telah masih OPEN atau Sudah OPEN terdaftar hari ini !");
            redirect('pendaftaran/pendaftaran?nomr=' . $PatientCode);
        } else {
            // CEGAH CASES > 1
            $dataCases = $this->db->query("SELECT * FROM Cases WHERE PatientCode = '$PatientCode' AND [Intake Date] = '$tgl' AND [Case Status] = 'OPEN'");
            $countCases = $dataCases->num_rows();
            if ($countCases >= 1) {
                $this->session->set_flashdata("error", "Data Pasien telah terdaftar di hari ini !");
                redirect('pendaftaran/pendaftaran?nomr=' . $PatientCode);
            } else {
                $abdulradjak = $this->db->query("SELECT * FROM Bpjs_ID")->row_array();
                $KodePPK = $abdulradjak['KodePPK'];
                if ($company == 102) {
                    // ---------------------------------------------------------------------
                    date_default_timezone_set("Asia/Jakarta");
                    $tgl = date('Y-m-d');
                    $tglkirim = date('d-m-Y');

                    $ch = curl_init();
                    $jsonarray = array(
                        'kdProviderPeserta' => "$KodePPK",
                        'tglDaftar'         => "$tglkirim",
                        'noKartu'           => "$nokartu",
                        'kdPoli'            => "001",
                        'keluhan'           => null,
                        'kunjSakit'         => true,
                        'sistole'           => 0,
                        'diastole'          => 0,
                        'beratBadan'        => 0,
                        'tinggiBadan'       => 0,
                        'respRate'          => 0,
                        'heartRate'         => 0,
                        'rujukBalik'        => 0,
                        'kdTkp'             => "10"
                    );

                    $payload = json_encode($jsonarray);

                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
                    curl_setopt($ch, CURLOPT_URL, $abdulradjak['IP_WS_Layanan'] . "pcare/pendaftaran/addpendaftaran");
                    $result = curl_exec($ch);
                    curl_close($ch);
                    $result = json_decode($result, true);
                    $kodeNotif = $result['metaData']['code'];
                    $pesan = $result['metaData']['message'];
                    // echo $pesan;
                    // exit;

                }

                // CASE ID BARU
                $getCase = $this->db->query("SELECT * FROM SystemNo WHERE SystemName = 'Case'")->row_array();
                $dbInit = $this->db->query("SELECT TOP 1 * FROM Bpjs_ID")->row_array();
                $case = $getCase['NoNumeric'];
                $cases = $getCase['NoNumeric'] + 1;
                $caseidterakhir = $this->db->query("SELECT TOP 1 * FROM Cases order by [Case ID] DESC")->row_array();
                $caseterakhir = $caseidterakhir['Case ID'] + 1;

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

                $tujuanA = $tujuan[0];
                $doctorA = $doctor[0];

                $tPoli = $this->db->query("SELECT * FROM Category WHERE ActivityClass = '$tujuanA'")->row_array();
                $tujuanKode = $tPoli['KodePoli'];
                $Politujuan = $tPoli['ActivityClass'];
                // ANTRIAN
                // $aPoli = $this->db->query("SELECT TOP 1 * FROM Antrian where DoctInCharge = '$doctorA'")->row_array();
                // if ($jns == "pribadi") {
                //     $antrian = $aPoli['NoAntrian'] + 1;
                //     $this->db->query("UPDATE Antrian SET No_Akhir = '$antrian' WHERE DoctInCharge = '$doctorA'");
                //     $noAntrian = $aPoli['Alias'] . '.' . $antrian;
                // } else if ($jns == "bpjs") {
                //     $antrian = $aPoli['NoAntrian'] + 1;
                //     $this->db->query("UPDATE Antrian SET No_Akhir = '$antrian' WHERE DoctInCharge = '$doctorA'");
                //     $noAntrian = $aPoli['Alias'] . '.' . $antrian;
                // } 

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

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

                $poliTerakhir = $this->db->query("SELECT TOP 1 * FROM [dbo].[Cases] where [PatientCode] = '$PatientCode' order by [Intake Date] DESC")->row_array();
                $LastOP = $poliTerakhir['LastOP'];
                $tglCreate = date('Y-m-d H:i:s');

                $this->db->query("INSERT INTO Cases ([Case ID], [Description], [Category], [Case Status], [Intake Date], [Intake Time], PatientCode, CompanyCode, RefferedCode, [Patient Status], [UserCreated], DateCreated, RegStatus, DoctIncharge,  LastOP, CaseDetail, KODE, Class, Note) VALUES ('$caseterakhir', '$Description', 'OP', 'OPEN', '$tgl', '$intakeTime', '$PatientCode', '$company', '$RefferedCode','$statusPatient', 'web-$user','$tglCreate', '$RegStatus', '$doctorA', '$Politujuan', '0', '$perusahaan', 'OP', '$catatan')");

                $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
                $id_bpjs = $abdulradjak['BPJS_ID'];
                $KodePPK = $abdulradjak['KodePPK'];




                // // INSERT TEMP STATUS
                // $this->db->query("INSERT INTO Temp_Status ([Case ID], [Intake Date], PatientCode, PatientName, iPrint, Label) VALUES ('$case','$tgl','$PatientCode','$Description','0','0')");

                // INSERT CASE ADMIN
                $cek_tambah = $this->input->post('cek_tambah');
                $jumlah_dipilih1 = count($cek_tambah) + 1;
                for ($x = 0; $x < $jumlah_dipilih1; $x++) {
                    $this->db->query("
                    INSERT INTO CaseAdmin ([Case ID], Unit, [DoctorID]
                    ) VALUES (
                    '$caseterakhir', '$tujuan[$x]', '$doctor[$x]')");
                }

                // INSERT TEMPCASES
                $this->db->query("INSERT INTO [dbo].[TempCases] ([Case ID], [Intake Date], [PatientCode], [PatientName], [iPrint]) VALUES ('$caseterakhir', '$tgl', '$PatientCode','$Description', '0')");

                // 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']);
                $this->db->query("INSERT INTO TLOG (sKey,sTableName,sAction,dDate,sTime,sUser,sCompName) VALUES ('$caseterakhir','Cases','ADD','$tgl','$intakeTime','web-$user','$hostname')");

                $this->session->set_flashdata("success", "Ok !");
                redirect('pendaftaran/detailCaseUmum?case=' . $caseterakhir);
            }
        }
    }

    public function detailCaseUmum()
    {
        extract($_GET);
        $this->load->model('M_Pendaftaran');
        // ---------------------------------------------------------------------
        date_default_timezone_set("Asia/Jakarta");
        $day = date('Y-m-d');
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        // ---------------------------------------------------------------------
        $data['detailCaseUmum'] = $mr = $this->M_Pendaftaran->detailCaseUmum($case)->row_array();
        $patientCode = $mr['PatientCode'];

        $data['countCaseUmum'] = $this->M_Pendaftaran->detailCaseUmum($case)->num_rows();
        // ===================================================================================
        // if (isset($histori)) {
        // 	$history = $this->M_Pendaftaran->history($histori);
        // 	$data['history'] = @$history['response']['list']['histori'];
        // 	$data['code'] = @$history['metaData']['code'];
        // 	$data['message'] = @$history['metaData']['message'];
        // }
        // ===================================================================================
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pendaftaran/detailCaseUmum', $data);
        $this->load->view('properti/footer', $data);
    }

    public function addTujuanKunjungan($case)
    {
        $Unit = $this->input->post('Unit');
        $DoctorID = $this->input->post('DoctorID');

        $this->db->query("INSERT INTO CaseAdmin ([Case ID],Unit,DoctorID) VALUES ('$case','$Unit','$DoctorID')");
        $this->session->set_flashdata("success", "Berhasil!");
        redirect('Pendaftaran/detailCaseUmum?case=' . $case);
    }

    public function updateTujuanKunjungan($id, $case)
    {
        $Unit = $this->input->post('Unit');
        $DoctorID = $this->input->post('DoctorID');
        $this->db->query("UPDATE CaseAdmin SET Unit = '$Unit', DoctorID = '$DoctorID' WHERE AdminID = '$id'");
        $this->db->query("UPDATE Cases SET DoctIncharge = '$DoctorID' WHERE [Case ID] = '$case'");
        $this->session->set_flashdata("success", "Berhasil!");
        redirect('pendaftaran/detailCaseUmum?case=' . $case);
    }

    public function cekpesertabpjs()
    {
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $this->M_user->getUserSession()->row_array();

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

    public function bpjsByNo()
    {
        extract($_GET);
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $this->M_user->getUserSession()->row_array();

        $peserta = $this->M_Pendaftaran->peserta($nobpjs);
        $data['getpeserta'] = $peserta['response']['list'];
        $data['cekpeserta'] = $peserta['metaData']['code'];
        $data['messagepeserta'] = $peserta['metaData']['message'];

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

    public function bpjsByNik()
    {
        extract($_GET);
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $this->M_user->getUserSession()->row_array();

        $peserta = $this->M_Pendaftaran->pesertaNik($nik);
        $data['getpeserta'] = $peserta['response']['list'];
        $data['cekpeserta'] = $peserta['metaData']['code'];
        $data['messagepeserta'] = $peserta['metaData']['message'];

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

    /**List Diagnosa */
    public function DaftarDiagnosa()
    {
        $query =  $this->db->query("Select ICD_CODE, DESCRPTION From ICD9 where Active = '1' ")->result();
        $cari = $this->input->post('cari');
        if ($cari != '') {
            $query = $this->db->query("Select ICD_CODE, DESCRPTION From ICD9 WHERE Active = '1' and ICD_CODE like '%$cari%' or DESCRPTION like '%$cari%' order by ICD_CODE ")->result();
        }

        echo json_encode($query);
    }

    public function DaftarDiagnosa1()
    {
        $query =  $this->db->query("Select ICD_CODE, DESCRPTION From ICD9 where Active = '1' ")->result();
        $cari = $this->input->post('cari');
        if ($cari != '') {
            $query = $this->db->query("Select ICD_CODE, DESCRPTION From ICD9 WHERE Active = '1' and ICD_CODE like '%$cari%' or DESCRPTION like '%$cari%' order by ICD_CODE ")->result();
        }

        echo json_encode($query);
    }

    public function pelayananBpjs()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['pasienbpjs'] = $this->db->query("select c.[Case ID],c.PatientCode,c.Description as nama,c.Category,c.[Case Status], co.CompanyName ,c.[Intake Date],a.Unit,cd.StatusPlayanan
        from Cases c join CaseAdmin a on c.[Case ID] = a.[Case ID]
        Join CaseDetail cd on cd.[Case ID] = c.[Case ID]
        join Company co on co.CompanyCode = c.CompanyCode
        where c.[Intake Date] = '$tgl' and c.CompanyCode = '102' and c.[Case Status] <> 'Cancel' and cd.StatusPlayanan is null ")->result_array();

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

    public function RecordpelayananBpjs()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['pasienbpjs'] = $this->db->query("select c.[Case ID],c.PatientCode,c.Description as nama,c.Category,c.[Case Status], co.CompanyName ,c.[Intake Date],a.Unit,cd.StatusPlayanan
        from Cases c join CaseAdmin a on c.[Case ID] = a.[Case ID]
        Join CaseDetail cd on cd.[Case ID] = c.[Case ID]
        join Company co on co.CompanyCode = c.CompanyCode
        where c.[Intake Date] = '$tgl' and c.CompanyCode = '102' and cd.Statusplayanan = 1 ")->result_array();

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

    public function viewpelayanan($id)
    {
        date_default_timezone_set("Asia/Jakarta");

        $data['record'] = $this->input->get('record');

        $tgl = date('Y-m-d');
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['id'] = $this->db->query("SELECT C.[Case ID] AS ID, C.PatientCode AS MR, C.Description AS Nama, C.[Intake Date] AS Kunjungan, P.DOB AS TTL, D.[FirstName] AS Dokter, CA.Unit AS Poli, C.CompanyCode, P.EmployeeID FROM Cases C, CaseAdmin CA, Doctor D, Patient P WHERE C.[Case ID] = '$id' AND C.[Case ID]=CA.[Case ID] AND CA.[DoctorID] = D.[DoctorID] AND C.[PatientCode]=P.[PatientCode]")->row_array();
        $data['poli'] = $this->M_anamnesa->poli()->result_array();
        $data['dokter'] = $this->M_anamnesa->dokter()->result_array();
        $data['diagnosa'] = $this->M_rekamMedis->diagnosa();

        $polik = $data['id']['Poli'];
        $poliklinik = $this->db->query("Select * from Antrian where Jenis like '%$polik%'")->row_array();
        $kdpoli = $poliklinik['KodePoli'];
        // ======================================================
        $apigetpulang = $this->M_Pendaftaran->apigetpulang();
        $data['getpulang'] = $apigetpulang['response']['list']['list'];
        // ======================================================
        $apigetdokter = $this->M_anamnesa->apigetdokter($kdpoli);
        $data['getdokter'] = $apigetdokter['response']['list'];

        $apigetperawat = $this->M_anamnesa->apigetperawat();
        $data['getperawat'] = $apigetperawat['response']['list']['list'];

        // print_r($apigetperawat);
        // exit();
        //===================================================================
        $apigetspesialis = $this->M_Pendaftaran->apigetspesialis();
        $data['getspesialis'] = $apigetspesialis['response']['list']['list'];
        //===================================================================
        $apigetsarana = $this->M_Pendaftaran->apigetsarana();
        $data['getsarana'] = $apigetsarana['response']['list']['list'];
        //===================================================================
        $apigetprognosa = $this->M_anamnesa->apigetprognosa();
        $data['getprognosa'] = $apigetprognosa['response']['list']['list'];

        $data['alergiMakan'] = $this->M_anamnesa->apigetalergi("01")['response']['list']['list'];
        $data['alergiObat'] = $this->M_anamnesa->apigetalergi("03")['response']['list']['list'];
        $data['alergiUdara'] = $this->M_anamnesa->apigetalergi("02")['response']['list']['list'];


        //print_r($apigetdokter['response']);exit();

        $caseid = $this->uri->segment(3);
        $data['hasilpemeriksaan'] = $this->db->query("Select er.pemeriksaan_fisik, c.[Case ID],c.PatientCode,c.Description as nama,cd.Unit, 
        cd.Keluhan,er.obat,er.diagnosa_primer,er.diagnosa_sekunder,er.paneldiag,
        cd.TinggiBadan,cd.BeratBadan,cd.Suhu,cd.Tensi,cd.Diastole,cd.respRate,cd.heartRate,cd.DoctorID, d.KodeAlias,
        er.alergiMakan, er.alergiObat, er.alergiUdara, er.prognosa, er.statusPulang, cd.lingkarperut
        from Cases c join CaseDetail cd on c.[Case ID] = cd.[Case ID]
        join erm_pemeriksaan_fisik er on er.case_id = c.[Case ID] 
        join Doctor d on d.DoctorID = cd.DoctorID
        where c.[Case ID] = '$caseid'")->result_array();

        $obat = $this->db->query("select p.Description  from [Activity Drugs] ad 
        join Pharmacy p on p.PharmacyCode = ad.DrugsID
        where ad.[Case ID] = '$caseid'")->result_array();

        $data['terapi'] = "";
        foreach ($obat as $obat) {
            $data['terapi'] .= $obat['Description'] . ', ';
        }

        //print_r($data['hasilpemeriksaan']); exit();

        $data['diagnosa1'] = $this->db->query("select er.diagnosa_primer,ic.DESCRPTION as Description from erm_pemeriksaan_fisik er
        join ICD9 ic on er.diagnosa_primer = ic.ICD_CODE where er.case_id = '$caseid'")->row_array();

        $data['diagnosa2'] = $this->db->query("select er.diagnosa_sekunder,ic.DESCRPTION as Description from erm_pemeriksaan_fisik er
        join ICD9 ic on er.diagnosa_sekunder = ic.ICD_CODE where er.case_id = '$caseid'")->row_array();

        $data['rujukan'] = $this->db->query("Select * from BPJS_Rujukan where [Case ID] = '$caseid'")->row_array();

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

    public function GetAlergi()
    {
        $type = $this->input->post('type');
        $apigetalergi = $this->M_anamnesa->apigetalergi($type);
        $data['alergi'] = $apigetalergi['response']['list']['list'];
        echo json_encode($data['alergi']);
    }

    public function prosespelayananbpjs()
    {
        // --- SETUP DASAR ---
        date_default_timezone_set("Asia/Jakarta");
        $tglSekarang = date('d-m-Y'); // format YYYY-MM-DD
        $jamSekarang = date('H:i');
        $tanggalbuat = date('Y-m-d H:i:s');

        // --- KONFIG BPJS ---
        $abdulradjak = $this->M_BpjsID->abdulradjak()->row_array();
        $KodePPK = $abdulradjak['KodePPK'];

        // --- INPUT POST ---
        $record         = $this->input->post('record');
        $caseid         = $this->input->post('caseid');
        $doktertujuan   = $this->input->post('doktertujuan');
        $keluhan        = $this->input->post('keluhan');
        $terapi         = $this->input->post('terapi');
        $terapinonobat  = $this->input->post('terapinonobat');
        $kesadaran      = $this->input->post('kesadaran');
        $statusPulangDesc = $this->input->post('statuspulang');
        $statuspulang   = explode("-", $statusPulangDesc)[0];
        $politujuan     = $this->input->post('politujuan');
        $tinggibadan    = $this->input->post('tinggibadan');
        $beratbadan     = $this->input->post('beratbadan');
        $suhu           = $this->input->post('suhu');
        $tensi          = $this->input->post('tensi');
        $diastole       = $this->input->post('diastole');
        $resprate       = $this->input->post('resprate');
        $heartrate      = $this->input->post('heartrate');
        $lingkarperut   = $this->input->post('lingkarperut');
        $kartu          = $this->input->post('kartu');
        $anamnesa       = $this->input->post('anamnesa');
        $bmhp           = $this->input->post('bmhp');

        // --- ALERGI & PROGNOSA ---
        $alergiMakanDesc = $this->input->post('subAlergiMakan');
        $alergiUdaraDesc = $this->input->post('subAlergiUdara');
        $alergiObatDesc  = $this->input->post('subAlergiObat');
        $prognosaDesc    = $this->input->post('prognosa');

        $kodeAlergiMakan = explode("-", $alergiMakanDesc)[0] ?? '0';
        $kodeAlergiUdara = explode("-", $alergiUdaraDesc)[0] ?? '0';
        $kodeAlergiObat  = explode("-", $alergiObatDesc)[0] ?? '0';
        $kodePrognosa    = explode("-", $prognosaDesc)[0] ?? '0';

        // --- RUJUKAN ---
        $ppkrujukan      = $this->input->post('ppkrujukan');
        $spesialis       = $this->input->post('spesialis');
        $subspesialis    = $this->input->post('subspesialis');
        $catatan         = $this->input->post('catatan');
        $tglrujukInput   = $this->input->post('tglrujuk');
        $jadwal          = $this->input->post('jadwal');
        $kdppkrujuk      = $this->input->post('kdppkrujukan');
        $kdspesialis     = $this->input->post('kdspesialis');
        $kdsubspesialis  = $this->input->post('kdsubspesialis');

        // --- FORMAT TANGGAL VALID ---
        $tglrujuk = null;
        if (!empty($tglrujukInput)) {
            $cekFormat = DateTime::createFromFormat('Y-m-d', $tglrujukInput);
            if ($cekFormat) {
                $tglrujuk = $tglrujukInput;
            } else {
                $tglrujuk = date('Y-m-d', strtotime(str_replace('/', '-', $tglrujukInput)));
            }
        }

        // --- DATA PASIEN ---
        $qdata = $this->db->query("
        SELECT c.[Case ID], p.Sex, p.DOB 
        FROM Cases c
        INNER JOIN Patient p ON c.PatientCode = p.PatientCode
        WHERE c.[Case ID] = '$caseid'
    ")->row_array();

        $sex      = $qdata['Sex'] ?? '';
        $tgllahir = $qdata['DOB'] ?? '';

        if ($statuspulang != '4') {
            $kdsubspesialis = null;
            $subspesialis   = null;
        }

        // --- BANGUN JSON ---
        $jsonarray = [
            "noKunjungan"          => null,
            "noKartu"              => $kartu,
            "tglDaftar"            => $tglSekarang,
            "kdPoli"               => $politujuan,
            "keluhan"              => $keluhan,
            "kdSadar"              => $kesadaran,
            "sistole"              => (int)$tensi,
            "diastole"             => (int)$diastole,
            "beratBadan"           => (int)$beratbadan,
            "tinggiBadan"          => (int)$tinggibadan,
            "respRate"             => (int)$resprate,
            "heartRate"            => (int)$heartrate,
            "lingkarPerut"         => (int)$lingkarperut,
            "kdStatusPulang"       => $statuspulang,
            "tglPulang"            => $tglSekarang,
            "kdDokter"             => $doktertujuan,
            "kdDiag1"              => $this->input->post('diag1'),
            "kdDiag2"              => null,
            "kdDiag3"              => null,
            "kdPoliRujukInternal"  => null,
            "rujukLanjut" => [
                "tglEstRujuk"   => $tglrujuk ?? null,
                "kdppk"         => $kdppkrujuk ?? null,
                "subSpesialis"  => $kdsubspesialis ?? null,
                "khusus"        => null
            ],
            "kdTacc"        => 0,
            "alasanTacc"    => null,
            "anamnesa"      => $anamnesa,
            "alergiMakan"   => $kodeAlergiMakan,
            "alergiUdara"   => $kodeAlergiUdara,
            "alergiObat"    => $kodeAlergiObat,
            "kdPrognosa"    => $kodePrognosa,
            "terapiObat"    => $terapi,
            "terapiNonObat" => $terapinonobat,
            "bmhp"          => $bmhp,
            "suhu"          => $suhu
        ];

        // --- SETUP CURL ---
        $payload = json_encode($jsonarray, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $ch = curl_init();

        $url = !empty($record)
            ? $abdulradjak['IP_WS_Layanan'] . "pcare/kunjungan/EditKunjungan"
            : $abdulradjak['IP_WS_Layanan'] . "pcare/kunjungan/addkunjungan";

        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_CUSTOMREQUEST  => "POST",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS     => $payload,
            CURLOPT_TIMEOUT        => 30
        ]);

        $result = curl_exec($ch);

        // --- ERROR HANDLING ---
        if (curl_errno($ch)) {
            $err = curl_error($ch);
            curl_close($ch);

            // Tulis ke log
            log_message('error', "BPJS CURL ERROR | CASEID: $caseid | $err");
            $this->session->set_flashdata('error', "Gagal koneksi ke server BPJS: $err");
            redirect('pendaftaran/pelayananBpjs');
            return;
        }

        curl_close($ch);
        $a = json_decode($result, true);
        $kodeNotif  = $a['metaData']['message'] ?? 'Server BPJS tidak merespon';
        $kode       = $a['metaData']['code'] ?? 500;
        $nokunjungan = $a['response']['list']['message'] ?? '';

        // --- LOG KE FILE ---
        $logFile = APPPATH . 'logs/log-bpjs-' . date('Y-m-d') . '.log';
        $logData = "=== BPJS REQUEST ===\n" .
            "Tanggal : " . date('Y-m-d H:i:s') . "\n" .
            "CaseID  : $caseid\n" .
            "URL     : $url\n" .
            "Payload : $payload\n" .
            "Response: $result\n\n";
        file_put_contents($logFile, $logData, FILE_APPEND);

        // --- CEK APAKAH RUJUKAN SUDAH ADA ---
        $cekRujukan = $this->db->query("
        SELECT TOP 1 [Case ID] 
        FROM BPJS_Rujukan 
        WHERE [Case ID] = '$caseid'
    ")->num_rows();

        if ($cekRujukan > 0) {
            // ✅ UPDATE JIKA SUDAH ADA
            $this->db->query("
            UPDATE BPJS_Rujukan SET
                RujukanNo      = '$nokunjungan',
                [DestCode]     = '$kdppkrujuk',
                [DestName]     = '$ppkrujukan',
                [DestPoliCode] = '$kdspesialis',
                [DestPoliName] = '$spesialis',
                [Note]         = '$catatan',
                [Sex]          = '$sex',
                [DOB]          = '$tgllahir',
                [TglBerkunjung]= '$tglrujuk',
                [JadwalPraktek]= '$jadwal',
                [DateCreated]  = '$tanggalbuat',
                [TelahDiberikan]= 'RUJUK',
                [KodePPK]      = '$KodePPK',
                [DokterPerujuk]= '$doktertujuan',
                [AlasanTACC]   = '-'
            WHERE [Case ID] = '$caseid'
        ");
        } else {
            // ✅ INSERT BARU
            $this->db->query("
            INSERT INTO BPJS_Rujukan 
            ([Case ID],RujukanNo,[DestCode],[DestName],[DestPoliCode],[DestPoliName],
             [Note],[Sex],[DOB],[TglBerkunjung],[JadwalPraktek],[DateCreated],
             [TelahDiberikan],[KodePPK],[DokterPerujuk],[AlasanTACC])
            VALUES 
            ('$caseid','$nokunjungan','$kdppkrujuk','$ppkrujukan','$kdspesialis',
             '$spesialis','$catatan','$sex','$tgllahir','$tglrujuk','$jadwal',
             '$tanggalbuat','RUJUK','$KodePPK','$doktertujuan','-')
        ");
        }

        // --- UPDATE PEMERIKSAAN FISIK ---
        $this->db->query("
        UPDATE erm_pemeriksaan_fisik SET
            alergiMakan  = '$alergiMakanDesc',
            alergiObat   = '$alergiObatDesc',
            alergiUdara  = '$alergiUdaraDesc',
            prognosa     = '$prognosaDesc',
            statusPulang = '$statusPulangDesc'
        WHERE [case_id] = '$caseid'
    ");

        // --- HANDLE HASIL BPJS ---
        if ($kode == 201) {
            $this->db->query("
                UPDATE CaseDetail 
                SET StatusPlayanan = '1', NoKunjungan = '$nokunjungan'
                WHERE [Case ID] = '$caseid'
            ");
            $this->session->set_flashdata("success", $kodeNotif);
        } else {
            $pesanError = $kodeNotif ?? 'Terjadi kesalahan pada server BPJS.';
            $this->session->set_flashdata("error", $pesanError);
        }
        session_write_close(); // penting agar session tersimpan dulu

        redirect('pendaftaran/pelayananBpjs');
    }


    /**List Diagnosa */
    public function PelayananDiagnosa1()
    {
        $this->db->select('ICD_CODE, DESCRPTION');
        $this->db->from('ICD9');
        $cari = $this->input->post('cari');
        if ($cari != '') {
            $this->db->like('ICD_CODE', $cari);
            $this->db->or_like('DESCRPTION', $cari);
        }

        $this->db->order_by('ICD_CODE');
        $query = $this->db->get()->result();
        echo json_encode($query);
    }

    public function PelayananDiagnosa2()
    {
        $this->db->select('ICD_CODE, DESCRPTION');
        $this->db->from('ICD9');
        $cari = $this->input->post('cari');
        if ($cari != '') {
            $this->db->like('ICD_CODE', $cari);
            $this->db->or_like('DESCRPTION', $cari);
        }

        $this->db->order_by('ICD_CODE');
        $query = $this->db->get()->result();
        echo json_encode($query);
    }

    public function PelayananDiagnosa3()
    {
        $this->db->select('ICD_CODE, DESCRPTION');
        $this->db->from('ICD9');
        $cari = $this->input->post('cari');
        if ($cari != '') {
            $this->db->like('ICD_CODE', $cari);
            $this->db->or_like('DESCRPTION', $cari);
        }

        $this->db->order_by('ICD_CODE');
        $query = $this->db->get()->result();
        echo json_encode($query);
    }
    /**End of List Diagnosa */



    public function daftarnomr()
    {
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['asuransi'] = $this->M_Pendaftaran->asuransi()->result_array();
        $data['dokter'] = $this->M_anamnesa->dokter()->result_array();
        $data['poli'] = $this->M_Pendaftaran->daftarPoli()->result_array();
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pasien/daftartanpamr', $data);
        $this->load->view('properti/footer', $data);
    }


    public function form()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $data['judul'] = "Form Pendaftaran";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['cases'] = $this->db->query("select c.[Case ID],c.PatientCode,c.Description,c.Category,
        c.[Case Status],c.[Intake Date],c.[Intake Time],co.CompanyName
        from Cases c 
        join Company co on co.CompanyCode = c.CompanyCode
        where [Intake Date] ='$tgl'")->result_array();
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('pendaftaran/form', $data);
        $this->load->view('properti/footer', $data);
    }

    public function formpendaftaranttd($id)
    {
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $user = $this->M_user->getUserSession()->row_array();
        $data['pasien'] = $this->db->query("Select * from Patient where PatientCode = '$id'")->row_array();

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

    public function simpanformpendaftaran($mr)
    {
        date_default_timezone_set('Asia/Jakarta');
        $folderPath = "./images/uploadsign/pendaftaran/";
        $yang_menjelaskan = $_POST['yang_menjelaskan'];
        $pasien = $_POST['pasien'];
        date_default_timezone_set('Asia/Jakarta');
        $tgl = date('Y-m-d');
        $jam = date('H:i');

        // yang menjelaskan
        $filename_1 = $mr . ' - Penjelasan ' . url_title($yang_menjelaskan, '-', true);
        $image_parts_1 = explode(";base64,", $_POST['ttd_yang_menjelaskan']);
        $image_type_aux_1 = explode("image/", $image_parts_1[0]);
        $image_type_1 = $image_type_aux_1[1];
        $image_base64_1 = base64_decode($image_parts_1[1]);
        $file_1 = $folderPath . $filename_1 . '.' . $image_type_1;
        file_put_contents($file_1, $image_base64_1);

        // pasien
        $filename_2 = $mr . ' - Pasien ' . url_title($pasien, '-', true);
        $image_parts_2 = explode(";base64,", $_POST['ttd_pasien']);
        $image_type_aux_2 = explode("image/", $image_parts_2[0]);
        $image_type_2 = $image_type_aux_2[1];
        $image_base64_2 = base64_decode($image_parts_2[1]);
        $file_2 = $folderPath . $filename_2 . '.' . $image_type_2;
        file_put_contents($file_2, $image_base64_2);

        $this->db->query("INSERT INTO Formdaftarttd (PatientCode, yang_menjelaskan, ttd_yang_menjelaskan, pasien, ttd_pasien, tgl_buat, jam_buat) VALUES ('$mr', '$yang_menjelaskan', '$filename_1', '$pasien', '$filename_2', '$tgl', '$jam')");

        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> TTD Tersimpan.</div>');
        redirect(base_url('pendaftaran/formpendaftaranttd/' . $mr));
    }

    public function cetakformdaftar($mr)
    {
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['pasien'] = $this->db->query("SELECT * FROM Patient WHERE PatientCode = '$mr'")->row_array();
        $data['unit'] = $this->db->query("SELECT * FROM Utama")->row_array();
        $data['ttd'] = $this->db->query("SELECT * FROM Formdaftarttd WHERE PatientCode = '$mr'")->row_array();
        $this->load->view('cetakFR/printFormDaftar', $data);
    }

    public function get_subspesialis()
    {
        $kdspesialis = $this->input->post('kdSpesialis');
        $getSubspesialis = $this->M_Pendaftaran->getSubspesialis($kdspesialis);
        $data['getSubspesialis'] = $getSubspesialis['response']['list']['list'];
        echo json_encode($data['getSubspesialis']);
    }

    public function carirujukanfaskes()
    {
        $kodeSubSpesialis = $this->input->post('subspesialis');
        $kodeSarana = $this->input->post('sarana');
        $tanggalEstimasiRujuk = $this->input->post('TglRencana');

        $results = $this->M_Pendaftaran->get_faskes_rujukan($kodeSubSpesialis, $kodeSarana, $tanggalEstimasiRujuk);

        echo json_encode($results);
    }

    public function cetakrujukan($id)
    {
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['pasien'] = $this->db->query("SELECT r.DestPoliName,r.DestName,c.Description,c.PatientCode,p.EmployeeID,c.[Presenting Problem],Age,P.DOB,p.Sex,r.TglBerkunjung,r.DestCode,r.DestPoliName,r.Note,r.JadwalPraktek FROM Patient p Inner Join Cases c 
        on p.PatientCode = c.PatientCode 
        INNER JOIN BPJS_Rujukan R
        on r.[Case ID] = c.[Case ID]
        WHERE r.[Case ID] = '$id'")->row_array();
        $data['unit'] = $this->db->query("SELECT * FROM Utama")->row_array();
        $this->load->view('cetak/cetakrujukanppk', $data);
    }
}
