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

class Laboratorium 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->helper('url');

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


    public function index()
    {
        extract($_GET);
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        // $data['user'] = $this->db->get_where('userV2', ['UserName' => $this->session->userdata('UserName')])->row_array();

        $data['pasien'] = $this->db->query("select ca.[Case ID] as CaseID,ca.Description,ca.PatientCode,lh.dokterKirim, dk.FirstName,dk.LastName,lh.tglRequest,lh.jamRequest,
        lh.IdRequestHeader,lh.status,c.CompanyName
        from Cases ca join LabRequestHeader lh on ca.[Case ID] = lh.CaseID
        join Company c on c.CompanyCode = ca.CompanyCode
        join Doctor dk on lh.dokterKirim = dk.DoctorID where lh.status = 1")->result_array();

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

    public function historilab(){
        extract($_GET);
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();
        // $data['user'] = $this->db->get_where('userV2', ['UserName' => $this->session->userdata('UserName')])->row_array();

        $data['pasien'] = $this->db->query("select ca.[Case ID] as CaseID,ca.Description,ca.PatientCode,lh.dokterKirim, dk.FirstName,dk.LastName,lh.tglRequest,lh.jamRequest,
        lh.IdRequestHeader,lh.status
        from Cases ca join LabRequestHeader lh on ca.[Case ID] = lh.CaseID
        join Doctor dk on lh.dokterKirim = dk.DoctorID where lh.status = 2")->result_array();

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

    public function caridatalab()
    {
        extract($_GET);
        date_default_timezone_set("Asia/Jakarta");
        $data['judul'] = "Klinik";
        $data['user'] = $this->M_user->getUserSession()->row_array();

        $data['pasien'] = $this->db->query("select ca.[Case ID] as CaseID,ca.Description,ca.PatientCode,cn.CompanyName,lh.dokterKirim, dk.FirstName,dk.LastName,lh.tglRequest,lh.jamRequest,
        lh.IdRequestHeader
        from Cases ca join LabRequestHeader lh on ca.[Case ID] = lh.CaseID
        join Company cn on cn.[CompanyCode] = ca.CompanyCode
        join Doctor dk on lh.dokterKirim = dk.DoctorID where tglRequest = '$tgl'")->result_array();

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

    public function proseslaborat()
    {
        $data['judul'] = 'Kelinik';
        $idheader = $this->uri->segment(4);
        $data['lab'] = $this->db->query("select lh.IdRequestHeader, ld.PackedID, pd.Description
        from LabRequestHeader lh join LabRequestDetail ld on lh.IdRequestHeader = ld.IdRequestHeader
        join tblLabPacked pd on pd.PackedID = ld.PackedID where lh.IdRequestHeader = '$idheader'
        ")->result_array();
        $data['user'] = $this->db->get_where('userV2', ['UserName' => $this->session->userdata('UserName')])->row_array();
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('laboratorium/proseslaborat', $data);
        $this->load->view('properti/footer', $data);
    }

    public function inputlaborat()
    {
        $data['judul'] = 'Kelinik';
        $data['user'] = $this->db->get_where('userV2', ['UserName' => $this->session->userdata('UserName')])->row_array();
        $idheader = $this->uri->segment(3);
        $data['lab'] = $this->db->query("select lh.IdRequestHeader, ld.PackedID,pd.ResultID,lf.ResultName, pc.Description as [Group], lf.NormalValue, pc.CategoryID
        from LabRequestHeader lh join LabRequestDetail ld on lh.IdRequestHeader = ld.IdRequestHeader
        join tblLabPackedDetail pd on pd.PackedID = ld.PackedID
		join tblLabPacked pc on pc.PackedID = pd.PackedID
        join tblLabReference lf on lf.ResultID = pd.ResultID where lh.IdRequestHeader = '$idheader'
        ")->result_array();
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('laboratorium/inputlaborat', $data);
        $this->load->view('properti/footer', $data);
    }

    public function updatelaborat($id)
    {
        $data['judul'] = 'Kelinik';
        $data['user'] = $this->db->get_where('userV2', ['UserName' => $this->session->userdata('UserName')])->row_array();
        $data['lab'] = $this->db->query("SELECT td.id,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['header'] = $this->db->query("Select top 1 * From Cases where [Case ID] ='$id'")->row_array();


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

     public function prosesupdatelaborat()
    {
        // Ambil data dari form
        $resultid = $this->input->post('resultid');
        $inputvalue = $this->input->post('inputvalue');
        $caseid = $this->input->post('caseid');
        $mr = $this->input->post('mr');

        // Pastikan ada data
        if (!empty($resultid) && is_array($resultid)) {
            $updated = 0;

            // Loop setiap baris input
            for ($i = 0; $i < count($resultid); $i++) {
                $id = $resultid[$i];
                $value = trim($inputvalue[$i]);

                // Lewati jika kosong
                if ($id == '' || $value == '') continue;

                // Lakukan update ke tabel
                $this->db->where('id', $id);
                $this->db->update('tblLabResultDetail', ['ResultValue' => $value]);

                if ($this->db->affected_rows() > 0) {
                    $updated++;
                }
            }

            // Tampilkan hasil
            $this->session->set_flashdata('success', "$updated data berhasil diperbarui.");
        } else {
            $this->session->set_flashdata('error', 'Tidak ada data yang dikirim.');
        }

        // Redirect kembali ke halaman sebelumnya
        redirect('anamnesa/formmcu/'.$caseid.'/'.$mr);
    }

    public function cetaklab($id){
        // ob_start();
        $data['abdulradjak'] = $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();
        $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['group'] = $this->db->query("select distinct LC.Bahasa as BahasaLC, LR.ReceiptTime
        from tblLabResult LR
        join Doctor DR on LR.DoctorID = DR.DoctorID
        join tblLabResultDetail LRD on LR.LabNo = LRD.LabNo
        join tblLabCategory LC on LRD.CategoryID = LC.CategoryID
        JOIN tblLabResult ltr on ltr.LabNo = lrd.LabNo
        where ltr.caseid = '$id'")->result_array();
        $this->load->view('cetak/cetaklab', $data);
        // $isi = ob_get_clean();
        // ob_end_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;
        // }
    }


    public function prosesinput()
    {
        date_default_timezone_set("Asia/Jakarta");
        $data['user'] = $user = $this->db->get_where('userV2', ['UserName' => $this->session->userdata('UserName')])->row_array();
        $data['judul'] = "Klinik";
         // ======================================================================
        $ResultID    =  $_POST['ResultID'];
        $ResultName  =  $_POST['ResultName'];
        $Group       =  $_POST['Group'];
        $NormalValue =  $_POST['NormalValue'];
        $inputvalue  =  $_POST['inputvalue'];
        $CategoryID  =  $_POST['CategoryID'];
 
        $idheader = $this->uri->segment(3);
        $labheader = $this->db->query("select ca.[Case ID] as CaseID,ca.Description,ca.PatientCode,lh.dokterKirim, dk.FirstName,dk.LastName,lh.tglRequest,lh.jamRequest,
        lh.IdRequestHeader,p.HomeAddress1,p.Age,p.Sex
        from Cases ca join LabRequestHeader lh on ca.[Case ID] = lh.CaseID
		join Patient p on p.PatientCode = lh.PatientCode
        join Doctor dk on lh.dokterKirim = dk.DoctorID where lh.IdRequestHeader = '$idheader' ")->row_array();

        $caseid = $labheader['CaseID'];
        $nama   = $labheader['Description'];
        $mr     = $labheader['PatientCode'];
        $dokter = $labheader['dokterKirim'];
        $tanggal = date('Y-m-d');
        $alamat = $labheader['HomeAddress1'];
        $umur   = $labheader['Age'];
        $sex    = $labheader['Sex'];
        $waktu = date('H:i:s');
        $username = $user['nama'];
 
        $getLab = $this->db->query("SELECT * FROM SystemNo WHERE SystemName = 'LabNo'")->row_array();
        $LabNo  = $getLab['NoNumeric'] + 1;
        $this->db->query("UPDATE SystemNo SET NoNumeric = '$LabNo' WHERE SystemName = 'LabNo'"); 

            $data2 = array();
    
       $index = 0; 
       foreach($ResultID as $dataid){ 
         array_push($data2, array(
           'ResultID'      =>  $dataid,
           'LabNo'         =>  $LabNo,
           'ResultValue'   =>  $inputvalue[$index],  //DoubleNet
           'Bahasa'        =>  $ResultName[$index],
           'Unit'          =>  'Laboratorium',
           'NormalValue'   =>  $NormalValue[$index],
           'CategoryID'   =>   $CategoryID[$index]
         ));
         
         $index++;
       }

       $this->load->model('M_rekamMedis');
       //Save & Update
       $this->db->query("INSERT INTO tblLabResult (LabNo,MR,ReceiptDate,DoctorID,Room,ReceiptTime,[Address],Age,Sex,PatientName,UserCreated,caseid) VALUES ('$LabNo','$mr','$tanggal','$dokter','OP','$waktu','$alamat','$umur','$sex','$nama','$username','$caseid')");
       $sql = $this->M_rekamMedis->save_batch1($data2);
       $this->db->query("UPDATE LabRequestHeader SET [status] = '2' WHERE IdRequestHeader = '$idheader'");
 
        $this->session->set_flashdata("success", "Berhasil !");
        redirect('mcu/index');
    }

    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('laboratorium/record', $data);
        $this->load->view('properti/footer', $data);
    }

    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['tab'] = $this->M_rekamMedis->tab($id)->row_array();
        // =================================================================================
        $data['pasien'] = $this->M_rekamMedis->pemeriksaan($id)->row_array();
        // =================================================================================
        $this->load->model('M_Transaksi');
        $data['dokter'] = $this->M_Transaksi->getdokter()->result_array();
        // =================================================================================
        $data['hasilLaboratory'] = $this->M_rekamMedis->hasilLaboratory($id)->row_array();
        $data['countLaboratory'] = $this->M_rekamMedis->hasilLaboratory($id)->num_rows();
        // =================================================================================
        $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();
        // =================================================================================

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

    public function updaterequest($id)
    {
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $data['judul'] = "Klinik";
        $data['pasien'] = $this->M_rekamMedis->pemeriksaan($id)->row_array();
        // =================================================================================
        $data['element'] = $this->M_rekamMedis->ElementGigi()->result_array();
        // =================================================================================
        $data['tab'] = $this->M_rekamMedis->tab($id)->row_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();
        // =================================================================================

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


}
?>

