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

class Transaction 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->model('M_rekamMedis');
        $this->load->model('M_anamnesa');
        $this->load->model('M_Transaksi');
        $this->load->helper('url');

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


    public function index()
    {
        $tgl = date('Y-m-d');
        $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();

        $statusParam = $this->input->get('status');
        if(empty($statusParam)){
            $statusParam = "OPEN";
        }
        $data['statusParam'] = $statusParam;

        $data['nomr'] = $this->db->query("Select c.[Case ID],c.Description,co.CompanyName,ca.Unit,c.[Intake Date],d.FirstName,c.[Case Status]
        from Cases c join CaseAdmin ca on c.[Case ID] = ca.[Case ID] 
        Join Company co on co.CompanyCode = c.CompanyCode 
        join Doctor d on d.DoctorID = ca.DoctorID where  [PatientCode] IS NULL and c.[Intake Date] ='$tgl' ")->result_array();
        $data['pasien'] = $this->M_rekamMedis->transaksipasien(strtoupper($statusParam))->result_array();
        $data['poli'] = $this->M_anamnesa->poli()->result_array();
        $data['dokter'] = $this->M_anamnesa->dokter()->result_array();
        $data['trans1'] = $this->M_Transaksi->detail()->result_array();
        //$data['count'] = $this->M_Transaksi->count()->row_array();

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

    public function AddTransaction($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();
        $data['dokter'] = $this->M_Transaksi->getdokter()->result_array();
        $data['category'] = $this->M_Transaksi->getcategory()->result_array();
        $data['tindakan'] = $this->M_Transaksi->gettreatment()->result_array();
        $data['trans'] = $this->M_Transaksi->getTrans($id)->result_array();

        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('transaction/AddTransaction', $data);
        $this->load->view('properti/footer', $data);

    }

    public function detailtrans($id,$idtrx)
    {
        $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();
        $data['dokter'] = $this->M_Transaksi->getdokter()->result_array();
        $data['tindakan'] = $this->M_Transaksi->gettreatment()->result_array();
        $data['category'] = $this->M_Transaksi->getcategory()->result_array();
        $data['trans1'] = $this->M_Transaksi->getDetailTrans($id,$idtrx)->result_array();

        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('transaction/detailtrans', $data);
        $this->load->view('properti/footer', $data);

    }

    public function EditTransaction($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();
        $data['dokter'] = $this->M_Transaksi->getdokter()->result_array();
        $data['tindakan'] = $this->M_Transaksi->gettreatment()->result_array();
        $data['category'] = $this->M_Transaksi->getcategory()->result_array();
        $data['get'] = $this->M_Transaksi->getedit($id)->result_array();

        $this->load->view('properti/header', $data);
        $this->load->view('properti/menu', $data);
        $this->load->view('transaction/edit', $data);
        $this->load->view('properti/footer', $data);

    }

    public function DaftarTindakan()
    {
        $category = $this->input->post('category');
        $query = $this->db->query("SELECT M.[ProcedureCode] ,M.[Description] ,M.[Category] ,M.[Active] ,M.[COA] ,mp.Class ,mp.Price
        FROM [tegalann].[dbo].[MedicalProcedure] M LEFT JOIN MedicalProcedurePrice MP ON M.ProcedureCode = mp.ProcedureCode where Category = '$category' AND  Active = 'T'")->result();
        $cari = $this->input->post('cari');
        if ($cari != '') {
           $query = $this->db->query("SELECT M.[ProcedureCode] ,M.[Description] ,M.[Category] ,M.[Active] ,M.[COA] ,mp.Class ,mp.Price
           FROM [tegalann].[dbo].[MedicalProcedure] M LEFT JOIN MedicalProcedurePrice MP ON M.ProcedureCode = mp.ProcedureCode where Category = '$category' AND  Description like '%$cari%' ")->result();
        }
    
        echo json_encode($query);;
    }

    public function prosesAddTreatment()
    {
        $CaseID     = $this->input->post('caseID');
        $mr         = $this->input->post('mr');
        $Class      = $this->input->post('class');
        $user       = $this->input->post('user');
        $DoctorID       = $this->input->post('dokter');
        $Refrensi       = $this->input->post('refrensi');
        $KodeTransaksi  = $this->input->post('kodetindakan');
        $harga          = $this->input->post('harga');
        $coa            = $this->input->post('coa');
        $order  = count($KodeTransaksi);
        date_default_timezone_set("Asia/Jakarta");
        $Transaction_Date = date('Y-m-d');
        $Transaction_Time = date('Y-m-d H:i:s');
        $time = date('H:i');
        $cekidtransaksi     = $this->input->post('cekidtransaksi');
        $idtransaksi     = $this->input->post('idtransaksi');

        //CekID
        if ($cekidtransaksi > 0) {
            $this->db->query("
            INSERT INTO Activity ( 
                DoctorID,
                [Case ID],
                TransactionID,
                Unit,
                Activity,
                Charge,
                COA
                )
                Values (
                '$DoctorID',
                '$CaseID',
                '$idtransaksi',
                '0',
                '$KodeTransaksi',
                '$harga',
                '$coa'
                    )
                ");


            //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','Activity','ADD','$Transaction_Date','$time','web-$user','$hostname')");
            $this->db->query("exec ACC_ActivityJournal '" . $idtransaksi . "' , '" . $user . "', '" . $hostname . "' ");

        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil DiTambahkan </div>');
        redirect('Transaction/detailTransaction/' . $CaseID .'/'.$idtransaksi);
 
    }else{

        $no = $this->db->query("SELECT * FROM SystemNo WHERE SystemName = 'Trans'")->row_array();
        $nomor = '1' . $no['NoNumeric'];
        $noAwal = $no['NoNumeric'] + 1;
        $this->db->query("UPDATE SystemNo SET NoNumeric = '$noAwal' WHERE SystemName = 'Trans'");
    
        $this->db->query("
                INSERT INTO TransactionHeader (
                    TransactionID,
                    [Case ID],
                    PatientCode,
                    Transaction_Date,
                    Transaction_Time,
                    DoctorID,
                    SurgeryDate,
                    SurgeryTime,
                    Class,
                    RefferedBy,
                    UserCreated,
                    DateCreated,
                    LockPosting
                    ) 
                VALUES (
                    '$nomor',
                    '$CaseID',
                    '$mr',
                    '$Transaction_Date',
                    '$Transaction_Time',
                    '$DoctorID',
                    '$Transaction_Date',
                    'F',
                    '$Class',
                    '$Refrensi',
                    '$user',
                    '$Transaction_Time',
                    '0'
                )
            ");


            $this->db->query("
            INSERT INTO Activity ( 
                DoctorID,
                [Case ID],
                TransactionID,
                Unit,
                Activity,
                Charge,
                COA
                )
                Values (
                '$DoctorID',
                '$CaseID',
                '$nomor',
                '0',
                '$KodeTransaksi',
                '$harga',
                '$coa'
                    )
                ");
                
                //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','Activity','ADD','$Transaction_Date','$time','web-$user','$hostname')");
                $this->db->query("exec ACC_ActivityJournal '" . $idtransaksi . "' , '" . $user . "', '" . $hostname . "' ");

                $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil DiTambahkan </div>');
                redirect('Transaction/detailTransaction/' . $CaseID .'/'.$nomor);     
    
}
  }

  public function DeletItems($id,$trx)
  {
    $this->db->delete('Activity', ['ID' => $id]);
    $data['user'] = $user = $this->M_user->getUserSession()->row_array();
    $pengirim = $user['nama'];

     //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("exec ACC_ActivityJournal '" . $trx . "' , '" . $pengirim . "', '" . $hostname . "' ");
    $this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert"> Data Berhasil Dihapus </div>');
    $caseid = $this->uri->segment(5);
    redirect('Transaction/detailheader/'.$caseid);
  }

  public function DeleteTransaction($id)
  {
    date_default_timezone_set("Asia/Jakarta");
    $this->db->delete('Activity', ['TransactionID' => $id]);
    $this->db->delete('TransactionHeader', ['TransactionID' => $id]);

    $user = $this->M_user->getUserSession()->row_array();
    $username = $user['nama'];
    $tgl = date('Y-m-d');
    $time = date('H:i');
     //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 ('$id','Activity','DELETE','$tgl','$time','web-$username','$hostname')");
    $this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert"> Data Berhasil Dihapus </div>');
    redirect($_SERVER['HTTP_REFERER']);
  }

  public function UpdateTransaction($id)
  {
    $DoctorID       = $this->input->post('dokter');
    $tindakan       = $this->input->post('tindakan');
    $harga          = $this->input->post('harga');
    $this->db->query("UPDATE Activity SET Activity = '$tindakan', DoctorID = '$DoctorID', Charge = '$harga' WHERE ID = '$id'");
    $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil di Update </div>');
    redirect($_SERVER['HTTP_REFERER']); 
}

public function save()
{
    $CaseID     = $this->input->post('caseID');
    $mr         = $this->input->post('mr');
    $Class      = $this->input->post('class');
    $user       = $this->input->post('user');
    $DoctorID       = $this->input->post('dokter');
    $Refrensi       = $this->input->post('refrensi');
    $doktername     = $this->input->post('doktername');
    date_default_timezone_set("Asia/Jakarta");
    $Transaction_Date = date('Y-m-d');
    $Transaction_Time = date('Y-m-d H:i:s');
    $time = date('H:i');
    $namatindakan         = $this->input->post('namatindakan');
    $order                = count($namatindakan);
    $dokter               = $this->input->post('dokter');
    $harga                = $this->input->post('harga');
    $coa                  = $_POST['Coa'];

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

    //INSERT TRANSACTIONHEADER 
    $this->db->query("
    INSERT INTO TransactionHeader (
        TransactionID,
        [Case ID],
        PatientCode,
        Transaction_Date,
        Transaction_Time,
        DoctorID,
        SurgeryDate,
        SurgeryTime,
        Class,
        RefferedBy,
        UserCreated,
        DateCreated,
        LockPosting
        ) 
    VALUES (
        '$nomor',
        '$CaseID',
        '$mr',
        '$Transaction_Date',
        '$Transaction_Time',
        '$doktername',
        '$Transaction_Date',
        'F',
        '$Class',
        '$Refrensi',
        '$user',
        '$Transaction_Time',
        '0'
    )
");

    //INSERT AVTIVITY TREATMENT TINDAKAN
    for ($x = 0; $x < $order; $x++) {
        $splitX = explode(' ', $namatindakan[$x]);
        $this->db->query("INSERT INTO Activity (DoctorID,[Case ID],TransactionID,Unit,Activity,Charge,COA) VALUES ('$DoctorID[$x]','$CaseID','$nomor','0','$splitX[0]','$harga[$x]','$coa[$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','Activity','ADD','$Transaction_Date','$time','web-$user','$hostname')");
        $this->db->query("exec ACC_ActivityJournal '" . $nomor . "' , '" . $user . "', '" . $hostname . "' ");

        $this->session->set_flashdata('message', '<div class="alert alert-success" role="alert"> Data Berhasil DiTambahkan </div>');
        redirect('Transaction/detailheader/'.$CaseID); 
}

function searchTindakan()
{
    date_default_timezone_set("Asia/Jakarta");
    $keyword = $this->input->post('keyword');
    $kategori = $this->input->post('kategori');
    $company = $this->input->post('company');
    $id = $this->input->post('id');

    if($company != '1'){
        $obj = $this->db->query("SELECT M.[ProcedureCode] ,M.[Description] ,M.[Category] ,M.[Active] ,M.[COA] ,mp.Class ,mp.Price
        FROM [tegalan].[dbo].[MedicalProcedure] M LEFT JOIN MedicalProcedurePriceCompany MP ON M.ProcedureCode = mp.ProcedureCode where Active = 'T' And Category = '$kategori' And CompanyCode = '$company' And Description like '%$keyword%' Order by ProcedureCode ")->result_array();
    }else{
        $obj = $this->db->query("SELECT M.[ProcedureCode] ,M.[Description] ,M.[Category] ,M.[Active] ,M.[COA] ,mp.Class ,mp.Price
        FROM [tegalan].[dbo].[MedicalProcedure] M LEFT JOIN MedicalProcedurePrice MP ON M.ProcedureCode = mp.ProcedureCode where Active = 'T' And Category = '$kategori' And Description like '%$keyword%' Order by ProcedureCode ")->result_array();
    }

    $output = '<ul class="list-unstyled ulclass">';
    if (empty($obj)) {
        $output .= "<li class='liclass' onClick=\"setObatCode('empty','$id');\" >Tidak ditemukan</li>";
        $output .= '</ul>';
    } else {
        foreach ($obj as $data) {
            $ProcedureCode = $data['ProcedureCode'];
            $dataLi =  $data['ProcedureCode'] . ' # ' . $data['Description'] . ' # ' . number_format($data['Price'],0) . ' # ' . $data['COA'];
            $output .= "<li class='liclass' onClick=\"setObatCode('$dataLi','$id');\">" . $dataLi . "</li>";
        }
        $output .= '</ul>';
    }

    $response = array(
        "status" => "00",
        "data" => $output
    );
    echo json_encode($response);
    exit();
}

public function detailTransaction($id,$idtrx)
{
    $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();
    $data['dt'] = $this->M_Transaksi->detailTransaction($id)->row_array();
    $data['trans1'] = $this->M_Transaksi->getDetailTrans($id,$idtrx)->result_array();
    $data['detail'] = $this->M_Transaksi->detailtrx($id)->row_array();
    $data['total'] = $this->M_Transaksi->total($id)->row_array();
    $data['dokter'] = $this->M_Transaksi->getdokter()->result_array();
    $data['tindakanedit'] = $this->M_Transaksi->gettreatmentedit($idtrx)->result_array();
    $data['category'] = $this->M_Transaksi->getcategory()->result_array();

    $this->load->view('properti/header', $data);
    $this->load->view('properti/menu', $data);
    $this->load->view('transaction/detail', $data);
    $this->load->view('properti/footer', $data);

}

public function detailheader($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();
    $data['dt'] = $this->M_Transaksi->detailTransaction($id)->row_array();
    $data['detail'] = $this->M_Transaksi->detailtrx($id)->row_array();
    $data['total'] = $this->M_Transaksi->total($id)->row_array();
    $data['dokter'] = $this->M_Transaksi->getdokter()->result_array();
    $data['tindakan'] = $this->M_Transaksi->gettreatment()->result_array();

    $this->load->view('properti/header', $data);
    $this->load->view('properti/menu', $data);
    $this->load->view('transaction/detailTransaction', $data);
    $this->load->view('properti/footer', $data);

}

public function detailheaderdepo($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();
    $data['dt'] = $this->M_Transaksi->detailTransaction($id)->row_array();
    $data['detail'] = $this->M_Transaksi->detailtrxdepo($id)->row_array();
    $data['total'] = $this->M_Transaksi->totaldepo($id)->row_array();
    $data['dokter'] = $this->M_Transaksi->getdokter()->result_array();
    $data['tindakan'] = $this->M_Transaksi->gettreatment()->result_array();

    $this->load->view('properti/header', $data);
    $this->load->view('properti/menu', $data);
    $this->load->view('transaction/detaildepo', $data);
    $this->load->view('properti/footer', $data);

}

public function detailTransactiondepo($id,$idtrx)
{
    $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();
    $data['dt'] = $this->M_Transaksi->detailTransaction($id)->row_array();
    $data['trans1'] = $this->M_Transaksi->getDetailDepo($idtrx)->result_array();
    $data['detail'] = $this->M_Transaksi->detailtrxdepo($id)->row_array();
    $data['total'] = $this->M_Transaksi->totaldepo($id)->row_array();
    $data['dokter'] = $this->M_Transaksi->getdokter()->result_array();
    $data['tindakanedit'] = $this->M_Transaksi->gettreatmentedit($idtrx)->result_array();
    $data['category'] = $this->M_Transaksi->getcategory()->result_array();

    $this->load->view('properti/header', $data);
    $this->load->view('properti/menu', $data);
    $this->load->view('transaction/detailTransactiondepo', $data);
    $this->load->view('properti/footer', $data);

}

}