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

class worklist extends CI_Controller
{

    // CONSTRUCT
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->library('tcpdf_lib');
        $this->load->helper('url');
        $this->load->model('Worklist_Model');
        if (!$this->session->userdata('UserName')) {
            redirect('login');
        }
    }

    public function index()
    {
        $data['user'] = $this->db->get_where("userV2", ["UserName" => $this->session->userdata('UserName')])->row_array();
        $data['abdulradjak'] = $this->db->query("SELECT TOP 1 * FROM Utama")->row_array();
        $data['judul'] = "Worklist Laboratorium";
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('worklist/index', $data);
        $this->load->view('properti/footer', $data);
    }

    public function get_company()
    {
        // Ambil hanya penjamin aktif
        $data = $this->db->select('CompanyCode, CompanyName')
            ->where('Status', 'T')
            ->order_by('CompanyName', 'ASC')
            ->get('Company')
            ->result_array();

        // Jika tidak ada data
        if (empty($data)) {
            echo json_encode([]);
            return;
        }

        // Return JSON terstruktur
        $response = [
            'status' => true,
            'data' => $data
        ];

        echo json_encode($response);
    }

      public function updatecompany()
        {
            $caseid   = $this->input->post('caseid');
            $penjamin = $this->input->post('penjamin');

            //$update = $this->db->query("UPDATE Cases SET CompanyCode = '$penjamin' WHERE [Case ID] = '$caseid'");
            $update = $this->db->query("UPDATE tblLabResult SET Penjamin = '$penjamin' WHERE caseid = '$caseid'");

            if ($update) {
                echo json_encode(['status' => true, 'message' => 'Update berhasil']);
            } else {
                echo json_encode(['status' => false, 'message' => 'Gagal update']);
            }
        }


    public function pencarian()
    {
        $caseid = $this->input->post('caseid');
        $nomr = $this->input->post('nomr');
        $tanggal = $this->input->post('tanggal');

        if ($caseid != '' && $nomr == '' && $tanggal == '') {
            // caseid
            $field = "l.caseid = '$caseid'";
        } else if ($caseid != '' && $nomr != '' && $tanggal == '') {
            // caseid, nomr
            $field = "l.caseid = '$caseid' AND l.MR = '$nomr'";
        } else if ($caseid == '' && $nomr != '' && $tanggal == '') {
            // nomr
            $field = "l.MR = '$nomr'";
        } else if ($caseid == '' && $nomr == '' && $tanggal != '') {
            // tanggal
            $field = "l.ReceiptDate = '$tanggal'";
        } else {
            // all
            $field = "l.ReceiptDate = '$tanggal'";
        }

        $data = $this->Worklist_Model->cariPasien($field);
        $respon = [
            "jumlahData" => $data->num_rows(),
            "body" => $data->result()
        ];
        echo json_encode($respon);
    }

    public function getPasien()
    {
        $query = $this->Worklist_Model->getPasien();
        $dataRespon = [
            "jumlahData" => $query->num_rows(),
            "body" => $query->result()
        ];
        echo json_encode($dataRespon);
    }

    public function dataLabHeader()
    {
        $noLab = $this->input->post('noLab');
        $data = $this->Worklist_Model->dataLabHeader($noLab);
        $respon = [
            "jumlahData" => $data->num_rows(),
            "body" => $data->row()
        ];
        echo json_encode($respon);
    }

    public function dataLabDetail()
    {
        $noLab = $this->input->post('noLab');
        $data = $this->Worklist_Model->dataLabDetail($noLab);
        $respon = [
            "jumlahData" => $data->num_rows(),
            "body" => $data->result()
        ];
        echo json_encode($respon);
    }

    public function loopNormalValue()
    {
        $resultID = $this->input->post('resultID');
        $umurHariAja = $this->input->post('umurHariAja');
        $jk = $this->input->post('jk');
        $data = $this->Worklist_Model->loopNormalValue($resultID, $umurHariAja, $jk);
        $respon = [
            "jumlahData" => $data->num_rows(),
            "body" => $data->row()
        ];
        echo json_encode($respon);
    }

    public function getPilihan()
    {
        $data = $this->Worklist_Model->getPilihan()->result();
        echo json_encode($data);
    }

    public function updateHasilLab()
    {
        date_default_timezone_set("Asia/Jakarta");
        $noLab = $this->input->post('noLab');
        $diagnosa = $this->input->post('diagnosa');
        $cekData = $this->Worklist_Model->dataLabHeader($noLab)->row();
        if ($cekData->SampleDate == '') {
            $dataHeader = [
                "SampleDate" => date('Y-m-d'),
                "SampleTime" => date('H:i'),
                "Diagnosa" => $diagnosa,
                "TanggalCetak" => date('Y-m-d'),
                "HasilLab" => 1
            ];
        } else {
            $dataHeader = [
                "Diagnosa" => $diagnosa
            ];
        }
        $this->Worklist_Model->updateHeader($dataHeader, $noLab);

        // array
        $ID = $this->input->post('ID');
        $up = $this->input->post('up');
        $down = $this->input->post('down');
        $ResultValue = $this->input->post('ResultValue');
        $NormalValue = $this->input->post('NormalValue');
        $CharValue = $this->input->post('CharValue');
        $row = count($ID);
        for ($i = 0; $i < $row; $i++) {
            if ($CharValue[$i] == 'TEXT') {
                if ($NormalValue[$i] == '') {
                    $colorAnalis = 'white';
                } else {
                    if ($ResultValue[$i] == $NormalValue[$i]) {
                        $colorAnalis = 'white';
                    } else {
                        $colorAnalis = 'red';
                    }
                }
            } else {
                if ($ResultValue[$i] < $up[$i] || $ResultValue[$i] > $down[$i]) {
                    $colorAnalis = 'red';
                } else {
                    $colorAnalis = 'white';
                }
            }

            $this->db->query("UPDATE tblLabResultDetail SET ResultValue = '$ResultValue[$i]', ColorValue = '$colorAnalis' WHERE ID = '$ID[$i]'");
        }

        $respon = [
            "pesan" => 0
        ];
        echo json_encode($respon);
    }

    public function cetak($noLab)
    {
        $data['utama'] = $this->db->get("Utama")->row();
        $data['noLab'] = $noLab;
        $data['header'] = $this->Worklist_Model->dataLabHeaderCetak($noLab)->row();
        $data['kategoriLab'] = $this->Worklist_Model->kategoriLab($noLab)->result();
        $filename = 'NO-' . $noLab . '.pdf';
        $htmlLab = $this->load->view('worklist/cetak', $data, true);
        $this->tcpdf_lib->generate_satu_page($htmlLab, $filename);
    }

    function simpanEditNormal()
    {
        $id = $this->input->post('id');
        $normal = $this->input->post('normal');
        $edit = [
            "NormalValue" => $normal
        ];
        $this->Worklist_Model->simpanEditNormal($edit, $id);
        $respon = [
            "pesan" => 0
        ];
        echo json_encode($respon);
    }

    public function khususRiwayatPemeriksaanDokter()
    {
        $nomr = $this->input->post('nomr');
        $field = "l.MR = '$nomr' AND l.HasilLab = 1";
        $data = $this->Worklist_Model->cariPasien($field);
        $respon = [
            "jumlahData" => $data->num_rows(),
            "body" => $data->result()
        ];
        echo json_encode($respon);
    }

    public function cekHasilListLab()
    {
        $userID = $this->input->post('userID');
        $data = $this->Worklist_Model->cekHasilListLab($userID)->row();
        echo json_encode($data);
    }

    public function getHasilListLab()
    {
        $userID = $this->input->post('userID');
        $data = $this->Worklist_Model->getHasilListLab($userID)->result();
        echo json_encode($data);
    }
}
