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

class RekamMedis extends CI_Controller
{

    // CONSTRUCT
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->model('M_rekamMedis');
        $this->load->model('M_user');
        $this->load->model('M_anamnesa');
        $this->load->model('M_BpjsID');
        $this->load->helper('url');

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

    public function index()
    {
        $data['judul'] = "Klinik";
        $data['utama'] = $this->db->query('SELECT * FROM BPJS_ID')->row_array();
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['antrian'] = $this->db->query("SELECT * FROM Antrian")->result_array();
        $data['dokter'] = $this->db->query("SELECT * FROM Doctor where Active = 'T'")->result_array();
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('rekamMedis/home', $data);
        $this->load->view('properti/footer', $data);
    }

    public function updateAntrian()
    {
        $id = $_POST['id'];
        $poli = $_POST['poli'];
        $dokter = $_POST['dokter'];
        $count = count($id);
        for ($i = 0; $i < $count; $i++) {
            $this->db->query("UPDATE Antrian SET Jenis='$poli[$i]', DoctInCharge='$dokter[$i]' WHERE Id_Poli=" . $id[$i]);
        }
        redirect('rekamMedis');
    }

    public function getDokter()
    {
        $layanan = $this->input->post('layanan');

        $query = $this->db->query("SELECT * FROM Antrian a, Doctor d WHERE a.DoctInCharge=d.DoctorID and Jenis = '$layanan'")->result();
        echo json_encode($query);
    }

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

    public function listpasienanamnesa()
    {
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['pasien'] = $this->M_rekamMedis->pasienanamnesa()->result_array();
        $data['poli'] = $this->M_anamnesa->poli()->result_array();
        $data['dokter'] = $this->M_anamnesa->dokter()->result_array();
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('anamnesa/listpasienanamnesa', $data);
        $this->load->view('properti/footer', $data);
    }

    public function monitoring()
    {
        $type = $this->input->get('type');
        if (empty($type)) {
            echo 'Invalid request';
            exit();
        }
        $data['tanggal'] = $this->input->post('tanggal');
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['pasien'] = $this->M_rekamMedis->monitoring($type)->result_array();
        //$data['pelayanan'] = $this->db->query("select erm_pemeriksaan_fisik.obat,erm_pemeriksaan_fisik.case_id from erm_pemeriksaan_fisik join Cases on erm_pemeriksaan_fisik.case_id = Cases.[Case ID]")->result_array();
        $data['poli'] = $this->M_anamnesa->poli()->result_array();
        $data['dokter'] = $this->M_anamnesa->dokter()->result_array();
        //$data['hasilpemeriksaan'] = $this->M_rekamMedis->hasilpemeriksaan($id)->row_array();
        $data['type'] = $type;
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('rekamMedis/monitoring', $data);
        $this->load->view('properti/footer', $data);
    }

    public function monitoringapotik()
    {
        $type = $this->input->get('type');
        if (empty($type)) {
            echo 'Invalid request';
            exit();
        }
        $data['tanggal'] = $this->input->post('tanggal');
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['pasien'] = $this->M_rekamMedis->monitoringapotik($type)->result_array();
        //$data['pelayanan'] = $this->db->query("select erm_pemeriksaan_fisik.obat,erm_pemeriksaan_fisik.case_id from erm_pemeriksaan_fisik join Cases on erm_pemeriksaan_fisik.case_id = Cases.[Case ID]")->result_array();
        $data['poli'] = $this->M_anamnesa->poli()->result_array();
        $data['dokter'] = $this->M_anamnesa->dokter()->result_array();
        //$data['hasilpemeriksaan'] = $this->M_rekamMedis->hasilpemeriksaan($id)->row_array();
        $data['type'] = $type;

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

    public function penghapusanrecord()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tanggal = date('Y-m-d');
        $data['tanggal'] = $tanggal;
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $user = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        // =================================================================================
        if ($user['dept'] == 1 || $user['dept'] == 13) {
            $data['record'] = $this->M_rekamMedis->record1($tanggal)->result_array();
        } else if ($user['dept'] == 2) {
            $data['record'] = $this->M_rekamMedis->record2($tanggal)->result_array();
        }
        // =================================================================================
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('rekamMedis/deleterecord', $data);
        $this->load->view('properti/footer', $data);
    }

    public function filterdelete()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tanggal = date('Y-m-d');
        $data['tanggal'] = $tanggal;
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $user = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        $data['record'] = $this->M_rekamMedis->filter()->result_array();

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

    public function prosesMonitoring()
    {
        date_default_timezone_set("Asia/jakarta");
        $tgl = date('Y-m-d');

        $username = $this->session->userdata('username');

        $id = $this->input->get('ermId');
        if (empty($id)) {
            echo 'Invalid Request';
            exit();
        }
        $header = $this->input->get('header');
        $caseId = $this->input->get('c');
        if (isset($id)) {

            $this->db->query("UPDATE erm_pemeriksaan_fisik SET status = 2 , modifiedDate = '$tgl', modifiedBy = '$username'  WHERE erm_pemeriksaan_fisik_id= '$id'");
            $this->db->query("UPDATE pemeriksaanRecord SET status = 2 , modifiedDate = '$tgl', modifiedBy = '$username'  WHERE caseId= '$caseId' and header = '$header'");
            $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data berhasil diproses.</div>');
            redirect('rekamMedis/monitoring?type=' . strtolower($header));
        } else {
            $this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert"> Data gagal diproses.</div>');
            redirect('rekamMedis/monitoring?type=' . strtolower($header));
        }
    }

    public function deletepemeriksaan($id)
    {
        $this->db->delete('erm_pemeriksaan_fisik', ['case_id' => $id]);
        $this->db->delete('pemeriksaanRecord', ['caseid' => $id]);
        $this->db->delete('Cases', ['([Case ID]) =' => $id]);
        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil Dihapus </div>');
        redirect('rekamMedis/penghapusanrecord');
    }

    public function prosesBulkMonitoring()
    {
        date_default_timezone_set("Asia/jakarta");
        $tgl = date('Y-m-d');

        $username = $this->session->userdata('username');
        $proses = $this->input->post('proses');
        if (isset($proses)) {
            for ($x = 0; $x < count($proses); $x++) {
                $data = explode("#", $proses[$x]);
                $id = $data[0];
                $caseId = $data[1];
                $header = $data[2];
                $this->db->query("UPDATE erm_pemeriksaan_fisik SET status = 2 , modifiedDate = '$tgl', modifiedBy = '$username'  WHERE erm_pemeriksaan_fisik_id= '$id'");
                $this->db->query("UPDATE pemeriksaanRecord SET status = 2 , modifiedDate = '$tgl', modifiedBy = '$username'  WHERE caseId= '$caseId' and header = '$header'");
            }

            $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data berhasil diproses.</div>');
            redirect('rekamMedis/monitoring/');
        }

        echo 'Invalid Request';
        exit();
    }

    public function prosesdeletefilter()
    {
        $username = $this->session->userdata('username');
        $proses = $this->input->post('proses');
        if (isset($proses)) {
            for ($x = 0; $x < count($proses); $x++) {
                $data = explode("#", $proses[$x]);
                $caseId = $data[0];
                $this->db->delete('erm_pemeriksaan_fisik', ['case_id' => $caseId]);
                $this->db->delete('pemeriksaanRecord', ['caseid' => $caseId]);
                $this->db->delete('Cases', ['([Case ID]) =' => $caseId]);
            }

            $this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert"> Data berhasil di Hapus.</div>');
            redirect('rekamMedis/penghapusanrecord');
        }

        echo 'Invalid Request';
        exit();
    }

    public function prosesdeletefilter1()
    {
        date_default_timezone_set("Asia/jakarta");
        $tgl = date('Y-m-d');
        $username = $this->session->userdata('username');

        $caseId = $this->input->get('caseid');
        if (empty($caseId)) {
            echo 'Invalid Request';
            exit();
        }
        $caseId = $this->input->get('c');
        if (isset($caseId)) {

            $this->db->delete('erm_pemeriksaan_fisik', ['case_id' => $caseId]);
            $this->db->delete('pemeriksaanRecord', ['caseid' => $caseId]);
            $this->db->delete('Cases', ['([Case ID]) =' => $caseId]);
            $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data berhasil dihapus.</div>');
            redirect('rekamMedis/penghapusanrecord');
        } else {
            $this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert"> Data gagal dihapus.</div>');
            redirect('rekamMedis/penghapusanrecord');
        }
    }

    public function add()
    {
        $user = $this->session->userdata('username');
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $caseID = $this->input->post('caseID');
        $PatientCode = $this->input->post('PatientCode');

        $kondisi = $this->M_rekamMedis->countCaseDetail($caseID)->num_rows();
        //$this->db->query("UPDATE Cases SET Pelayanan = '1' WHERE [Case ID] = '$caseID'");

        if ($kondisi > 0) {
            redirect('rekamMedis/pemeriksaan/' . $caseID . '/' . $PatientCode);
        } else {
            $this->db->query("INSERT INTO tabelCaseDetail ([Case ID],[Intake Date], userCreated, PatientCode) VALUES ('$caseID','$tgl','$user','$PatientCode')");
            $this->db->query("INSERT INTO tabelTaskID ([Case ID],[TaskID]) VALUES ('$caseID','1')");
            redirect('rekamMedis/pemeriksaan/' . $caseID . '/' . $PatientCode);
        }
    }

    public function pemeriksaan($id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        $data['pasien'] = $this->M_rekamMedis->pemeriksaan($id)->row_array();
        // =================================================================================
        $data['dosis'] = $this->M_rekamMedis->dosis()->result_array();
        $data['caraPakai'] = $this->M_rekamMedis->CaraPakai()->result_array();
        $data['pharmacy'] = $this->M_rekamMedis->pharmacy()->result_array();
        $data['obat'] = $this->M_rekamMedis->obatparmasi($id)->result_array();
        $data['trxheader'] = $this->M_rekamMedis->headernonracik($id)->result_array();
        $data['trxheaderRacik'] = $this->M_rekamMedis->trxheaderRacik($id)->result_array();
        $data['obatmodal'] = $this->M_rekamMedis->obatmodal()->result_array();
        $data['cppt'] = $this->M_rekamMedis->historicppt($id)->result_array();
        // =================================================================================
        $data['element'] = $this->M_rekamMedis->ElementGigi()->result_array();
        // =================================================================================
        $data['tab'] = $this->M_rekamMedis->tab($id)->row_array();
        // =================================================================================
        $data['hasilpemeriksaan'] = $this->M_rekamMedis->hasilpemeriksaan($id)->row_array();
        $data['countPemeriksaan'] = $this->M_rekamMedis->hasilpemeriksaan($id)->num_rows();
        $data['poli'] = $this->M_rekamMedis->getPoli($id)->result_array();
        $data['diagnosa'] = $this->M_rekamMedis->diagnosa();
        //$data['diagnosa'] = $this->M_rekamMedis->diagnosa()->result_array();
        $data['histori'] = $this->M_rekamMedis->getCasesByPatientCode($data['pasien']['PatientCode'])->result_array();
        $data['pasien'] = $this->M_rekamMedis->pemeriksaan($id)->row_array();
        // =================================================================================
        $data['hasilDiagnosa'] = $this->M_rekamMedis->hasilDiagnosa($id)->row_array();
        $data['countDiagnosa'] = $this->M_rekamMedis->hasilDiagnosa($id)->num_rows();
        // =================================================================================
        $data['hasilRujukan'] = $this->M_rekamMedis->hasilRujukan($id)->row_array();
        $data['countRujukan'] = $this->M_rekamMedis->hasilRujukan($id)->num_rows();
        // =================================================================================
        $data['hasilTindakan'] = $this->M_rekamMedis->hasilTindakan($id)->row_array();
        $data['countTindakan'] = $this->M_rekamMedis->hasilTindakan($id)->num_rows();
        // =================================================================================
        $data['hasilObat'] = $this->M_rekamMedis->hasilObat($id)->result_array();
        $data['countObat'] = $this->M_rekamMedis->hasilObat($id)->num_rows();
        // =================================================================================
        $data['hasilLaboratory'] = $this->M_rekamMedis->hasilLaboratory($id)->row_array();
        $data['countLaboratory'] = $this->M_rekamMedis->hasilLaboratory($id)->num_rows();
        // =================================================================================
        $data['usiakehamilan'] = $this->M_rekamMedis->usiakehamilan()->result_array();
        $data['jenisimunisasi'] = $this->M_rekamMedis->jenisimunisasi()->result_array();
        $data['jeniskb'] = $this->M_rekamMedis->jeniskb()->result_array();
        $data['HeaderLab'] = $this->M_rekamMedis->HeaderLab($id)->row_array();
        $data['HasilLab'] = $this->M_rekamMedis->HasilLab($id)->result_array();


        $tglListHeader = $this->input->get('tglRequest');
        $data['tglRequest'] = $tglListHeader;
        $whereTglListHeader = "";
        $data['tabLab'] = '';
        if (!empty($tglListHeader)) {
            $whereTglListHeader = "and tglRequest = '$tglListHeader'";
            $data['tabLab'] = 'active';
        }

        $data['listHeader'] = $this->db->query("select tglRequest  from LabRequestHeader where CaseID  = '$id' group by tglRequest ")->result_array();

        $data['list'] = $this->db->query("select lh.CaseID, lh.IdRequestHeader, lh.tglRequest, ld.PackedID, pd.Description, lh.status
        from LabRequestHeader lh join LabRequestDetail ld on lh.IdRequestHeader = ld.IdRequestHeader
        join tblLabPacked pd on pd.PackedID = ld.PackedID
        where lh.CaseID = '$id'  " . $whereTglListHeader)->result_array();

        $data['viewlab'] = $this->db->query("SELECT td.LabNo,td.ResultID,td.Bahasa,td.ResultValue,td.Normalvalue
        from tblLabResult tr 
        JOIN tblLabResultDetail td on tr.LabNo = td.LabNo
        where tr.caseid = '$id'")->result_array();
        $data['paket'] = $this->db->query("select PackedID as code, Description as description,CategoryID from tblLabPacked")->result_array();
        // =================================================================================






        //print_r($data['hasilLaboratory'] );exit();
        // --- riki
        $cpptCase = $this->uri->segment(3);
        $mr = $this->uri->segment(4);



        // $data['countHeaderCppt'] = $this->db->query("SELECT * FROM HeaderCppt WHERE Mr='$mr' AND Note = '1'")->num_rows();
        $data['headerCppt'] = $headerCppt = $this->db->query("SELECT * FROM HeaderCppt WHERE Mr='$mr' ORDER BY IdHeader DESC")->row_array();
        $IdHeaderCppt = $headerCppt['IdHeader'];
        $data['listCppt'] = $this->db->query("SELECT * FROM DetailCppt WHERE IdHeader = '$IdHeaderCppt'")->result_array();
        $data['cpptCase'] = $this->db->query("SELECT * FROM DetailCppt WHERE CaseId = '$cpptCase' ORDER BY IdDetail DESC")->row_array();




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

    public function xupdatepemeriksaan($id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        $data['pasien'] = $this->M_rekamMedis->pemeriksaan($id)->row_array();
        // =================================================================================
        $data['dosis'] = $this->M_rekamMedis->dosis()->result_array();
        $data['caraPakai'] = $this->M_rekamMedis->CaraPakai()->result_array();
        $data['pharmacy'] = $this->M_rekamMedis->pharmacy()->result_array();
        $data['obat'] = $this->M_rekamMedis->obatparmasi($id)->result_array();
        $data['obatmodal'] = $this->M_rekamMedis->obatmodal()->result_array();
        $data['tampilracik'] = $this->M_rekamMedis->tampilracik($id)->result_array();
        $data['headerRacik'] = $this->M_rekamMedis->headerRacik($id)->row_array();
        // =================================================================================
        $data['element'] = $this->M_rekamMedis->ElementGigi()->result_array();
        // =================================================================================
        $data['tab'] = $this->M_rekamMedis->tab($id)->row_array();
        // =================================================================================
        $data['hasilpemeriksaan'] = $this->M_rekamMedis->hasilpemeriksaan($id)->row_array();
        $data['countPemeriksaan'] = $this->M_rekamMedis->hasilpemeriksaan($id)->num_rows();
        $data['poli'] = $this->M_rekamMedis->getPoli($id)->result_array();
        $data['diagnosa'] = $this->M_rekamMedis->diagnosa();
        //$data['diagnosa'] = $this->M_rekamMedis->diagnosa()->result_array();
        $data['histori'] = $this->M_rekamMedis->getCasesByPatientCode($data['pasien']['PatientCode'])->result_array();
        $data['pasien'] = $this->M_rekamMedis->pemeriksaan($id)->row_array();
        // =================================================================================
        $data['hasilDiagnosa'] = $this->M_rekamMedis->hasilDiagnosa($id)->row_array();
        $data['countDiagnosa'] = $this->M_rekamMedis->hasilDiagnosa($id)->num_rows();
        // =================================================================================
        $data['hasilRujukan'] = $this->M_rekamMedis->hasilRujukan($id)->row_array();
        $data['countRujukan'] = $this->M_rekamMedis->hasilRujukan($id)->num_rows();
        // =================================================================================
        $data['hasilTindakan'] = $this->M_rekamMedis->hasilTindakan($id)->row_array();
        $data['countTindakan'] = $this->M_rekamMedis->hasilTindakan($id)->num_rows();
        // =================================================================================
        $data['hasilObat'] = $this->M_rekamMedis->hasilObat($id)->result_array();
        $data['countObat'] = $this->M_rekamMedis->hasilObat($id)->num_rows();
        // =================================================================================
        $data['hasilLaboratory'] = $this->M_rekamMedis->hasilLaboratory($id)->row_array();
        $data['countLaboratory'] = $this->M_rekamMedis->hasilLaboratory($id)->num_rows();
        // =================================================================================
        $data['usiakehamilan'] = $this->M_rekamMedis->usiakehamilan()->result_array();
        $data['jenisimunisasi'] = $this->M_rekamMedis->jenisimunisasi()->result_array();
        $data['jeniskb'] = $this->M_rekamMedis->jeniskb()->result_array();
        $data['HeaderLab'] = $this->M_rekamMedis->HeaderLab($id)->row_array();
        $data['HasilLab'] = $this->M_rekamMedis->HasilLab($id)->result_array();
        $data['list'] = $this->db->query("select lh.CaseID, lh.IdRequestHeader, ld.PackedID, pd.Description, lh.status
        from LabRequestHeader lh join LabRequestDetail ld on lh.IdRequestHeader = ld.IdRequestHeader
        join tblLabPacked pd on pd.PackedID = ld.PackedID
        where lh.CaseID = '$id' ")->result_array();
        $data['viewlab'] = $this->db->query("SELECT td.LabNo,td.ResultID,td.Bahasa,td.ResultValue,td.Normalvalue
        from tblLabResult tr 
        JOIN tblLabResultDetail td on tr.LabNo = td.LabNo
        where tr.caseid = '$id'")->result_array();
        $data['paket'] = $this->db->query("select PackedID as code, Description as description,CategoryID from tblLabPacked")->result_array();
        // =================================================================================

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

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

    public function prosesPemeriksaan()
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $CaseID = $this->input->post('CaseID');
        $user =  $this->session->userdata('username');
        $poli = $this->input->post('poli');
        $keluhanUtama = $this->input->post('keluhanUtama');
        $penyakitTerdahulu = $this->input->post('penyakitTerdahulu');
        $pemeriksaanFisik = str_replace("'", "''", $this->input->post('pemeriksaanFisik'));
        $diagnosaPrimer = $this->input->post('txtCariIdDiagnosa');
        $diagnosaSekunder = $this->input->post('txtCariIdDiagnosa1');
        $usiakehamilan = $this->input->post('usiakehamilan');
        $jenisimunisasi = $this->input->post('jenisimunisasi');
        $jeniskb = $this->input->post('jeniskb');
        $paneldiagnosa = $this->input->post('paneldiagnosa');
        $rencanaTindakan = $this->input->post('rencanaTindakan');
        $tindakLanjut = $this->input->post('tindakLanjut');
        $catatan = $this->input->post('catatan');
        $obat = $this->input->post('obat');
        $alergi = $this->input->post('alergi');
        $tanggalKontrol = $this->input->post('tanggalKontrol');
        $tanggalMeninggal = $this->input->post('tanggalMeninggal');
        $poliTujuan = $this->input->post('poliTujuan');
        $instansiTujuan = $this->input->post('instansiTujuan');

        $titleTindakanMedis = $this->input->post('titleTindakanMedis');
        //print_r( $titleTindakanMedis);exit();
        $namadiagnosa = $this->db->query("Select DESCRPTION from ICD9 where ICD_CODE = '$diagnosaPrimer'")->row_array();
        $nmdiagnosa = $namadiagnosa['DESCRPTION'];
        //$this->db->query("INSERT INTO tabelPemeriksaan ([Case ID],CatatanFisik,Catatan,Alergi) VALUES ('$CaseID','$CatatanFisik','$Catatan','$Alergi')");
        $insert = $this->db->query("INSERT INTO erm_pemeriksaan_fisik (case_id,poli,keluhan_utama,penyakit_terdahulu,pemeriksaan_fisik,diagnosa_primer,diagnosa_sekunder,rencana_tindakan,tindak_lanjut,catatan, alergi, tanggal_kontrol, tanggal_meninggal, poli_tujuan, instansi_tujuan, obat, createdBy, modifiedBy,kdhamil,kdimunisasi,kdkb,paneldiag) 
        VALUES ('$CaseID','$poli','$keluhanUtama','$penyakitTerdahulu','$pemeriksaanFisik','$diagnosaPrimer','$diagnosaSekunder','$rencanaTindakan','$tindakLanjut','$catatan','$alergi','$tanggalKontrol','$tanggalMeninggal','$poliTujuan','$instansiTujuan', '$obat', '$user', '$user', '$usiakehamilan', '$jenisimunisasi', '$jeniskb', '$paneldiagnosa')");
        $ermPemeriksaanFisikId =  $this->db->insert_id();
        $this->db->query("UPDATE tabelTaskID SET TaskID = '1' WHERE [Case ID] = '$CaseID'");
        $this->db->query("UPDATE Cases SET [ICD_Code] = '$diagnosaPrimer', [Presenting Problem] = '$nmdiagnosa', [Pelayanan] = '1' WHERE [Case ID] = '$CaseID'");

        $titleTindakanMedis = $this->input->post('titleTindakanMedis');
        $tindakanMedis = $this->input->post('tindakanMedis');
        $image = $this->input->post('image');
        //var_dump($image);exit();

        if (isset($_FILES['image'])) {
            $files = $_FILES;
            $cpt = count($_FILES['image']['name']);
            for ($x = 0; $x < $cpt; $x++) {
                $imageName = round(microtime(true) * 1000) . $x . '.jpg';


                $_FILES['image']['name'] = $imageName;
                $_FILES['image']['type'] = $files['image']['type'][$x];
                $_FILES['image']['tmp_name'] = $files['image']['tmp_name'][$x];
                $_FILES['image']['error'] = $files['image']['error'][$x];
                $_FILES['image']['size'] = $files['image']['size'][$x];

                //upload image multiple
                $config['upload_path']          = FCPATH . '/upload-tindakan-medis/';
                $config['allowed_types']        = 'gif|jpg|png|jpeg';
                $config['file_name']        = $imageName;
                $config['max_size']             = 4096;
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if ($this->upload->do_upload('image')) {
                    $this->db->query("INSERT INTO erm_pemeriksaan_fisik_image (ermPemeriksaanFisikId, caseId, title, description, image ) values ('$ermPemeriksaanFisikId','$CaseID','$titleTindakanMedis[$x]', '$tindakanMedis[$x]', '$imageName')   ");
                } else {
                    $errors = $this->upload->display_errors();
                    //print_r($errors);exit();
                    $this->session->set_flashdata('message', "<div class='alert alert-warning' role='alert'> Data gagal di simpan, image upload gagal $errors .</div>");
                    redirect('rekamMedis/pemeriksaan/' . $CaseID);
                }
            }
        }
        $bpjsAntrian = $this->db->query("select * from BPJS_Antrian ba where CaseID = '$CaseID'")->row_array();

        $newDatePeriksa = date("Y-m-d", strtotime($bpjsAntrian['TanggalPeriksa']));

        // send antrean panggil
        $payloadPanggil = [
            "tanggalperiksa" => $newDatePeriksa,
            "kodepoli" => $bpjsAntrian['KodePoli'],
            "nomorkartu" => $bpjsAntrian['NomorKartu'],
            "status" => 1, // hadir
            "waktu" => intval(microtime(true) * 1000),
        ];

        //$this->SendAntreanPanggil($payloadPanggil);


        if (!empty($obat)) {
            $this->db->query("INSERT INTO pemeriksaanRecord (caseId,header,status,createdBy, modifiedBy) VALUES ('$CaseID','APOTIK','1','$user','$user')");
        }

        $this->session->set_flashdata('message', "<div class='alert alert-success' role='alert'> Data Berhasil disimpan.</div>");
        redirect('rekamMedis/pemeriksaan/' . $CaseID);
    }

    public function SendAntreanPanggil($payload)
    {

        $ch = curl_init();
        $abdulradjak = $this->M_BpjsID->abdulradjak()->row_array();
        $payload = json_encode($payload);

        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'] . "WsBpjsAntreanFktp/updateStatusPanggilAntrean");
        $result = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result, true);
    }



    public function updatePemeriksaan($id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();

        $poli = $this->input->post('poli');
        $keluhanUtama = $this->input->post('keluhanUtama');
        $penyakitTerdahulu = $this->input->post('penyakitTerdahulu');
        $pemeriksaanFisik = $this->input->post('pemeriksaanFisik');
        $diagnosaPrimer = $this->input->post('txtCariIdDiagnosa');
        $diagnosaSekunder = $this->input->post('txtCariIdDiagnosa1');
        $usiakehamilan = $this->input->post('usiakehamilan');
        $jenisimunisasi = $this->input->post('jenisimunisasi');
        $jeniskb = $this->input->post('jeniskb');
        $paneldiagnosa = $this->input->post('paneldiagnosa');
        $rencanaTindakan = $this->input->post('rencanaTindakan');
        $tindakLanjut = $this->input->post('tindakLanjut');
        $catatan = $this->input->post('catatan');
        $obat = $this->input->post('obat');
        $alergi = $this->input->post('alergi');
        $tanggalKontrol = $this->input->post('tanggalKontrol');
        $tanggalMeninggal = $this->input->post('tanggalMeninggal');
        $poliTujuan = $this->input->post('poliTujuan');
        $instansiTujuan = $this->input->post('instansiTujuan');

        $this->db->query("UPDATE erm_pemeriksaan_fisik 
        SET 
        poli = '$poli',
        keluhan_utama = '$keluhanUtama', 
        penyakit_terdahulu = '$penyakitTerdahulu' ,
        pemeriksaan_fisik = '$pemeriksaanFisik' ,
        diagnosa_primer = '$diagnosaPrimer' ,
        diagnosa_sekunder = '$diagnosaSekunder' ,
        rencana_tindakan = '$rencanaTindakan' ,
        tindak_lanjut = '$tindakLanjut' ,
        catatan = '$catatan' ,
        obat = '$obat' ,
        alergi = '$alergi', 
        tanggal_kontrol = '$tanggalKontrol' ,
        tanggal_meninggal = '$tanggalMeninggal' ,
        poli_tujuan = '$poliTujuan' ,
        instansi_tujuan = '$instansiTujuan',
        kdhamil = '$usiakehamilan',
        kdimunisasi = '$jenisimunisasi',
        kdkb = '$jeniskb',
        paneldiag = '$paneldiagnosa'
        WHERE case_id = '$id'");

        $namadiagnosa = $this->db->query("Select DESCRPTION from ICD9 where ICD_CODE = '$diagnosaPrimer'")->row_array();
        $nmdiagnosa = addslashes($namadiagnosa['DESCRPTION']);

        $bpjsAntrian = $this->db->query("select * from BPJS_Antrian ba where CaseID = '$id'")->row_array();

        $newDatePeriksa = date("Y-m-d", strtotime($bpjsAntrian['TanggalPeriksa']));

        // send antrean panggil
        $payloadPanggil = [
            "tanggalperiksa" => $newDatePeriksa,
            "kodepoli" => $bpjsAntrian['KodePoli'],
            "nomorkartu" => $bpjsAntrian['NomorKartu'],
            "status" => 1, // hadir
            "waktu" => intval(microtime(true) * 1000),
        ];

        $this->SendAntreanPanggil($payloadPanggil);

        $this->db->query("UPDATE tabelTaskID SET TaskID = '1' WHERE [Case ID] = '$id'");
        $this->db->query("UPDATE Cases SET [ICD_Code] = '$diagnosaPrimer', [Presenting Problem] = '$nmdiagnosa' WHERE [Case ID] = '$id'");
        redirect('rekamMedis/pemeriksaan/' . $id);
    }

    // =================================================================================

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

    public function editDiagnosa($id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        $data['pasien'] = $this->M_rekamMedis->pemeriksaan($id)->row_array();
        // =================================================================================
        $data['diagnosa'] = $this->M_rekamMedis->diagnosa()->result_array();
        $data['codediagnosa'] = $this->M_rekamMedis->codediagnosa($id)->row_array();
        // =================================================================================
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('rekamMedis/editDiagnosa', $data);
        $this->load->view('properti/footer', $data);
    }

    public function prosesDiagnosa()
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $caseID = $this->input->post('caseID');
        $Diagnosa = $this->input->post('Diagnosa');
        $this->db->query("INSERT INTO tabelDiagnosa ([Case ID],ICD_Code) VALUES ('$caseID','$Diagnosa')");
        $this->db->query("UPDATE tabelTaskID SET TaskID = '2' WHERE [Case ID] = '$caseID'");
        redirect('rekamMedis/pemeriksaan/' . $caseID);
    }

    public function updateDiagnosa($id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $Diagnosa = $this->input->post('Diagnosa');

        $this->db->query("UPDATE tabelDiagnosa SET ICD_Code = '$Diagnosa' WHERE [Case ID] = '$id'");
        $this->db->query("UPDATE tabelTaskID SET TaskID = '2' WHERE [Case ID] = '$id'");
        redirect('rekamMedis/pemeriksaan/' . $id);
    }

    // =================================================================================

    public function prosesRujukan()
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $CaseID = $this->input->post('CaseID');
        $Rujukan = $this->input->post('Rujukan');
        $Poli = $this->input->post('Poli');

        $this->db->query("INSERT INTO tabelRujukan ([Case ID],Rujukan,Poli) VALUES ('$CaseID','$Rujukan','$Poli')");
        $this->db->query("UPDATE tabelTaskID SET TaskID = '3' WHERE [Case ID] = '$CaseID'");
        redirect('rekamMedis/pemeriksaan/' . $CaseID);
    }

    public function updateRujukan($id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $Rujukan = $this->input->post('Rujukan');
        $Poli = $this->input->post('Poli');

        $this->db->query("UPDATE tabelRujukan SET Rujukan = '$Rujukan', Poli = '$Poli' WHERE [Case ID] = '$id'");
        $this->db->query("UPDATE tabelTaskID SET TaskID = '3' WHERE [Case ID] = '$id'");
        redirect('rekamMedis/pemeriksaan/' . $id);
    }

    // =================================================================================

    public function prosesTindakan()
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $CaseID = $this->input->post('CaseID');
        $Tindakan = $this->input->post('Tindakan');

        $this->db->query("INSERT INTO tabelTindakan ([Case ID],Tindakan) VALUES ('$CaseID','$Tindakan')");
        $this->db->query("UPDATE tabelTaskID SET TaskID = '4' WHERE [Case ID] = '$CaseID'");
        redirect('rekamMedis/pemeriksaan/' . $CaseID);
    }

    public function updateTindakan($id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $Tindakan = $this->input->post('Tindakan');

        $this->db->query("UPDATE tabelTindakan SET Tindakan = '$Tindakan' WHERE [Case ID] = '$id'");
        $this->db->query("UPDATE tabelTaskID SET TaskID = '4' WHERE [Case ID] = '$id'");
        redirect('rekamMedis/pemeriksaan/' . $id);
    }

    // =================================================================================

    public function prosesObat()
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $CaseID = $this->input->post('CaseID');
        $Obat = $this->input->post('Obat');
        $Satuan = $this->input->post('Satuan');
        $Dosis = $this->input->post('Dosis');
        $Jumlah = $this->input->post('Jumlah');
        $CaraPakai = $this->input->post('CaraPakai');

        $this->db->query("INSERT INTO tabelObat ([Case ID],Obat,Satuan,Dosis,Jumlah,CaraPakai) VALUES ('$CaseID','$Obat','$Satuan','$Dosis','$Jumlah','$CaraPakai')");
        $this->db->query("UPDATE tabelTaskID SET TaskID = '5' WHERE [Case ID] = '$CaseID'");
        redirect('rekamMedis/pemeriksaan/' . $CaseID);
    }

    public function hapusObat($id, $case)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();

        $this->db->query("DELETE FROM tabelObat WHERE id = '$id'");
        $this->db->query("UPDATE tabelTaskID SET TaskID = '5' WHERE [Case ID] = '$case'");
        redirect('rekamMedis/pemeriksaan/' . $case);
    }

    // =================================================================================

    public function prosesLaboratory()
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $CaseID = $this->input->post('CaseID');
        $Hematologi = $this->input->post('Hematologi');
        $Serologi = $this->input->post('Serologi');
        $KimiaDarah = $this->input->post('KimiaDarah');
        $Urinalisa = $this->input->post('Urinalisa');
        $FungsiGinjal = $this->input->post('FungsiGinjal');
        $Lemak = $this->input->post('Lemak');
        $TestGula = $this->input->post('TestGula');
        $TestKehamilan = $this->input->post('TestKehamilan');
        $Lainnya = $this->input->post('Lainnya');
        $DarahLengkap = $this->input->post('DarahLengkap');

        $this->db->query("INSERT INTO tabelLaboratory ([Case ID],Hematologi,Serologi,KimiaDarah,Urinalisa,FungsiGinjal,Lemak,TestKehamilan,TestGula,Lainnya,DarahLengkap) VALUES ('$CaseID','$Hematologi','$Serologi','$KimiaDarah','$Urinalisa','$FungsiGinjal','$Lemak','$TestGula','$TestKehamilan','$Lainnya','$DarahLengkap')");
        $this->db->query("UPDATE tabelTaskID SET TaskID = '6' WHERE [Case ID] = '$CaseID'");

        $user =  $this->session->userdata('username');
        $this->db->query("INSERT INTO pemeriksaanRecord (caseId,header,status,createdBy,modifiedBy) VALUES ('$CaseID','LAB','1','$user','$user')");
        redirect('rekamMedis/pemeriksaan/' . $CaseID);
    }

    public function updateLaboratory($id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $Hematologi = $this->input->post('Hematologi');
        $Serologi = $this->input->post('Serologi');
        $KimiaDarah = $this->input->post('KimiaDarah');
        $Urinalisa = $this->input->post('Urinalisa');
        $FungsiGinjal = $this->input->post('FungsiGinjal');
        $Lemak = $this->input->post('Lemak');
        $TestGula = $this->input->post('TestGula');
        $TestKehamilan = $this->input->post('TestKehamilan');
        $Lainnya = $this->input->post('Lainnya');
        $DarahLengkap = $this->input->post('DarahLengkap');

        $this->db->query("UPDATE tabelLaboratory SET Hematologi = '$Hematologi',Serologi='$Serologi',KimiaDarah='$KimiaDarah',Urinalisa='$Urinalisa',FungsiGinjal='$FungsiGinjal',Lemak='$Lemak',TestKehamilan='$TestKehamilan',TestGula='$TestGula',Lainnya='$Lainnya', DarahLengkap = '$DarahLengkap' WHERE [Case ID] = '$id'");
        $this->db->query("UPDATE tabelTaskID SET TaskID = '6' WHERE [Case ID] = '$id'");
        redirect('rekamMedis/pemeriksaan/' . $id);
    }

    public function cetakRekamMedis($id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Cetak Rekam Medis";
        $data['utama'] = $this->db->query('SELECT * FROM Utama')->row_array();
        $data['pasien'] = $this->M_rekamMedis->pemeriksaan($id)->row_array();
        $data['lokasi'] = $this->M_rekamMedis->getErmSetting('LOKASI')->row_array()['value'];
        // =================================================================================
        $data['hasilpemeriksaan'] = $this->M_rekamMedis->hasilpemeriksaan($id)->row_array();
        $data['countPemeriksaan'] = $this->M_rekamMedis->hasilpemeriksaan($id)->num_rows();
        $data['pemeriksaangigi'] = $this->M_rekamMedis->hasilpemeriksaangigi($id)->row_array();
        // =================================================================================
        $data['hasilDiagnosa'] = $this->M_rekamMedis->hasilDiagnosa($id)->row_array();
        $data['countDiagnosa'] = $this->M_rekamMedis->hasilDiagnosa($id)->num_rows();
        // =================================================================================
        $data['hasilRujukan'] = $this->M_rekamMedis->hasilRujukan($id)->row_array();
        $data['countRujukan'] = $this->M_rekamMedis->hasilRujukan($id)->num_rows();
        // =================================================================================
        $data['hasilTindakan'] = $this->M_rekamMedis->hasilTindakan($id)->row_array();
        $data['countTindakan'] = $this->M_rekamMedis->hasilTindakan($id)->num_rows();
        // =================================================================================
        $data['hasilObat'] = $this->M_rekamMedis->hasilObat($id)->result_array();
        $data['countObat'] = $this->M_rekamMedis->hasilObat($id)->num_rows();
        $data['nonracik'] = $this->M_rekamMedis->Obatnonracik($id)->result_array();
        $data['racikan'] = $this->M_rekamMedis->Obatracikan($id)->result_array();
        // =================================================================================
        $data['hasilLaboratory'] = $this->M_rekamMedis->hasilLaboratory($id)->row_array();
        $data['countLaboratory'] = $this->M_rekamMedis->hasilLaboratory($id)->num_rows();
        // =================================================================================
        $data['usiahamil'] = $this->db->query("Select e.kdhamil,u.Description from erm_pemeriksaan_fisik e join Usia_hamil u on e.kdhamil = u.KodeUsia where e.case_id = '$id'")->row_array();
        $data['imunisasi'] = $this->db->query("Select e.kdimunisasi,j.Description from erm_pemeriksaan_fisik e 
        join Jenis_Imunisasi j on e.kdimunisasi = j.Kodeimun  where e.case_id = '$id'")->row_array();
        $data['kb'] = $this->db->query("Select e.kdkb,j.Description from erm_pemeriksaan_fisik e 
        join Jenis_KB j on e.kdimunisasi = j.KodeKB  where e.case_id = '$id'")->row_array();
        //===================================================================================
        $this->load->view('rekamMedis/cetakRekamMedis', $data);
    }

    // =================================================================================

    public function histori($mr, $id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        $data['pasien'] = $this->M_rekamMedis->pemeriksaan($id)->row_array();
        $data['histori'] = $this->M_rekamMedis->histori($mr)->row_array();
        $data['Chistori'] = $this->M_rekamMedis->histori($mr)->num_rows();
        // =================================================================================
        $id2a = $this->M_rekamMedis->histori($mr)->row_array();
        $id2 = $id;
        // =================================================================================
        $data['hasilpemeriksaan'] = $this->M_rekamMedis->hasilpemeriksaan($id2)->row_array();
        $data['countPemeriksaan'] = $this->M_rekamMedis->hasilpemeriksaan($id2)->num_rows();
        // =================================================================================
        $data['hasilDiagnosa'] = $this->M_rekamMedis->hasilDiagnosa($id2)->row_array();
        $data['countDiagnosa'] = $this->M_rekamMedis->hasilDiagnosa($id2)->num_rows();
        // =================================================================================
        $data['hasilRujukan'] = $this->M_rekamMedis->hasilRujukan($id2)->row_array();
        $data['countRujukan'] = $this->M_rekamMedis->hasilRujukan($id2)->num_rows();
        // =================================================================================
        $data['hasilTindakan'] = $this->M_rekamMedis->hasilTindakan($id2)->row_array();
        $data['countTindakan'] = $this->M_rekamMedis->hasilTindakan($id2)->num_rows();
        // =================================================================================
        $data['hasilObat'] = $this->M_rekamMedis->hasilObat($id2)->result_array();
        $data['countObat'] = $this->M_rekamMedis->hasilObat($id2)->num_rows();
        // =================================================================================
        $data['hasilLaboratory'] = $this->M_rekamMedis->hasilLaboratory($id2)->row_array();
        $data['countLaboratory'] = $this->M_rekamMedis->hasilLaboratory($id2)->num_rows();
        $data['pemeriksaangigi'] = $this->M_rekamMedis->hasilpemeriksaangigi($id2)->row_array();
        // =================================================================================
        $data['usiahamil'] = $this->db->query("Select e.kdhamil,u.Description from erm_pemeriksaan_fisik e join Usia_hamil u on e.kdhamil = u.KodeUsia where e.case_id = '$id2'")->row_array();
        $data['imunisasi'] = $this->db->query("Select e.kdimunisasi,j.Description from erm_pemeriksaan_fisik e 
        join Jenis_Imunisasi j on e.kdimunisasi = j.Kodeimun  where e.case_id = '$id2'")->row_array();
        $data['kb'] = $this->db->query("Select e.kdkb,j.Description from erm_pemeriksaan_fisik e 
        join Jenis_KB j on e.kdimunisasi = j.KodeKB  where e.case_id = '$id2'")->row_array();
        //==================================================================================
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('rekamMedis/histori', $data);
        $this->load->view('properti/footer', $data);
    }

    // =================================================================================

    public function cariMr()
    {
        extract($_GET);
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        // =================================================================================
        $data['cariMr'] = $this->M_rekamMedis->cariMr($mr)->result_array();
        // =================================================================================
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('rekamMedis/cariMr', $data);
        $this->load->view('properti/footer', $data);
    }

    public function cariCppt()
    {
        extract($_GET);
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        $data['cppt'] = $this->db->query("SELECT * FROM HeaderCppt c, Patient p WHERE c.Mr=p.PatientCode AND c.Mr = '$mr'")->result_array();
        // =================================================================================

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

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

    public function detailBerkasCppt($IdHeader)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Cppt";
        $data['listCppt'] = $this->db->query("SELECT * FROM DetailCppt WHERE IdHeader = '$IdHeader'")->result_array();
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('rekamMedis/detailBerkasCppt', $data);
        $this->load->view('properti/footer', $data);
    }
    // =================================================================================

    public function record()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tanggal = date('Y-m-d');
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $user = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        // =================================================================================
        if ($user['dept'] == 1 || $user['dept'] == 13 || $user['dept'] == 4) {
            $data['record'] = $this->M_rekamMedis->record1($tanggal)->result_array();
        } else if ($user['dept'] == 2) {
            $data['record'] = $this->M_rekamMedis->record2($tanggal)->result_array();
        }
        // =================================================================================
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('rekamMedis/record', $data);
        $this->load->view('properti/footer', $data);
    }

    public function tanggal()
    {
        extract($_GET);
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        // =================================================================================
        $data['record'] = $this->M_rekamMedis->record1($tanggal)->result_array();
        // =================================================================================
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('rekamMedis/record', $data);
        $this->load->view('properti/footer', $data);
    }

    // =================================================================================

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

    public function logout()
    {
        $this->session->unset_userdata('username');
        $this->session->unset_userdata('nama');
        $this->session->set_flashdata('message', '<div class="alert alert-warning" role="alert"> Anda telah keluar dari halaman admin.</div>');
        redirect('login');
    }

    public function prosesSaveOdontogram()
    {
        $elemenGigi = $this->input->post('elemenGigi');
        $diagnosa = $this->input->post('diagnosa');
        $prosedur = $this->input->post('prosedur');
        $caseId = $this->input->post('caseId');

        if (empty($elemenGigi) || empty($caseId)) {
            $data = array(
                "success" => 0,
                "message" => "invalid request " . $elemenGigi . " or " . $caseId,
            );
            echo json_encode($data);
        } else {
            $this->db->query("INSERT INTO ermPemeriksaanGigi (elemenGigi,diagnosa,prosedur,caseId) VALUES ('$elemenGigi','$diagnosa','$prosedur','$caseId')");
            $data = array(
                "success" => 1,
                "message" => "Success",
            );
            echo json_encode($data);
        }
    }

    public function loadOdontogram()
    {

        $caseId = $this->input->post('caseId');
        $PatientCode = $this->input->post('PatientCode');
        if (empty($caseId)) {
            $data = array(
                "success" => 0,
                "message" => "invalid request " . $caseId,
            );
            echo json_encode($data);
        } else {
            $query = $this->db->query("Select caseId,elemenGigi,diagnosa,prosedur from ermPemeriksaanGigi e join Cases c on c.[Case ID] = e.caseId
            where c.PatientCode = '$PatientCode'");
            $data = array(
                "success" => 1,
                "data" => $query->result_array(),
                "message" => "Success",
            );
            echo json_encode($data);
        }
    }

    public function hapusOdontogram()
    {

        $id = $this->input->post('id');
        if ($id == "") {
            $data = array(
                "success" => 0,
                "message" => "invalid request " . $id,
            );
            echo json_encode($data);
        } else {
            $query = $this->db->query("delete from ermPemeriksaanGigi where ermPemeriksaanGigiId = '$id'");
            $data = array(
                "success" => 1,
                "message" => "Success",
            );
            echo json_encode($data);
        }
    }


    function GetColorPoli($poli)
    {
        if ($poli == 'POLI BIDAN') {
            return '#1175CB';
        } else if ($poli == 'POLI UMUM') {
            return '#448C18';
        } else if ($poli == 'POLI GIGI') {
            return '#B1C200';
        } else if ($poli == 'POLI BEKAM') {
            return '#CF520B';
        } else {
            return '#4B5A73';
        }
    }

    public function cetakresep($id)
    {
        ob_start();
        $data['utama'] = $this->db->query('SELECT * FROM Utama')->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 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();
        $this->load->view('cetak/cetakobat', $data);
        $isi = ob_get_clean();
        require_once('./aset/html2pdf/html2pdf.class.php');

        try {
            // $width_in_mm = '60';
            // $height_in_mm = '60';

            $html2pdf = new HTML2PDF('P', 'A4', 'en', false, 'ISO-8859-15', array(5, 2, 5, 2));
            // $html2pdf = new HTML2PDF('P', array($width_in_mm, $height_in_mm), 'en', false, 'ISO-8859-15', array(2, 10, 2, 10));
            $html2pdf->writeHTML($isi, isset($_GET['vuehtml']));
            $html2pdf->Output('cover.pdf');
        } catch (HTML2PDF_exception $e) {
            echo $e;
            exit;
        }
    }

    function searchLab()
    {
        $keyword = $this->input->post('keyword');
        $id = $this->input->post('id');
        $obj = $this->db->query("select PackedID as code, Description as description,CategoryID from tblLabPacked Where PackedID like '$keyword%' or Description like '%$keyword%' Order by ProcedureCode ")->result_array();
        $output = '<ul class="list-unstyled ulclass">';
        if (empty($obj)) {
            $output .= "<li class='liclass' onClick=\"setLabCode('empty','$id');\" >Tidak ditemukan</li>";
            $output .= '</ul>';
        } else {
            foreach ($obj as $data) {
                $dataLi =  $data['code'] . ' # ' . $data['description'];
                $output .= "<li class='liclass' onClick=\"setLabCode('$dataLi','$id');\">" . $dataLi . "</li>";
            }
            $output .= '</ul>';
        }

        $response = array(
            "status" => "00",
            "data" => $output
        );
        echo json_encode($response);
        exit();
    }

    public function ProsesLab($id)
    {
        //=======================================================================
        $data['user'] = $user = $this->db->get_where('userV2', ['UserName' => $this->session->userdata('UserName')])->row_array();
        $data['judul'] = "Klinik";
        date_default_timezone_set("Asia/jakarta");
        // ======================================================================
        $caseid      =  $this->input->post('caseid');
        $tanggal     =  date('Y-m-d');
        $jam         =  date('H:i:s');
        $dokter      =  $_POST['DoctorID'];
        $mr          =  $this->input->post('PatientCode');
        $status      =  1;
        $iduri       =  $this->uri->segment(3);
        $PackedID    = $_POST['PackedID'];


        $this->db->query("Insert Into LabRequestHeader(CaseID,tglRequest,jamRequest,dokterKirim,PatientCode,status) VALUES ('$caseid','$tanggal','$jam','$dokter','$mr', '$status')");

        $qdata = $this->db->query("select IdRequestHeader from LabRequestHeader where CaseID = '$id' ")->row_array();
        $idheader = $qdata['IdRequestHeader'];

        $count = count($PackedID);
        for ($x = 0; $x < $count; $x++) {
            $splitX = explode(' ', $PackedID[$x]);
            $this->db->query("INSERT INTO LabRequestDetail (IdRequestHeader,PackedID) VALUES ('$idheader','$splitX[0]')");
        }

        //    $count = count($PackedID);
        //    for ($x = 0; $x < $count; $x++) {
        //     $splitX = explode(' ', $PackedID[$x]);
        //     print_r($splitX[0]);
        //     exit;
        //     $this->db->query("INSERT INTO LabRequestDetail (IdRequestHeader,PackedID) VALUES ('$idheader','$splitX[0]')");
        //    }


        //    $data2 = array();

        //    $index = 0; 
        //    foreach($PackedID as $dataid){ 
        //      array_push($data2, array(
        //        'IdRequestHeader' =>  $idheader,
        //        'PackedID'        =>  $idpaket[$index],  //DoubleNet
        //      ));

        //      $index++;
        //    }

        //    $sql = $this->M_rekamMedis->save_batch($data2); 

        $this->session->set_flashdata("success", "Berhasil !");
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function hapusrequeslab($id, $caseid)
    {
        $this->db->delete('LabRequestDetail', ['PackedID' => $id]);
        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil Dihapus </div>');
        redirect('RekamMedis/pemeriksaan' . $caseid);
    }

    function searchObat()
    {
        date_default_timezone_set("Asia/Jakarta");
        $keyword = $this->input->post('keyword');
        $id = $this->input->post('id');
        $obj = $this->db->query("select top 30 PharmacyCode as code, Description as description, PharmacyUnit as satuan from Pharmacy Where PharmacyCode like '$keyword%' or Description like '%$keyword%' And Active = 1 Order by PharmacyCode ")->result_array();
        $output = '<ul class="list-unstyled ulclass">';
        if (empty($obj)) {
            $output .= "<li class='liclass' onClick=\"setObatCode('empty','$id');\" >Tidak ditemukan</li>";
            $output .= '</ul>';
        } else {
            foreach ($obj as $data) {
                $ware = 1;
                $aPharmacyCode = $data['code'];
                $stok = $this->db->query("exec Sp_SisaStok '" . date('Y-m-d') . "' , '" . $ware . "', '" . $aPharmacyCode . "' ")->row_array();
                $dataLi =  $data['code'] . ' # ' . $data['description'] . ' # ' . $data['satuan'] . ' # ' . $stok['TotQty'];
                $output .= "<li class='liclass' onClick=\"setObatCode('$dataLi','$id');\">" . $dataLi . "</li>";
            }
            $output .= '</ul>';
        }

        $response = array(
            "status" => "00",
            "data" => $output,
        );
        echo json_encode($response);
        exit();
    }

    function CheckStockObat()
    {
        date_default_timezone_set("Asia/Jakarta");
        $ware = $this->session->userdata('wareHouseCode');
        $pharmachyCode = $this->input->post('pharmachyCode');
        $query = $this->db->query("exec Sp_SisaStok '" . date('Y-m-d') . "' , '" . $ware . "', '" . $pharmachyCode . "' ")->row_array();
        $stock = "";
        if (!empty($query)) {
            $stock = $query['TotQty'];
        }
        $response = array(
            "status" => "00",
            "stock" => $stock,
        );
        echo json_encode($response);
        exit();
    }

    public function ProsesLaboratori($id)
    {
        //=======================================================================
        $data['user'] = $user = $this->db->get_where('userV2', ['UserName' => $this->session->userdata('UserName')])->row_array();
        $data['judul'] = "Klinik";
        date_default_timezone_set("Asia/jakarta");
        // ======================================================================
        $caseid      =  $this->input->post('caseid');
        $tanggal     =  date('Y-m-d');
        $jam         =  date('H:i:s');
        $dokter      =  $_POST['DoctorID'];
        $mr          =  $this->input->post('PatientCode');
        $status      =  1;
        $iduri       =  $this->uri->segment(3);
        $PackedID    = $_POST['PackedID'];

        $qdata = $this->db->query("select IdRequestHeader from LabRequestHeader where CaseID = '$id' ")->row_array();
        $idheader = $qdata['IdRequestHeader'];

        $count = count($PackedID);
        for ($x = 0; $x < $count; $x++) {
            $splitX = explode(' ', $PackedID[$x]);
            $this->db->query("INSERT INTO LabRequestDetail (IdRequestHeader,PackedID) VALUES ('$idheader','$splitX[0]')");
        }

        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil Di Update </div>');
        redirect($_SERVER['HTTP_REFERER']);
    }

       public function updatePcare()
    {
        $data = array(
            'Username' => $this->input->post('user'),
            'Password' => $this->input->post('pass'),
        );
        $this->db->where('ConsID', $this->input->post('id'));
        $this->db->update('BPJS_ID', $data);
        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil Di Update </div>');
        redirect($_SERVER['HTTP_REFERER']);
    }

        public function getDoktersemua()
    {
        $query = $this->db->query("SELECT * FROM  Doctor where Active= 'T'")->result();
        echo json_encode($query);
    }

}
