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

class Sks extends CI_Controller
{

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

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

    public function Simpansurat()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tgl  = date('Y-m-d');
        $Waktu = date('H:i');
        $caseid = $this->uri->segment(3);
        $patiencode = $this->uri->segment(4);
        $pengirim = $this->input->post('pengirim');
        $pilihan = $this->input->post('pilihan');
        $daritgl    = $this->input->post('daritgl');
        $sampaitgl  = $this->input->post('sampaitgl');
        $pilihketerangan = $this->input->post('pilihketerangan');
        $texlainya = $this->input->post('texlainya');

        $simpan = $this->db->query("
        INSERT INTO erm_surat( 
            case_id,
            keterangan,
            daritgl,
            sampaitgl,
            pengirim,
            tglbuat,
            waktubuat,
            note,
            texlainya
            )
            Values (
            '$caseid',
            '$pilihan',
            '$daritgl',
            '$sampaitgl',
            '$pengirim',
            '$tgl',
            '$Waktu',
            '$pilihketerangan',
            '$texlainya'
            )
        ");

        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Surat Berhasil DiBuat </div>');
        redirect('rekamMedis/pemeriksaan/' . $caseid . '/' . $patiencode);
    }

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

        ob_start();
        $data['d'] = $this->db->query("SELECT e.case_id,c.Description as nama,e.pengirim,e.daritgl,e.sampaitgl,c.[Presenting Problem] as diagnosa 
            FROM Cases c 
            JOIN erm_surat e ON c.[Case ID] = e.case_id
            WHERE e.case_id = '$id'")->row_array();

        // ============================ Qr Code =============================
        $this->load->library('ciqrcode');
        $params['data'] = $data['d']['pengirim'];
        $params['level'] = 'H';
        $params['size'] = 3;
        $params['savename'] = FCPATH . 'qr/' . $data['d']['pengirim'] . '.png';
        $this->ciqrcode->generate($params);

        // Load tampilan view ke buffer
        $this->load->view('cetakFR/cetaksuratsakit', $data);
        // $isi = ob_get_clean();

        // require_once('./aset/html2pdf/html2pdf.class.php');

        // try {
        //     // Ubah ukuran ke A5 (setengah A4)
        //     $html2pdf = new HTML2PDF('P', 'A5', 'en', false, 'ISO-8859-15', array(10, 5, 10, 5));
        //     $html2pdf->writeHTML($isi, isset($_GET['vuehtml']));
        //     $html2pdf->Output('resume.pdf');
        // } catch (HTML2PDF_exception $e) {
        //     echo $e->getMessage();
        //     exit;
        // }
    }

    

    public function Printformpendaftaran()
    {
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $user = $this->M_user->getUserSession()->row_array();
        ob_start();
        $this->load->view('cetakFR/cetakformpendaftaran', $data);
        $isi = ob_get_clean();

        require_once('./aset/html2pdf/html2pdf.class.php');

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

    public function PrintSuratSehat($id)
    {
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $user = $this->M_user->getUserSession()->row_array();
        ob_start();
        $data['qdata'] = $this->db->query("SELECT c.[Case ID],c.PatientCode,c.Description,p.DOBPlace,p.DOB,p.Sex,p.HomeAddress1 ,d.TinggiBadan,d.BeratBadan,d.Tensi,d.Diastole,d.Suhu,dk.[FirstName],er.keterangan,er.note,er.texlainya,dk.LastName,P.HomeCity
        FROM Cases c join Patient p on c.PatientCode = p.PatientCode
        join CaseDetail d on c.[Case ID] = d.[Case ID]
        join Doctor dk on dk.DoctorID = d.DoctorID
        join erm_surat er on er.case_id = c.[Case ID]
        WHERE er.case_id = '$id'")->row_array();
        $this->load->view('cetakFR/CetakSuratSehat', $data);
        $isi = ob_get_clean();

        require_once('./aset/html2pdf/html2pdf.class.php');

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

    public function PrintRujukan($id)
    {
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $user = $this->M_user->getUserSession()->row_array();
        ob_start();
        $data['qdata'] = $this->db->query("SELECT c.[Case ID],c.PatientCode,c.Description,p.Sex,p.Age,p.HomeAddress1,
        p.CellPhone,dt.FirstName,dt.LastName,er.pemeriksaan_fisik,er.diagnosa_primer,er.obat,er.keluhan_utama,i.DESCRPTION,
        er.poli_tujuan,er.instansi_tujuan
        FROM Cases c join Patient p on c.PatientCode = p.PatientCode
        join CaseDetail d on c.[Case ID] = d.[Case ID]
        join Doctor dt on d.DoctorID = dt.DoctorID
        join erm_pemeriksaan_fisik er on er.case_id = c.[Case ID]
        join ICD9 i on i.ICD_CODE = er.diagnosa_primer
        WHERE c.[Case ID] = '$id'")->row_array();
        $this->load->view('cetakFR/CetakRujukan', $data);
        $isi = ob_get_clean();

        require_once('./aset/html2pdf/html2pdf.class.php');

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

    public function cppt($caseid, $patiencode)
    {
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $user = $this->M_user->getUserSession()->row_array();
        $userLog = $user['username'];
        $dept = $user['dept'];

        date_default_timezone_set("Asia/Jakarta");
        $tgl    = date('Y-m-d');
        $waktu  = date('H:i');
        $resume = $this->input->post('resume');
        $keterangan = $this->input->post('keterangan');
        $Subjek    = $this->input->post('Subjek');
        $Objek     = $this->input->post('Objek');
        $Asesment  = $this->input->post('Asesment');
        $Penilaian = $this->input->post('Penilaian');

        // $simpan = $this->db->query("UPDATE erm_pemeriksaan_fisik SET ResumMedis = '$resume', StatusResume = '$keterangan', WaktuResume = '$waktu', TglResume = '$tgl' WHERE case_id = '$caseid'");   

        // riki
        $count = $this->db->query("SELECT * FROM HeaderCppt WHERE Note = '1' and Mr = '$patiencode'")->num_rows();
        if ($count > 0) {
            // --- update header cppt lama
            $update = $this->db->query("SELECT IdHeader FROM HeaderCppt WHERE Mr = '$patiencode' ORDER BY IdHeader DESC")->row_array();
            $setId = $update['IdHeader'];
            $this->db->query("UPDATE HeaderCppt SET Note = '$keterangan' WHERE IdHeader = '$setId'");
        } else {
            // --- tambah header cppt baru
            $getNomor = $this->db->query("SELECT NoUrut FROM Penomoran WHERE ModulAktivitas = 'CpptKlinik'")->row_array();
            $setId = $getNomor['NoUrut'];
            $upId = $getNomor['NoUrut'] + 1;
            $this->db->query("UPDATE Penomoran SET NoUrut = '$upId' WHERE ModulAktivitas = 'CpptKlinik'");
            $this->db->query("INSERT INTO HeaderCppt (IdHeader, Mr, DateHeader, TimeHeader, Note) VALUES ('$setId' ,'$patiencode', '$tgl', '$waktu', '$keterangan')");
        }

        $this->db->query("INSERT INTO DetailCppt (IdHeader, CaseId, DateDetail, TimeDetail, UserCategory, UserCreated, Description, Subjek, Objek, Asesment, Penilaian) VALUES ('$setId', '$caseid', '$tgl', '$waktu', '$dept', '$userLog', '$resume', '$Subjek','$Objek','$Asesment','$Penilaian')");

        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Cppt Berhasil DiBuat </div>');
        // redirect('rekamMedis/pemeriksaan/' . $caseid . '/' . $patiencode);
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function PrintketeranganBerobat($id)
    {
        $data['abdulradjak'] = $this->M_Utama->abdulradjak()->row_array();
        $abdulradjak = $this->M_Utama->abdulradjak()->row_array();
        $pageAbdulRadjak = $abdulradjak['NamaPerusahaan'];
        $data['judul'] = $pageAbdulRadjak;
        $data['user'] = $user = $this->M_user->getUserSession()->row_array();
      
        ob_start();
        $data['qdata'] = $this->db->query("SELECT c.[Case ID],c.PatientCode,c.Description,p.DOBPlace,p.DOB,p.Sex,p.HomeAddress1 ,d.TinggiBadan,d.BeratBadan,d.Tensi,d.Diastole,d.Suhu,dk.[FirstName],er.keterangan,er.note,er.texlainya,dk.LastName,P.HomeCity,er.daritgl,er.pengirim,er.alamat,er.istri,er.pekerjaan,er.keluhan,er.waktubuat
        FROM Cases c join Patient p on c.PatientCode = p.PatientCode
        join CaseDetail d on c.[Case ID] = d.[Case ID]
        join Doctor dk on dk.DoctorID = d.DoctorID
        join erm_surat er on er.case_id = c.[Case ID]
        WHERE er.case_id = '$id'")->row_array();
        // ============================ Qr Code =============================
        $this->load->library('ciqrcode');
        $params['data'] = $data['qdata']['FirstName'];
        $params['level'] = 'H';
        $params['size'] = 3;
        $params['savename'] = FCPATH . 'qr/' . $data['qdata']['FirstName'] . '.png';
        $this->ciqrcode->generate($params);
       
       $this->load->view('cetakFR/Cetak_keterangan_berobat', $data);
        $isi = ob_get_clean();

        require_once('./aset/html2pdf/html2pdf.class.php');

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

    public function Simpansuratberobat()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tgl  = date('Y-m-d');
        $Waktu = date('H:i');
        $caseid = $this->uri->segment(3);
        $pengirim = $this->input->post('nama');
        $istri = $this->input->post('istri');
        $pekerjaan = $this->input->post('pekerjaan');
        $tglberobat  = $this->input->post('tglberobat');
        $alamat = $this->input->post('alamat');
        $keluhan = $this->input->post('keluhan');
        $keterangan = $this->input->post('keterangan');

        $simpan = $this->db->query("
        INSERT INTO erm_surat( 
            case_id,
            keterangan,
            daritgl,
            pengirim,
            tglbuat,
            waktubuat,
            alamat,
            istri,
            pekerjaan,
            keluhan,
            jenis_surat
            )
            Values (
            '$caseid',
            '$keterangan',
            '$tglberobat',
            '$pengirim',
            '$tgl',
            '$Waktu',
            '$alamat',
            '$istri',
            '$pekerjaan',
            '$keluhan',
            'Surat Keterangan Berobat'
            )
        ");

        redirect('sks/PrintketeranganBerobat/'.$caseid);
    }

    // Hapus surat berobat berdasarkan ID (primary key IdSurat di tabel erm_surat)
    public function HapusSuratBerobat($id)
    {
        // Hapus record
        $this->db->where('IdSurat', $id);
        $this->db->delete('erm_surat');

        // Kembalikan ke halaman sebelumnya
        redirect($_SERVER['HTTP_REFERER']);
    }

    // Tampilkan data surat (untuk edit) dan proses update
    public function UpdateSuratBerobat($id)
    {
        // Ambil input dari form
        $pengirim = $this->input->post('nama');
        $istri = $this->input->post('istri');
        $pekerjaan = $this->input->post('pekerjaan');
        $tglberobat  = $this->input->post('tglberobat');
        $alamat = $this->input->post('alamat');
        $keluhan = $this->input->post('keluhan');
        $keterangan = $this->input->post('keterangan');

        $data = [
            'pengirim' => $pengirim,
            'istri' => $istri,
            'pekerjaan' => $pekerjaan,
            'daritgl' => $tglberobat,
            'alamat' => $alamat,
            'keluhan' => $keluhan,
            'keterangan' => $keterangan
        ];

        $this->db->where('IdSurat', $id);
        $this->db->update('erm_surat', $data);

        // Redirect kembali
       redirect('sks/PrintketeranganBerobat/'.$caseid);
    }
}