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

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

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

    public function pasien()
    {
        $data['judul'] = "Klinik";
        $data['pasien'] = $this->M_anamnesa->pasien()->result_array();

        //print_r($data['pasien']);exit();
        $data['poli'] = $this->M_anamnesa->poli()->result_array();
        $data['dokter'] = $this->M_anamnesa->dokter()->result_array();
        $data['jkn'] = $this->M_anamnesa->Mjkn()->result_array();
        //print_r($data['jkn']);exit();
        $data['nomr'] = $this->M_anamnesa->Mjknnomr()->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('anamnesa/pasien', $data);
        $this->load->view('properti/footer', $data);
    }

    public function form($id,$mr)
    {
        $data['judul'] = "Klinik";
        $data['user'] = $this->db->get_where('userV2', ['username' => $this->session->userdata('username')])->row_array();
        $data['poli'] = $this->M_anamnesa->poli()->result_array();
        $data['dokter'] = $this->M_anamnesa->dokter()->result_array();
        $data['antrian'] = $this->db->query("SELECT * FROM Antrian")->result_array();
        $data['case'] = $this->db->query("SELECT *, c.PlanNo as nokartu FROM Cases c, Patient p WHERE c.[PatientCode]=p.[PatientCode] AND [Case ID] = '$id'")->row_array();
        
        //echo json_encode($data['case']);exit();
        $data['tingkatnyeri'] = $this->db->query("SELECT * FROM erm_tingkat_nyeri")->result_array();
        $data['riwayatPenyakit'] = $this->db->query("SELECT * FROM tabelRiwayatPenyakit")->result_array();
        $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();
        $data['caseId'] = $id;

        $this->load->model('M_Pendaftaran');
        $nokartu = $data['case']['nokartu'];
        
        $datapeserta = $this->M_Pendaftaran->peserta($nokartu);

        //print_r($datapeserta);exit();
        $data['kodePpkPeserta'] = $datapeserta['response']['list']['kdProviderPst']['kdProvider'];

        $this->load->model('M_BpjsID');
        $abdulradjak = $this->M_BpjsID->abdulradjak()->row_array();
        $data['kodePpkRs'] = $abdulradjak['KodePPK'];

        $data['IsKodePPKPesertaEqualRs'] = false;
        if($data['kodePpkPeserta'] == $data['kodePpkRs'] ){
            $data['IsKodePPKPesertaEqualRs'] = true;
        }


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

    public function detail($id)
    {
        $data['judul'] = "Klinik";
        $data['user'] = $this->db->get_where('userV2', ['username' => $this->session->userdata('username')])->row_array();

        $data['case'] = $this->db->query("SELECT * FROM Cases c, Patient p WHERE c.[PatientCode]=p.[PatientCode] AND [Case ID] = '$id'")->row_array();
        $data['listDetail'] = $this->db->query("SELECT * FROM CaseDetail WHERE [Case ID] = '$id'")->row_array();
        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('anamnesa/detail', $data);
        $this->load->view('properti/footer', $data);
    }

    public function prosesAnamnesis()
    {
        date_default_timezone_set("Asia/Jakarta");
        $date=date('Y-m-d');
        $CaseID = $this->input->post('case_id');
        $Unit = $this->input->post('Unit');
        $DoctorID = $this->input->post('DoctorID');
        $Kesadaran_E = $this->input->post('Kesadaran_E');
        $Kesadaran_M = $this->input->post('Kesadaran_M');
        $Kesadaran_M = $this->input->post('Kesadaran_M');
        $Kesadaran_V = $this->input->post('Kesadaran_V');
        $Tensi = $this->input->post('Tensi');
        $TensiPer = $this->input->post('TensiPer');
        $Suhu = $this->input->post('Suhu');
        $FrekuensiNadi = $this->input->post('FrekuensiNadi');
        $FrekuensiNafas = $this->input->post('FrekuensiNafas');
        $TB = $this->input->post('TB');
        $BB = $this->input->post('BB');
        $IMT = $this->input->post('IMT');
        $LingkarKepala = $this->input->post('LingkarKepala');
        $Keluhan = $this->input->post('Keluhan');
        $tingkat_nyeri = $this->input->post('tingkat_nyeri');
        $pernahDirawat = $this->input->post('pernahDirawat');
        $KapanDirawat = $this->input->post('KapanDirawat');
        $DimanaDirawat = $this->input->post('DimanaDirawat');
        $SakitYangSama = $this->input->post('SakitYangSama');
        $Operasi = $this->input->post('Operasi');
        $RiwayatOperasi = $this->input->post('RiwayatOperasi');
        $PenyakitKeluarga = $this->input->post('PenyakitKeluarga');
        $RiwayatPenyakitKeluarga = $this->input->post('RiwayatPenyakitKeluarga');
        $RiwayatObatDiminum = $this->input->post('RiwayatObatDiminum');
        $alergi_obat = $this->input->post('alergi_obat');
        $usia_kunjungan = $this->input->post('usia_kunjungan');
        $Pisikososial = $this->input->post('Pisikososial');
        $Spiritual = $this->input->post('Spiritual');
        $Statusgizi      = $this->input->post('statusgizi');
        $panjangbalita   = $this->input->post('panjangbalita');
        $lila            = $this->input->post('lila');
        $riwayatpenyakit = $this->input->post('riwayatpenyakit');
        $riwayatlainya   = $this->input->post('Riwayatlainya');
        $resikojatuh = $this->input->post('resikojatuh');
        $alergi_obat1    = $this->input->post('alergi_obat1');
        $klasifikasiIMT  = $this->input->post('klasifikasiIMT');
        $resiko_a        = $this->input->post('resiko_a');
        $resiko_b        = $this->input->post('resiko_b');
        $hasilresiko        = $this->input->post('hasilresiko');
        $tindakanresiko        = $this->input->post('tindakanresiko');

        if ($Unit == "POLI GIGI") {
            $no = $this->db->query("SELECT * FROM Antrian WHERE Jenis = '$Unit'")->row_array();
            $num = $no['No_Akhir'] + 1;
            $int = 'E';
            $NoAntrian = $int . '.' . $num;
        } else if ($Unit == "POLI KEBIDANAN") {
            $no = $this->db->query("SELECT * FROM Antrian WHERE Jenis = '$Unit'")->row_array();
            $num = $no['No_Akhir'] + 1;
            $int = 'O';
            $NoAntrian = $int . '.' . $num;
        } else if ($Unit == "POLI UMUM 1") {
            $no = $this->db->query("SELECT * FROM Antrian WHERE Jenis = '$Unit'")->row_array();
            $num = $no['No_Akhir'] + 1;
            $int = 'A';
            $NoAntrian = $int . '.' . $num;
        } else if ($Unit == "POLI UMUM 2") {
            $no = $this->db->query("SELECT * FROM Antrian WHERE Jenis = '$Unit'")->row_array();
            $num = $no['No_Akhir'] + 1;
            $int = 'I';
            $NoAntrian = $int . '.' . $num;
        } else {
            $no = $this->db->query("SELECT * FROM Antrian WHERE Jenis = '$Unit'")->row_array();
            $num = $no['No_Akhir'] + 1;
            $int = 'U';
            $NoAntrian = $int . '.' . $num;
        }

        $this->db->query("UPDATE Antrian SET No_Akhir = '$num' WHERE Jenis = '$Unit'");
        $this->db->query("UPDATE Cases SET CaseDetail = '1',QueueNo='$NoAntrian' WHERE [Case ID] = '$CaseID'");

        $this->db->query("INSERT INTO CaseDetail ([Case ID], BeratBadan, TinggiBadan, Tensi, Diastole, Suhu, Keluhan, Unit, DoctorID, NoAntrian, iStatus, respRate, heartRate, Kesadaran_E, Kesadaran_M, Kesadaran_V, IMT, LingkarKepala, tingkat_nyeri, pernahDirawat, KapanDirawat, DimanaDirawat, SakitYangSama, Operasi, RiwayatOperasi, PenyakitKeluarga, RiwayatPenyakitKeluarga, RiwayatObatDiminum, usia_kunjungan, alergi_obat, Psikososial, Spiritual,PanjangBadan,lila,Statusgizi,Riwayatpenyakit,Riwayatlainya,resikojatuh,alergiobat, KlasifikasiIMT, resiko_a,resiko_b,hasilresiko,tindakanresiko) VALUES ('$CaseID', '$BB', '$TB', '$Tensi', '$TensiPer', '$Suhu', '$Keluhan', '$Unit', '$DoctorID', '$NoAntrian', '0', '$FrekuensiNafas', '$FrekuensiNadi', '$Kesadaran_E', '$Kesadaran_M', '$Kesadaran_V', '$IMT', '$LingkarKepala', '$tingkat_nyeri', '$pernahDirawat', '$KapanDirawat', '$DimanaDirawat', '$SakitYangSama', '$Operasi', '$RiwayatOperasi', '$PenyakitKeluarga', '$RiwayatPenyakitKeluarga', '$RiwayatObatDiminum', '$usia_kunjungan', '$alergi_obat', '$Pisikososial', '$Spiritual','$panjangbalita','$lila','$Statusgizi','$riwayatpenyakit','$riwayatlainya','$resikojatuh','$alergi_obat1','$klasifikasiIMT','$resiko_a','$resiko_b','$hasilresiko','$tindakanresiko')");
        
        $this->db->query("UPDATE CaseAdmin SET DoctorID = '$DoctorID' WHERE [Case ID] = '$CaseID'");
        //$this->db->query("INSERT INTO CaseAdmin ([Case ID], Unit, DoctorID) VALUES ('$CaseID', '$Unit', '$DoctorID')");

        redirect('anamnesa/detail/' . $CaseID);
    }

    public function prosesAnamnesa()
    {
        $CaseID = $this->input->post('CaseID');
        $BeratBadan = $this->input->post('BeratBadan');
        $TinggiBadan = $this->input->post('TinggiBadan');
        $Tensi = $this->input->post('Tensi');
        $Suhu = $this->input->post('Suhu');
        $Keluhan = $this->input->post('Keluhan');
        $Diastole = $this->input->post('Diastole');
        $respRate = $this->input->post('respRate');
        $heartRate = $this->input->post('heartRate');
        $Unit = $this->input->post('Unit');
        $DoctorID = $this->input->post('DoctorID');



        if ($Unit == "POLI GIGI") {
            $no = $this->db->query("SELECT * FROM Antrian WHERE Jenis = '$Unit'")->row_array();
            $num = $no['No_Akhir'] + 1;
            $int = 'E';
            $NoAntrian = $int . '.' . $num;
        } else if ($Unit == "POLI KEBIDANAN") {
            $no = $this->db->query("SELECT * FROM Antrian WHERE Jenis = '$Unit'")->row_array();
            $num = $no['No_Akhir'] + 1;
            $int = 'O';
            $NoAntrian = $int . '.' . $num;
        } else if ($Unit == "POLI UMUM 1") {
            $no = $this->db->query("SELECT * FROM Antrian WHERE Jenis = '$Unit'")->row_array();
            $num = $no['No_Akhir'] + 1;
            $int = 'A';
            $NoAntrian = $int . '.' . $num;
        } else if ($Unit == "POLI UMUM 2") {
            $no = $this->db->query("SELECT * FROM Antrian WHERE Jenis = '$Unit'")->row_array();
            $num = $no['No_Akhir'] + 1;
            $int = 'I';
            $NoAntrian = $int . '.' . $num;
        } else {
            $no = $this->db->query("SELECT * FROM Antrian WHERE Jenis = '$Unit'")->row_array();
            $num = $no['No_Akhir'] + 1;
            $int = 'U';
            $NoAntrian = $int . '.' . $num;
        }

        // echo $NoAntrian;exit();

        $this->db->query("UPDATE Antrian SET No_Akhir = '$num' WHERE Jenis = '$Unit'");
        $this->db->query("UPDATE Cases SET CaseDetail = '1',QueueNo='$NoAntrian' WHERE [Case ID] = '$CaseID'");

        $this->db->query("INSERT INTO CaseDetail ([Case ID], BeratBadan, TinggiBadan, Tensi, Diastole, Suhu, Keluhan, Unit, DoctorID, NoAntrian, iStatus, respRate, heartRate) VALUES ('$CaseID','$BeratBadan','$TinggiBadan','$Tensi', '$Diastole','$Suhu','$Keluhan','$Unit', '$DoctorID','$NoAntrian', '1','$respRate', '$heartRate')");
        redirect('rekamMedis/pasien');
    }

   public function updateAnamnesa()
    {
        $CaseID = $this->input->post('CaseID');
        $BeratBadan = $this->input->post('BeratBadan');
        $TinggiBadan = $this->input->post('TinggiBadan');
        $Tensi = $this->input->post('Tensi');
        $Suhu = $this->input->post('Suhu');
        $Keluhan = $this->input->post('Keluhan');
        $Diastole = $this->input->post('Diastole');
        $respRate = $this->input->post('respRate');
        $heartRate = $this->input->post('heartRate');
        $Unit = $this->input->post('Unit');
        $DoctorID = $this->input->post('DoctorID');
        $nomorkartu = $this->input->post('NoBpjs');
        $antrian = $this->db->query("Select * From Antrian Where Jenis like '%$Unit%'")->row_array();

        $tglformat = date('d-m-Y');
        $bpjs = $this->db->query("SELECT TOP 1 * FROM BPJS_ID")->row_array();
        $kodepoli = $antrian['KodePoli'];

        $abdulradjak = $this->M_BpjsID->abdulradjak()->row_array();
        $ch = curl_init();
        $jsonarray = array(
            'kdProviderPeserta' => $bpjs['KodePPK'],
            'tglDaftar'         => $tglformat,
            'noKartu'           => "$nomorkartu",
            'kdPoli'            => "$kodepoli",
            'keluhan'           => "$Keluhan",
            'kunjSakit'         => true,
            'sistole'           => "$Tensi",
            'diastole'          => "$Diastole",
            'beratBadan'        => "$BeratBadan",
            'tinggiBadan'       => 0,
            'respRate'          => "$respRate",
            'lingkarPerut'      => 0,
            'heartRate'         => "$heartRate",
            'rujukBalik'        => 0,
            'kdTkp'             => "10"
        );

        $payload = json_encode($jsonarray);

        // print_r($payload);
        // exit();

        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'];
        if ($kodeNotif != 201) {
            echo "<script>alert('Gagal update data ke BPJS Kesehatan : $pesan');window.location='" . base_url('rekamMedis/listpasienanamnesa') . "';</script>";
            exit();
        }

        // send antrean panggil
        date_default_timezone_set('Asia/Jakarta');
        $waktu = date('Y-m-d H:i:s');
        $convert = strtotime($waktu) * 1000;

        // send antrean panggil
        $tglAntrian = date('Y-m-d');
        $payloadPanggil = [
            "tanggalperiksa" => $tglAntrian,
            "kodepoli" => "$kodepoli",
            "nomorkartu" => "$nomorkartu",
            "status" => 1, // hadir
            "waktu" => $convert,
        ];

        $this->SendAntreanPanggil($payloadPanggil);

        $this->db->query("UPDATE CaseDetail SET BeratBadan = '$BeratBadan', TinggiBadan = '$TinggiBadan', Tensi = '$Tensi', Diastole = '$Diastole', Suhu = '$Suhu', Keluhan = '$Keluhan', Unit = '$Unit', DoctorID = '$DoctorID', respRate = '$respRate', heartRate = '$heartRate' WHERE [Case ID] = '$CaseID'");
        redirect('rekamMedis/listpasienanamnesa');
    }



    public function prosesAnamnesisJKN()
    {
        $this->load->model('M_user');
        date_default_timezone_set("Asia/Jakarta");
        $user = $data['user'] = $this->M_user->getUserSession()->row_array();

        $CaseID = $this->input->post('case_id');
        $PatientCode = $this->input->post('PatientCode');
        $CompanyCode = $this->input->post('CompanyCode');
        $Nama = $this->input->post('nama');
        $Unit = $this->input->post('Unit');
        $DoctorID = $this->input->post('DoctorID');
        $Kesadaran_E = $this->input->post('Kesadaran_E');
        $Kesadaran_M = $this->input->post('Kesadaran_M');
        $Kesadaran_M = $this->input->post('Kesadaran_M');
        $Kesadaran_V = $this->input->post('Kesadaran_V');
        $Tensi = $this->input->post('Tensi');
        $TensiPer = $this->input->post('TensiPer');
        $Suhu = $this->input->post('Suhu');
        $FrekuensiNadi = $this->input->post('FrekuensiNadi');
        $FrekuensiNafas = $this->input->post('FrekuensiNafas');
        $TB = $this->input->post('TB');
        $BB = $this->input->post('BB');
        $IMT = $this->input->post('IMT');
        $lingkarperut = $this->input->post('lingkarperut');
        $LingkarKepala = $this->input->post('LingkarKepala');
        $Keluhan = $this->input->post('Keluhan');
        $tingkat_nyeri = $this->input->post('tingkat_nyeri');
        $pernahDirawat = $this->input->post('pernahDirawat');
        $KapanDirawat = $this->input->post('KapanDirawat');
        $DimanaDirawat = $this->input->post('DimanaDirawat');
        $SakitYangSama = $this->input->post('SakitYangSama');
        $Operasi = $this->input->post('Operasi');
        $RiwayatOperasi = $this->input->post('RiwayatOperasi');
        $PenyakitKeluarga = $this->input->post('PenyakitKeluarga');
        $RiwayatPenyakitKeluarga = $this->input->post('RiwayatPenyakitKeluarga');
        $RiwayatObatDiminum = $this->input->post('RiwayatObatDiminum');
        $alergi_obat = $this->input->post('alergi_obat');
        $usia_kunjungan = $this->input->post('usia_kunjungan');
        $Pisikososial = $this->input->post('Pisikososial');
        $Spiritual = $this->input->post('Spiritual');
        $nomorkartu = $this->input->post('nomorkartu');
        $kodePPKRs = $this->input->post('kodePPKRs');
        $kodePPKPeserta = $this->input->post('KodePPKPst');
        //echo $kodePPKPeserta;exit();
        if(empty($kodePPKRs) && empty($kodePPKPeserta)){
            echo 'Invalid Kode PPK / Not Set';exit();
        }

        $tglCreate = date('Y-m-d H:i:s');
        $tgl = date('Y-m-d');
        $tglFormat = date('d-m-Y', strtotime($tgl));
        $tglAntrian = date('Y-m-d', strtotime($tgl));

        /*if ($Unit == "POLI GIGI") {
            $no = $this->db->query("SELECT * FROM BPJS_Antrian WHERE NomorKartu = '$nomorkartu'")->row_array();
            $num = $no['NomorAntrean'];
        } else if ($Unit == "POLI KEBIDANAN") {
            $no = $this->db->query("SELECT * FROM BPJS_Antrian WHERE NomorKartu = '$nomorkartu'")->row_array();
            $num = $no['NomorAntrean'];
        } else if ($Unit == "POLI UMUM 1") {
            $no = $this->db->query("SELECT * FROM BPJS_Antrian WHERE NomorKartu = '$nomorkartu'")->row_array();
            $num = $no['NomorAntrean'];
        } else if ($Unit == "POLI UMUM 2") {
            $no = $this->db->query("SELECT * FROM BPJS_Antrian WHERE NomorKartu = '$nomorkartu'")->row_array();
            $num = $no['NomorAntrean'];
        } else {
            $no = $this->db->query("SELECT * FROM BPJS_Antrian WHERE NomorKartu = '$nomorkartu'")->row_array();
            $num = $no['NomorAntrean'];
        }*/
        $group = rtrim(preg_replace('/[^a-zA-Z\s]/', '', $Unit));
        $kodepoli =  $this->db->query("SELECT kodePoli FROM Poli WHERE [group] = '$group'")->row_array()['kodePoli'];
        
        $cases = $this->db->query("Select * From Cases where [Case ID] = '$CaseID'")->row_array();
        $Antrian = $cases['QueeNo'];
        $num = $Antrian;
         //$num = $this->GetNotAntrian($kodepoli);
         //$num = '';
        
        //echo $num;exit();
       
         $intakeTime = date('H:i:s');

        /*
         if ($jumlahCases > 0) {
             $RegStatus = "OLD";
         } else {
             $RegStatus = "NEW";
         }

         $patientStatus = $this->db->get_where('Company', ['CompanyCode' => $CompanyCode])->row_array();
         $statusPatient = $patientStatus['Group'];
        
         // CASE ID BARU
         $getCase = $this->db->query("SELECT * FROM SystemNo WHERE SystemName = 'Case'")->row_array();
         $dbInit = $this->db->query("SELECT TOP 1 * FROM Utama")->row_array();


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

        $cases = $this->db->query(" select [Case ID] from Cases where PatientCode = '$PatientCode' and convert(varchar, [Intake Date], 23)  = '$tglFormat' and [Case Status] = 'OPEN' ")->row_array();
        */
       // $caseidterakhir = $this->db->query("SELECT TOP 1 [Case ID] FROM Cases order by [Case ID] DESC")->row_array();
       $caseterakhir = $CaseID;

        if (strpos($Unit, "POLI UMUM") !== false) {
            $Unit = "POLI UMUM";
        }
        
        // check sudah ada apa belum
        // kalau belum insert cases..
       // if(empty($cases)){
            
            //Insert Cases
            //$this->db->query("INSERT INTO Cases ([Case ID], [Description], [Category], [Case Status], [Intake Date], [Intake Time], PatientCode, CompanyCode, [Patient Status], [UserCreated], DateCreated, RegStatus, DoctIncharge,  LastOP, CaseDetail, KODE, Class, Note, QueueNo) VALUES ('$caseterakhir', '$Nama', 'OP', 'OPEN', '$tgl', '$intakeTime', '$PatientCode', '$CompanyCode','$statusPatient', 'webtes','$tglCreate', '$RegStatus', '$DoctorID', '$Unit', '1', '', 'OP', 'M-JKN', '$num')");
            
            //CaseDetail
            $this->db->query("INSERT INTO CaseDetail ([Case ID], BeratBadan, TinggiBadan, Tensi, Diastole, Suhu, Keluhan, Unit, DoctorID, NoAntrian, iStatus, respRate, heartRate, Kesadaran_E, Kesadaran_M, Kesadaran_V, IMT, LingkarKepala, tingkat_nyeri, pernahDirawat, KapanDirawat, DimanaDirawat, SakitYangSama, Operasi, RiwayatOperasi, PenyakitKeluarga, RiwayatPenyakitKeluarga, RiwayatObatDiminum, usia_kunjungan, alergi_obat, Psikososial, Spiritual,lingkarperut) VALUES ('$caseterakhir', '$BB', '$TB', '$Tensi', '$TensiPer', '$Suhu', '$Keluhan', '$Unit', '$DoctorID', '$num', '0', '$FrekuensiNafas', '$FrekuensiNadi', '$Kesadaran_E', '$Kesadaran_M', '$Kesadaran_V', '$IMT', '$LingkarKepala', '$tingkat_nyeri', '$pernahDirawat', '$KapanDirawat', '$DimanaDirawat', '$SakitYangSama', '$Operasi', '$RiwayatOperasi', '$PenyakitKeluarga', '$RiwayatPenyakitKeluarga', '$RiwayatObatDiminum', '$usia_kunjungan', '$alergi_obat', '$Pisikososial', '$Spiritual','$lingkarperut')");
            $this->db->query("UPDATE Cases SET CaseDetail = '1' WHERE [Case ID] = '$caseterakhir'");
            $this->db->query("UPDATE CaseAdmin SET DoctorID = '$DoctorID' WHERE [Case ID] = '$caseterakhir'");
            // }else{
            // ambil case id yg existing
        //    $caseterakhir = $cases['Case ID'];
      //  }


        //$KodePPK = $kodePPKPeserta;
        //$kodepoli = $no['KodePoli'];


            // ---------------------------------------------------------------------
                $ch = curl_init();
                $jsonarray = array(
                'kdProviderPeserta' => $kodePPKPeserta,
                'tglDaftar'         => $tglFormat,
                'noKartu'           => "$nomorkartu",
                'kdPoli'            => "$kodepoli",
                'keluhan'           => "$Keluhan",
                'kunjSakit'         => true,
                'sistole'           => "$Tensi",       
                'diastole'          => "$TensiPer",
                'beratBadan'        => "$BB",
                'tinggiBadan'       => 0,
                'respRate'          => "$FrekuensiNadi",
                'lingkarPerut'      => 0,
                'heartRate'         => "$FrekuensiNafas",
                'rujukBalik'        => 0,
                'kdTkp'             => "10" 
                );

                // send antrean panggil
                date_default_timezone_set('Asia/Jakarta');
                $waktu = date('Y-m-d H:i:s');
                $convert = strtotime($waktu) * 1000;

                // send antrean panggil
                $payloadPanggil = [
                    "tanggalperiksa" => $tglAntrian,
                    "kodepoli" => "$kodepoli",
                    "nomorkartu" => "$nomorkartu",
                    "status" => 1, // hadir
                    "waktu" => $convert,
                ];

                $poli = $this->db->query("SELECT * from Poli where kodePoli = '$kodepoli'")->row_array();

                $cases = $this->db->query("SELECT * from Cases where [Case ID] = '$CaseID'")->row_array();
                
                $patientCode = $cases['PatientCode'];

                $patient = $this->db->query("SELECT * from Patient where [PatientCode] = '$patientCode'")->row_array();
                
                $doctor = $this->db->query("SELECT * from Doctor where [DoctorID] = '$DoctorID'")->row_array();
                
                $bpjsAntrian = $this->db->query("select * from BPJS_Antrian ba where CaseID = '$CaseID'")->row_array();

                $abdulradjak = $this->M_BpjsID->abdulradjak()->row_array();

                $payloadAddAntrean = [
                    "nomorkartu" => $bpjsAntrian['NomorKartu'],
                    "nik" => $bpjsAntrian['NIK'],
                    "nohp" => $bpjsAntrian['noHp'],
                    "kodepoli" => $bpjsAntrian['KodePoli'],
                    "namapoli" => $bpjsAntrian['NamaPoli'],
                    "norm" => $bpjsAntrian['noRm'],
                    "tanggalperiksa" => "$tglAntrian",
                    "kodedokter" => $bpjsAntrian['kodeDokter'],
                    "namadokter" => $doctor['FirstName'] . $doctor['LastName'] ,
                    "jampraktek" => $bpjsAntrian['jamPraktek'],
                    "nomorantrean" => $bpjsAntrian['NomorAntrean'],
                    "angkaantrean" => $bpjsAntrian['AngkaAntrean'],
                    "keterangan" => "",
                ];

                $this->SendAntreanPanggil($payloadPanggil);

                $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'];

                //print_r($result);exit();
                                
                //$this->AddAntreanPanggil($payloadAddAntrean);

                if (strpos($Unit, "POLI UMUM") !== false) {
                    $Unit = "POLI UMUM";
                }

               
                $this->db->query("UPDATE Antrian SET No_Panggil = No_Panggil + 1 where kodePoli ='$kodepoli'");
                // INSERT CASE ADMIN
                //$this->db->query("INSERT INTO CaseAdmin ([Case ID], [Unit], [DoctorID]) VALUES ('$caseterakhir','$Unit','$DoctorID')");


                // 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')");
               
                //updatestatus
                $this->db->query("UPDATE BPJS_Antrian SET isCaseDetail = '1', CaseID= '$caseterakhir', NomorAntrean = '$num' WHERE NomorKartu= '$nomorkartu' and tanggalperiksa = CONVERT(DATE,GETDATE(),101) and KodePoli = '$kodepoli' ");

                $this->session->set_flashdata("success", "Ok Data Berhasil Disimpan !");
                redirect('anamnesa/detail/' . $caseterakhir);
           
    }

    function GetNotAntrian($kodepoli){
        $ambilAntrian = $this->db->query("SELECT * FROM Antrian WHERE KodePoli = '$kodepoli'")->row_array();
        $ins = $ambilAntrian['No_Akhir'];
        $insAlias = $ambilAntrian['Alias'];
        $inserQueue = $insAlias.'.'.$ins;

        $up = $ins + 1;
        $this->db->query("UPDATE Antrian SET No_Akhir = '$up' where KodePoli = '$kodepoli'");

        return $insAlias.'.'.$up;
    }

    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 AddAntreanPanggil($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/addStatusPanggilAntrean");
        $result = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result, true);
    }

    public function formjkn($id)
    {
        $data['judul'] = "Klinik";
        $data['user'] = $this->db->get_where('userV2', ['username' => $this->session->userdata('username')])->row_array();
        $data['poli'] = $this->M_anamnesa->poli()->result_array();
        $data['dokter'] = $this->M_anamnesa->dokter()->result_array();
        $data['antrian'] = $this->db->query("SELECT * FROM Antrian")->result_array();
        $data['case'] = $this->db->query("SELECT * FROM Cases c, Patient p WHERE c.[PatientCode]=p.[PatientCode] AND p.[PatientCode] = '$id'")->row_array();
        $data['q'] = $this->db->query("Select b.NomorKartu
        from BPJS_Antrian b join Patient p on b.NomorKartu = p.EmployeeID
        join Poli po on po.kodePoli = b.KodePoli
        join Company co on co.CompanyCode = p.CompanyCode where isBatal is null and p.PatientCode = '$id'")->row_array();
        $data['tingkatnyeri'] = $this->db->query("SELECT * FROM erm_tingkat_nyeri")->result_array();
        $data['riwayatPenyakit'] = $this->db->query("SELECT * FROM tabelRiwayatPenyakit")->result_array();
       //$data['cppt'] = $this->M_rekamMedis->historicppt($id)->result_array();

        $data['alergiObat'] = $this->M_anamnesa->apigetalergi('01')['response']['list']['list'];


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

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

    public function cetakantrian($id){
        ob_start();
        $data['abdulradjak'] = $this->db->query("SELECT * FROM Utama")->row_array();
        $data['fr'] =  $this->db->query("SELECT * FROM CaseDetail c, Cases s,  Doctor d WHERE c.[Case ID]=s.[Case ID] AND c.[DoctorID]=d.[DoctorID] AND c.[Case ID] = '$id'")->row_array();
        $this->load->view('cetak/cetakantrian', $data);
        $isi = ob_get_clean();
        ob_end_clean();
        require_once('./aset/html2pdf/html2pdf.class.php');

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

           // $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 formmcu($id,$mr)
    {
        $data['judul'] = "Klinik";
        $data['user'] = $this->db->get_where('userV2', ['username' => $this->session->userdata('username')])->row_array();
        $data['poli'] = $this->M_anamnesa->poli()->result_array();
        $data['dokter'] = $this->M_anamnesa->dokter()->result_array();
        $data['antrian'] = $this->db->query("SELECT * FROM Antrian")->result_array();
        $data['case'] = $this->db->query("SELECT *, c.PlanNo as nokartu FROM Cases c, Patient p WHERE c.[PatientCode]=p.[PatientCode] AND [Case ID] = '$id'")->row_array();
        
        $data['tingkatnyeri'] = $this->db->query("SELECT * FROM erm_tingkat_nyeri")->result_array();
        $data['riwayatPenyakit'] = $this->db->query("SELECT * FROM tabelRiwayatPenyakit")->result_array();
        $cpptCase = $this->uri->segment(3);
        $mr = $this->uri->segment(4);
        $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();
        $data['caseId'] = $id;
        $data['HeaderLab'] = $this->M_rekamMedis->HeaderLab($id)->row_array();

        $this->load->model('M_Pendaftaran');
        $nokartu = $data['case']['nokartu'];
        
        $datapeserta = $this->M_Pendaftaran->peserta($nokartu);

        //print_r($datapeserta);exit();
        $data['kodePpkPeserta'] = $datapeserta['response']['list']['kdProviderPst']['kdProvider'];

        $this->load->model('M_BpjsID');
        $abdulradjak = $this->M_BpjsID->abdulradjak()->row_array();
        $data['kodePpkRs'] = $abdulradjak['KodePPK'];

        $data['IsKodePPKPesertaEqualRs'] = false;
        if($data['kodePpkPeserta'] == $data['kodePpkRs'] ){
            $data['IsKodePPKPesertaEqualRs'] = true;
        }

        $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'  " )->result_array();

        $data['header'] = $header = $this->db->query("Select top 1 * From LabRequestHeader where CaseID ='$id'")->row_array();
        $idheader = $header['IdRequestHeader'];
        $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();


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


public function prosesAnamnesismcu()
{
    $this->load->model('M_user');
    date_default_timezone_set("Asia/Jakarta");
    $user = $data['user'] = $this->M_user->getUserSession()->row_array();

    $CaseID = $this->input->post('case_id');
    $PatientCode = $this->input->post('PatientCode');
    $CompanyCode = $this->input->post('CompanyCode');
    $Nama = $this->input->post('nama');
    $Unit = $this->input->post('Unit');
    $DoctorID = $this->input->post('DoctorID');
    $Kesadaran_E = $this->input->post('Kesadaran_E');
    $Kesadaran_M = $this->input->post('Kesadaran_M');
    $Kesadaran_V = $this->input->post('Kesadaran_V');
    $Tensi = $this->input->post('Tensi');
    $TensiPer = $this->input->post('TensiPer');
    $Suhu = $this->input->post('Suhu');
    $FrekuensiNadi = $this->input->post('FrekuensiNadi');
    $FrekuensiNafas = $this->input->post('FrekuensiNafas');
    $TB = $this->input->post('TB');
    $BB = $this->input->post('BB');
    $IMT = $this->input->post('IMT');
    $lingkarperut = $this->input->post('lingkarperut');
    $LingkarKepala = $this->input->post('LingkarKepala');
    $Keluhan = $this->input->post('Keluhan');
    $tingkat_nyeri = $this->input->post('tingkat_nyeri');
    $pernahDirawat = $this->input->post('pernahDirawat');
    $KapanDirawat = $this->input->post('KapanDirawat');
    $DimanaDirawat = $this->input->post('DimanaDirawat');
    $SakitYangSama = $this->input->post('SakitYangSama');
    $Operasi = $this->input->post('Operasi');
    $RiwayatOperasi = $this->input->post('RiwayatOperasi');
    $PenyakitKeluarga = $this->input->post('PenyakitKeluarga');
    $RiwayatPenyakitKeluarga = $this->input->post('RiwayatPenyakitKeluarga');
    $RiwayatObatDiminum = $this->input->post('RiwayatObatDiminum');
    $alergi_obat = $this->input->post('alergi_obat');
    $usia_kunjungan = $this->input->post('usia_kunjungan');
    $Pisikososial = $this->input->post('Pisikososial');
    $Spiritual = $this->input->post('Spiritual');
    $bmi = $this->input->post('bmi');
    $ButaWarna = $this->input->post('butawarna');
    $riwayatsekarang = $this->input->post('riwayatsekarang');
    $riwayatsebelum = $this->input->post('riwayatsebelum');
    $jaminput = date('H:i:s');
    $tgl = date('Y-m-d');
    $intakeTime = date('H:i:s');

    // 🧠 CEK APAKAH DATA DENGAN CASEID SUDAH ADA
    $cek = $this->db->query("SELECT COUNT(*) AS jml FROM CaseDetail WHERE [Case ID] = '$CaseID'")->row_array();

    if ($cek['jml'] > 0) {
        // Jika sudah ada, tampilkan pesan dan jangan insert
        $this->session->set_flashdata("error", "Data untuk Case ID $CaseID sudah pernah diinput!");
         redirect('anamnesa/formmcu/'.$CaseID.'/'.$PatientCode);
        return;
    }

    // 🩺 INSERT DATA KE TABLE CaseDetail
    $this->db->query("INSERT INTO CaseDetail 
        ([Case ID], BeratBadan, TinggiBadan, Tensi, Diastole, Suhu, Keluhan, Unit, DoctorID, NoAntrian, iStatus, 
         respRate, heartRate, Kesadaran_E, Kesadaran_M, Kesadaran_V, IMT, LingkarKepala, tingkat_nyeri, 
         pernahDirawat, KapanDirawat, DimanaDirawat, SakitYangSama, Operasi, RiwayatOperasi, PenyakitKeluarga, 
         RiwayatPenyakitKeluarga, RiwayatObatDiminum, usia_kunjungan, alergi_obat, Psikososial, Spiritual,
         lingkarperut, jaminput, bmi, ButaWarna, RiwayatSebelum, RiwayatSekarang) 
    VALUES 
        ('$CaseID', '$BB', '$TB', '$Tensi', '$TensiPer', '$Suhu', '$Keluhan', '$Unit', '$DoctorID', '0', '0', 
         '$FrekuensiNafas', '$FrekuensiNadi', '$Kesadaran_E', '$Kesadaran_M', '$Kesadaran_V', '$IMT', '$LingkarKepala', 
         '$tingkat_nyeri', '$pernahDirawat', '$KapanDirawat', '$DimanaDirawat', '$SakitYangSama', '$Operasi', 
         '$RiwayatOperasi', '$PenyakitKeluarga', '$RiwayatPenyakitKeluarga', '$RiwayatObatDiminum', '$usia_kunjungan', 
         '$alergi_obat', '$Pisikososial', '$Spiritual', '$lingkarperut', '$jaminput', '$bmi', '$ButaWarna', 
         '$riwayatsebelum', '$riwayatsekarang')");

    // UPDATE tabel lain
    $this->db->query("UPDATE Cases SET CaseDetail = '1' WHERE [Case ID] = '$CaseID'");
    $this->db->query("UPDATE CaseAdmin SET DoctorID = '$DoctorID' WHERE [Case ID] = '$CaseID'");

    // Log aktivitas (opsional)
    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']);

    // Contoh jika ingin aktifkan kembali logging
    // $this->db->query("INSERT INTO TLOG (sKey,sTableName,sAction,dDate,sTime,sUser,sCompName) 
    // VALUES ('$CaseID','MCU','MCU','$tgl','$intakeTime','web','$hostname')");

    $this->session->set_flashdata("success", "Data anamnesis berhasil disimpan!");
    redirect('anamnesa/detail/' . $CaseID);
}


    public function frno($id)
    {
        $fr = $this->db->query("SELECT * FROM CaseDetail c, Cases s,  Doctor d WHERE c.[Case ID]=s.[Case ID] AND c.[DoctorID]=d.[DoctorID] AND c.[Case ID] = '$id'")->row_array();
        $abdulradjak = $this->db->query("SELECT * FROM Utama")->row_array();
    ?>
        <script>
            window.onload = function() {
                window.print();
                setTimeout(window.close, 500);
            };
        </script>
        <!doctype html>
        <html lang="en">

        <head>
            <!-- Required meta tags -->
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

            <!-- Bootstrap CSS -->
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

            <title>CETAK FR NO</title>

        </head>

        <body>

            <div align="center">
                <b>
                    ANTRIAN <br>
                    <?= $fr['Unit']; ?>
                </b>
                <br>
                <?= $fr['FirstName']; ?>
                <hr>
                <h2 style="font-weight: bolder;">
                    <?= $fr['NoAntrian']; ?>
                </h2>
                <?= $fr['Case ID']; ?> | <?= $fr['Description']; ?>
                <hr>
                Terima kasih telah menunggu.
                <br><br>
                <?php
                date_default_timezone_set("Asia/Jakarta");
                echo "<small>" . date('d F Y') . " " . $fr['Intake Time'] . "</small><br>";
                ?>
                <?= $abdulradjak['NamaPerusahaan']; ?>

            </div>

            <!-- Optional JavaScript -->
            <!-- jQuery first, then Popper.js, then Bootstrap JS -->
            <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
            <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
        </body>

        </html>
<?php
    }
}

