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

class Obat 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 ProsesObat()
    {
        date_default_timezone_set("Asia/Jakarta");
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $sistem = $this->db->query("SELECT * FROM SystemNo where SystemName ='Trans'")->row_array();
        $nomor  = '3'.$sistem['NoNumeric'];
        $updateNomor = $sistem['NoNumeric'] + 1;
        $this->db->query("UPDATE SystemNo SET NoNumeric = '$updateNomor' where SystemName = 'Trans'");
        $caseID = $this->uri->segment(3);
        $mr     = $this->uri->segment(4);
        $tgl    = date('Y-m-d');
        $waktu  = date('H:i');
       
        $userPembuat = $this->input->post('user');
        $DoctorID    = $this->input->post('idDokter');
        $obat = $this->input->post('obat');
        $qty = $this->input->post('qty');
        $satuan = $this->input->post('satuan');
        $aturan_pakai = $this->input->post('aturan_pakai');
        $cara_pakai = $this->input->post('cara_pakai');
        $keterangan = $this->input->post('keterangan');
        $orderObat = count($obat);
        date_default_timezone_set("Asia/Jakarta");
        $intakeTime = date('H:i');
        $tgl = date('Y-m-d');
        $wareHouseCode = $this->session->userdata('wareHouseCode');

            //InsertObat
            $this->db->query("INSERT INTO Resep_Header (ResepId, CaseID, DoctorId, WHCode, Category, PatientCode, IntakeDate, [Status], Alergi, Jenis, AddTrans) VALUES ('$nomor','$caseID','$DoctorID','$wareHouseCode','OP','$mr','$tgl','1','Tidak Ada', 'NON-RACIKAN', '0')");
            for ($x = 0; $x < $orderObat; $x++) {
                $splitX = explode(' ', $obat[$x]);
                $this->db->query("INSERT INTO Resep_Detail (ResepId,PharmacyCode,iQty,qtyUnit,frekuensi,Ket,CaraPakai) VALUES ('$nomor','$splitX[0]','$qty[$x]','$satuan[$x]','$aturan_pakai[$x]','$keterangan[$x]','$cara_pakai[$x]')");
                $this->db->query("INSERT INTO erm_resepObat (ResepId,PharmacyCode,iQty,qtyUnit,frekuensi,Ket,CaraPakai) VALUES ('$nomor','$splitX[0]','$qty[$x]','$satuan[$x]','$aturan_pakai[$x]','$keterangan[$x]','$cara_pakai[$x]')");
            }

               //INSERTTLOG
                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 ('$caseID','Resep_Detail','ADD','$tgl','$intakeTime','web-$userPembuat','$hostname')");

            $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil DiTambahkan X </div>');
            redirect('rekamMedis/pemeriksaan/' . $caseID) .'/'.$mr;

    }

    Public function prosesRacikan()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $tm = date('H:i:s');
        $time = date('H:i');
        $indate = date('Y-m-d H:i:s');
        $cek = $_POST['cek'];
        $caseID = $this->uri->segment(3);
        $mr     = $this->uri->segment(4);
        $jumlah_dipilih = count($cek) + 1;

        $Jenis = $this->input->post('Jenis');
        $QtyJenis = $this->input->post('QtyJenis');
        $Frekuensi = $this->input->post('Frekuensi');
        $AturanPakai = $this->input->post('AturanPakai');
        $Keterangan = $this->input->post('Keterangan');
        $DoctorID = $this->input->post('DokterPengirim');
        $Jumlah = $this->input->post('Jumlah');
        $SatuanRacikan = $this->input->post('SatuanRacikan');
        $userPembuat = $this->input->post('user');
        $nameracik = $this->input->post('namaracikan');

        $Obat = $this->input->post('Obat');
        // $Note = $this->input->post('Note');

        $sistem = $this->db->query("SELECT * FROM SystemNo where SystemName ='Trans'")->row_array();
        $nomor  = '3'.$sistem['NoNumeric'];
        $updateNomor = $sistem['NoNumeric'] + 1;
        $this->db->query("UPDATE SystemNo SET NoNumeric = '$updateNomor' where SystemName = 'Trans'");

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

        $this->db->query("INSERT INTO Resep_Header 
            (
            ResepId,
            CaseID,
            DoctorId,
            WHCode,
            Category,
            PatientCode,
            InTakeDate,
            [Status],
            Alergi,
            Jenis,
            StatusPembuatan,
            AddTrans
            ) VALUES (
            '$nomor',
            '$caseID',
            '$DoctorID',
            '$wareHouseCode',
            'OP',
            '$mr',
            '$indate',
            '1',
            'Tidak Ada',
            'RACIKAN',
            '0',
            '0'
            )
        ");

        $sRacikan = $this->db->query("SELECT * FROM Penomoran WHERE ModulAktivitas = 'Racikan'")->row_array();
        $RacikanNo = $sRacikan['NoUrut'];
        $RacikanNoUp = $RacikanNo + 1;
        $this->db->query("UPDATE Penomoran SET NoUrut = '$RacikanNoUp' WHERE ModulAktivitas = 'Racikan'");

        $this->db->query("INSERT INTO Resep_Racikan_H 
        (
        IdRacikan,
        ResepId,
        [Case ID],
        PatientCode,
        NamaRacikan,
        QtyRacikan,
        UnitRacikan,
        Frekuensi,
        Cara,
        [Status],
        Jenis
        ) VALUES (
        '$RacikanNo',
        '$nomor',
        '$caseID',
        '$mr',
        '$nameracik',
        '$QtyJenis',
        '$SatuanRacikan',
        '$Frekuensi',
        '$AturanPakai',
        '1',
        'Racikan'
        )
    ");


        for ($x = 0; $x < $jumlah_dipilih; $x++) {
            $this->db->query("INSERT INTO Resep_Racikan_D (
                ResepID,
                PharmacyCode,
                iQty,
                IdRacikan,
                Ket
            ) VALUES (
                '$nomor',
                '$Obat[$x]',
                '$Jumlah[$x]',
                '$RacikanNo',
                '$Keterangan[$x]'

            )");

            $this->db->query("INSERT INTO erm_racikObat (
                ResepID,
                PharmacyCode,
                iQty,
                IdRacikan,
                Ket
            ) VALUES (
                '$nomor',
                '$Obat[$x]',
                '$Jumlah[$x]',
                '$RacikanNo',
                '$Keterangan[$x]'

            )");
        }

           //INSERTTLOG
           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 ('$caseID','Resep_Detail','ADD','$tgl','$time','web-$userPembuat','$hostname')");
        redirect('rekamMedis/pemeriksaan/' . $caseID) .'/'.$mr;

    }

    public function prosesHeaderObat()
    {
        date_default_timezone_set("Asia/Jakarta");
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $caseID       = $this->uri->segment(3);
        $resepid      = $this->uri->segment(4);
        $tgl    = date('Y-m-d');
        $waktu  = date('H:i');
        $sistem = $this->db->query("SELECT * FROM Resep_Header where ResepId ='$resepid'")->row_array();
        $noheader = $sistem['ResepId'];
       
        $userPembuat = $this->input->post('user');
        $DoctorID    = $this->input->post('idDokter');
        $obat        = $this->input->post('kodeObat');
        $qty         = $this->input->post('qty');
        $satuan       = $this->input->post('satuan');
        $aturan_pakai = $this->input->post('dosisPakai');
        $cara_pakai = $this->input->post('caraPakai');
        $keterangan = $this->input->post('keterangan');
        $orderObat = count($obat);
        date_default_timezone_set("Asia/Jakarta");
        $intakeTime = date('H:i');
        $tgl = date('Y-m-d');

       
            //InsertObat
            for ($x = 0; $x < $orderObat; $x++) {
                $splitX = explode(' ', $obat[$x]);
                $this->db->query("INSERT INTO Resep_Detail (ResepId,PharmacyCode,iQty,qtyUnit,frekuensi,Ket,CaraPakai) VALUES ('$noheader','$splitX[0]','$qty[$x]','$satuan[$x]','$aturan_pakai[$x]','$keterangan[$x]','$cara_pakai[$x]')");
            }
       
        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil DiTambahkan. </div>'); 
        redirect('Apotik/rDetail/' . $caseID .'/'.$noheader);
    }

    public function prosesRacikanoheader()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $tm = date('H:i:s');
        $time = date('H:i');
        $indate = date('Y-m-d H:i:s');
        $cek = $_POST['cek'];
        $caseID = $this->uri->segment(3);
        $mr     = $this->uri->segment(4);
        $jumlah_dipilih = count($cek) + 1;

        $Jenis = $this->input->post('Jenis');
        $QtyJenis = $this->input->post('QtyJenis');
        $Frekuensi = $this->input->post('Frekuensi');
        $AturanPakai = $this->input->post('AturanPakai');
        $Keterangan = $this->input->post('Keterangan');
        $DoctorID = $this->input->post('DokterPengirim');
        $Jumlah = $this->input->post('Jumlah');
        $SatuanRacikan = $this->input->post('SatuanRacikan');
        $userPembuat = $this->input->post('user');
        $nameracik = $this->input->post('namaracikan');
        $Obat = $this->input->post('Obat');
        $idracikan = $this->uri->segment(4);

        $sRacikan = $this->db->query("SELECT * FROM Resep_Racikan_H WHERE ResepId = '$idracikan'")->row_array();
        $RacikanNo = $sRacikan['ResepId'];
        $nomor = $sRacikan['IdRacikan'];

        for ($x = 0; $x < $jumlah_dipilih; $x++) {
            $this->db->query("INSERT INTO Resep_Racikan_D (
                ResepID,
                PharmacyCode,
                iQty,
                IdRacikan,
                Ket
            ) VALUES (
                '$RacikanNo',
                '$Obat[$x]',
                '$Jumlah[$x]',
                '$nomor',
                '$Keterangan[$x]'

            )");
        }

           //INSERTTLOG
           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 ('$caseID','Resep_Detail','ADD','$tgl','$time','web-$userPembuat','$hostname')");
        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil DiTambahkan. </div>'); 
        redirect('rekamMedis/pemeriksaan/' . $caseID) .'/'.$mr;
    }

    public function hapusdetailApotekRacikan($id,$case)
    {
        extract($_GET);
        $iddokter = $doct;
        $idresep = $this->uri->segment(5);
        $this->db->query("DELETE FROM Resep_Racikan_D WHERE PharmacyCode= '$id'");
        $this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert"> Data Berhasil Dihapus </div>');
        redirect('apotik/detailApotekRacikan'.'/'.$idresep.'?case='.$case.'&doct='.$iddokter); 
    }

    public function prosesDetailRacikanoheader()
    {
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $tm = date('H:i:s');
        $time = date('H:i');
        $indate = date('Y-m-d H:i:s');
        $cek = $_POST['cek'];
        $caseID = $this->uri->segment(3);
        $mr     = $this->uri->segment(4);
        $jumlah_dipilih = count($cek) + 1;

        $Jenis = $this->input->post('Jenis');
        $QtyJenis = $this->input->post('QtyJenis');
        $Frekuensi = $this->input->post('Frekuensi');
        $AturanPakai = $this->input->post('AturanPakai');
        $Keterangan = $this->input->post('Keterangan');
        $DoctorID = $this->input->post('DokterPengirim');
        $Jumlah = $this->input->post('Jumlah');
        $SatuanRacikan = $this->input->post('SatuanRacikan');
        $userPembuat = $this->input->post('user');
        $nameracik = $this->input->post('namaracikan');
        $Obat = $this->input->post('Obat');
        $idracikan = $this->uri->segment(4);

        $sRacikan = $this->db->query("SELECT * FROM Resep_Racikan_H WHERE ResepId = '$caseID'")->row_array();
        $RacikanNo = $sRacikan['ResepId'];
        $nomor = $sRacikan['IdRacikan'];
        $idkunjungan = $sRacikan['Case ID'];

        for ($x = 0; $x < $jumlah_dipilih; $x++) {
            $this->db->query("INSERT INTO Resep_Racikan_D (
                ResepID,
                PharmacyCode,
                iQty,
                IdRacikan,
                Ket
            ) VALUES (
                '$RacikanNo',
                '$Obat[$x]',
                '$Jumlah[$x]',
                '$nomor',
                '$Keterangan[$x]'

            )");
        }

           //INSERTTLOG
           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 ('$idkunjungan','Resep_Detail','ADD','$tgl','$time','web-$userPembuat','$hostname')");
        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil DiTambahkan. </div>'); 
        redirect('apotik/detailApotekRacikan'.'/'.$caseID.'?case='.$idkunjungan.'&doct='); 
    }

    public function updateDetailMonitor()
    {
        $Id = $this->input->post('Id');
        $resep = $this->input->post('resep');
        $case = $this->input->post('case');
        $doct = $this->input->post('doct');
        $Resep_ID = $this->input->post('Resep_ID');
        $ProcedureCode = $this->input->post('ProcedureCode');
        $Qty = $this->input->post('Qty');
        $frekuensi = $this->input->post('frekuensi');
        $CaraPakai = $this->input->post('CaraPakai');
        $ket = $this->input->post('ket');
        $JumlahSatuanPakai = $this->input->post('JumlahSatuanPakai');
        $this->db->query("UPDATE Resep_Detail SET PharmacyCode = '$ProcedureCode' , iQty = '$Qty', frekuensi = '$frekuensi', CaraPakai = '$CaraPakai', Ket = '$ket' WHERE Id = '$Id' ");
        // TLOG
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $tm = date('H:i');
        $user = $this->db->get_where('userV2', ['UserName' => $this->session->userdata('UserName')])->row_array();
        $namaUser = $user['Name'];

        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 ('$Id','Resep_Detail','UPDATE', '$tgl', '$tm', '$namaUser','$hostname')");

        $this->session->set_flashdata("success", "Berhasil diupdate!");
        redirect('apotik/detailApotekTrans/' . $resep . '?case=' . $case . '&doct=' . $doct);
    }

    public function tambahDetailMonitor()
    {
        $resep = $this->input->post('resep');
        $case = $this->input->post('case');
        $doct = $this->input->post('doct');
        $Resep_ID = $this->input->post('Resep_ID');
        $ProcedureCode = $this->input->post('ProcedureCode');
        $Qty = $this->input->post('Qty');
        $frekuensi = $this->input->post('frekuensi');
        $CaraPakai = $this->input->post('CaraPakai');
        $ket = $this->input->post('ket');
        $this->db->query("INSERT INTO Resep_Detail (ResepId, PharmacyCode, iQty, frekuensi, CaraPakai, dosisQty, Ket) VALUES ('$Resep_ID', '$ProcedureCode','$Qty','$frekuensi','$CaraPakai','0','$ket')");
        $this->session->set_flashdata("success", "Berhasil Ditambahkan!");
        redirect('apotik/detailApotekTrans/' . $resep . '?case=' . $case . '&doct=' . $doct);
    }

    public function hapusObatDetail($id, $resep, $case, $doc)
    {
        $this->db->query("DELETE FROM Resep_Detail WHERE Id = '$id'");
        // TLOG
        date_default_timezone_set("Asia/Jakarta");
        $tgl = date('Y-m-d');
        $tm = date('H:i');
        $user = $this->db->get_where('userV2', ['UserName' => $this->session->userdata('UserName')])->row_array();
        $namaUser = $user['Name'];

        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 ('$id','Resep_Detail','DELETE', '$tgl', '$tm', '$namaUser','$hostname')");

        $this->session->set_flashdata("success", "Berhasil hapus!");
        redirect('Apotik/detailApotekTrans/' . $resep . '?case=' . $case . '&doct=' . $doc);
    }

    public function prosestambahtransaksiobat()
    {
        date_default_timezone_set("Asia/Jakarta");
        $data['user'] = $this->M_user->getUserSession()->row_array();
        $caseID = $this->uri->segment('3');
        $PatientCode = $this->uri->segment('4');
        $DoctorID = $this->input->post('idDokter');
        $user = $this->input->post('user');
        $obat        = $this->input->post('kodeObat');
        $qty         = $this->input->post('qty');
        $satuan       = $this->input->post('satuan');
        $aturan_pakai = $this->input->post('dosisPakai');
        $cara_pakai = $this->input->post('caraPakai');
        $keterangan = $this->input->post('keterangan');
        $Transaction_Date = date('Y-m-d');
        $Transaction_Time = date('Y-m-d H:i:s');
        $indate = date('Y-m-d H:i:s');

        $no = $this->db->query("SELECT * FROM SystemNo WHERE SystemName = 'Trans'")->row_array();
        $noAwal = $no['NoNumeric'] + 1;
        $this->db->query("UPDATE SystemNo SET NoNumeric = '$noAwal' WHERE SystemName = 'Trans'");
        $nomor = '3' . $no['NoNumeric'];

        // $this->db->query("
        //         INSERT INTO ApotikHeader (
        //             TransactionID,
        //             [Case ID],
        //             PatientCode,
        //             Transaction_Date,
        //             Transaction_Time,
        //             PresNo,
        //             DoctorID,
        //             Class,
        //             UserCreated,
        //             DateCreated,
        //             Type,
        //             LastUserModified,
        //             LastDateModified
        //             ) 
        //         VALUES (
        //             '$nomor',
        //             '$caseID',
        //             '$PatientCode',
        //             '$Transaction_Date',
        //             '$Transaction_Time',
        //             '$nomor',
        //             '$DoctorID',
        //             'OP',
        //             '$user',
        //             '$Transaction_Time',
        //             'SALE',
        //             '$user',
        //             '$Transaction_Time'
        //         )
        //     ");

        $aPharmacyCode = $obat;
        $aQuery = $this->db->query("exec Sp_DrugsPriceWeb  '" . $aPharmacyCode . "'   ")->row_array();
        $c = $aQuery['NettPrice'];
        $this->db->query("INSERT INTO [Activity Drugs] (
                TransactionID,
                [Case ID],
                Unit,
                DrugsID,
                Charge,
                Qty,
                BasicPrice,
                UnitPrice,
                FromDepo,
                Shift,
                DateCreated,
                UserCreated,
                PPN,
                Dosis,
                Cara,
                Ket
        ) VALUES (
            '$nomor',
            '$caseID',
            '0',
            '$obat',
            '0',
            '$qty',
            '$c',
            '$0',
            '1',
            '1',
            '$Transaction_Date',
            '$user',
            '0',
            '$aturan_pakai',
            '$cara_pakai',
            '$keterangan'
        )");

            

        $this->session->set_flashdata("success", "Berhasil ditambah!");
        redirect('apotik/transaksiPharmacy/' . $caseID);
    }

    public function updateracikan($Id)
    {
        $namaobat = $this->input->post('namaobat');
        $qty      =  $this->input->post('qty');
        $this->db->query("UPDATE Resep_Racikan_D SET PharmacyCode = '$namaobat' , iQty = '$qty' WHERE PharmacyCode = '$Id' ");

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


}