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

class ControllerSalery extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        //validasi jika user belum login
        check_not_login();
        if ($this->session->userdata('level') != 3) {
            redirect();
        }
        $this->set_timezone();
        $this->load->library('encrypt');
        $this->load->library('form_validation');
        $this->load->library('Mycustom');
        $this->load->library('pdfgenerator');
        $this->load->library('Notifikasi');
        $this->load->library('Phpmailer_library');
        $this->load->model('bagian_keuangan/insert_model');
        $this->load->model('bagian_keuangan/select_model');
        $this->load->model('bagian_keuangan/update_model');
    }
    public function set_timezone()
    {
        date_default_timezone_set("Asia/Jakarta");
    }

    public function index()
    {
        if (isset($_POST['filterTransaksiKasTanggal'])) :
            $bulan                 = htmlspecialchars($this->input->post('bulan_transaksi'));
            $tahun                 = htmlspecialchars($this->input->post('tahun_transaksi'));
        else:
            $a = date('m');
            $b = date('Y');
            if (($a - 1) == 0) :
                $bulan    = 12;
                $tahun    = $b - 1;
            else:
                $bulan                 = (date('m') - 1);
                $tahun                 = date('Y');
            endif;
        endif;
        $notif = $this->notifikasi->notif_keuangan();
        // Data Login
        $data_login            = $this->userlogin->user_login(); // Menampilkan siapa yang login
        $data_id_login         = $this->session->userdata('isloggedin'); // Menampilkan data session
        // Data Isian Konten
        // Query SQL Data atau isi data page 
        // Menampilkan histori gaji karyawan
        $data_gaji             = $this->select_model->vdataGajiKaraywan($bulan, $tahun);
        $data_karyawan         = $this->select_model->vd_KaryawanAktifKerja();
        $tampil_tahun          = $this->select_model->getDataTahunTransaksi();
        $total_gaji            = $this->select_model->vd_totalGajiPeriode($bulan, $tahun);
        $data = array(
            // Untuk memanggil halaman sesuai menu
            'folder'              => 'kas/gaji',
            'page'                => 'index',
            'judul'               => 'Histori Gaji Karyawan || Bagian Keuangan',
            'data_id_login'       => $data_id_login,
            'data_login'          => $data_login,
            'notif'               => $notif,
            'bulan'               => $bulan,
            'tahun'               => $tahun,
            'tampil_tahun'        => $tampil_tahun,
            'total_gaji'          => $total_gaji,
            // Isi data
            'data_gaji'           => $data_gaji,
            'data_karyawan'       => $data_karyawan
        );
        $this->load->view('keuangan/index', $data);
    }
    // Detail Salery Karyawan
    // Gaji Detail
    public function gaji_detail($id)
    {
        $notif = $this->notifikasi->notif_keuangan();
        // Data Login
        $data_login                   = $this->userlogin->user_login();
        $data_id_login                = $this->session->userdata('isloggedin');
        // Query SQL Data atau isi data page
        // Data gaji
        $gaji_id                      = $this->encrypt->decode($id);
        $data_gaji                    = $this->db->get_where('k_gaji', ['id' => $gaji_id])->row_array();
        $detail_gaji                  = $this->db->get_where('k_dgaji', ['gaji_id' => $gaji_id])->result();
        $identitas_karyawan           = $this->db->get_where('sistem_login', ['id' => $data_gaji['login_id']])->row_array();
        $detail_identitas             = $this->db->get_where('sistem_identitas', ['login_id' => $data_gaji['login_id']])->row_array();
        // echo '<pre>';
        // var_dump($identitas_karyawan, $gaji_id);
        // die;
        $data = array(
            // Untuk memanggil halaman sesuai menu
            'folder'              => 'kas/gaji_detail/',
            'page'                => 'index',
            'judul'               => 'Detail Gaji Karyawan || Bagian Keuangan',
            'notif'               => $notif,
            // Isi data
            'data_id_login'       => $data_id_login,
            'data_login'          => $data_login,
            // Data isian konten
            'identitas'           => $identitas_karyawan,
            'gaji'                => $data_gaji,
            'detail_gaji'         => $detail_gaji,
            'detail_identitas'    => $detail_identitas
        );
        $this->load->view('keuangan/index', $data);
    }
    // Transaksi Salery
    public function crud()
    {
        // Tambah Gaji
        if (isset($_POST['simpanTransaksiBaru'])) {
            // Cek gaji pokok
            $gaji_pokok = $this->_cekGajiPokokKaryawan();
            $bulan = date('m');
            $tahun = date('Y');
            // Cek apakah bulan dan tahun lebih besar dari pada hari ini
            if (htmlspecialchars($this->input->post('bulan_transaksi')) >= $bulan) :
                if (htmlspecialchars($this->input->post('tahun_transaksi')) >= $tahun) :
                    $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Bulan dan Tahun Tidak Boleh Lebih Besar atau sama Dari Bulan dan tahun Sekarang!</div>');
                    redirect('keuangan/salery');
                endif;
            endif;
            // Cek apakah bulan ini sudah gajian
            $cek_gaji = $this->db->get_where('k_gaji', ['login_id' => htmlspecialchars($this->input->post('login_id')), 'MONTH(tgl_gaji)' => htmlspecialchars($this->input->post('bulan_transaksi')), 'YEAR(tgl_gaji)' => htmlspecialchars($this->input->post('tahun_transaksi'))])->row_array();
            if ($cek_gaji != NULL) :
                $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Masukkan Rincian Gaji!</div>');
                redirect('keuangan/identitas/detail_gaji/' . $this->encrypt->encode($cek_gaji['id']));
            endif;
            $cek_disiplin = $this->db->get_where('k_disiplin', ['login_id' => htmlspecialchars($this->input->post('login_id')), 'MONTH(tgl_laporan)' => htmlspecialchars($this->input->post('bulan_transaksi')), 'YEAR(tgl_laporan)' => htmlspecialchars($this->input->post('tahun_transaksi'))])->row_array();
            if ($cek_disiplin != NULL) :
                $disiplin_id = $cek_disiplin['id'];
            else:
                $tgl_laporan   = htmlspecialchars($this->input->post('tahun_transaksi')) . '-' . htmlspecialchars($this->input->post('bulan_transaksi')) . '-01';
                $data_disiplin = array(
                    'login_id'      => htmlspecialchars($this->input->post('login_id')),
                    'tgl_laporan'   => $tgl_laporan,
                    'absensi_menit' => htmlspecialchars($this->input->post('total_kerja'))
                );
                $this->db->insert('k_disiplin', $data_disiplin);
                $cek_disiplin2 = $this->db->get_where('k_disiplin', ['login_id' => htmlspecialchars($this->input->post('login_id')), 'MONTH(tgl_laporan)' => htmlspecialchars($this->input->post('bulan_transaksi')), 'YEAR(tgl_laporan)' => htmlspecialchars($this->input->post('tahun_transaksi'))])->row_array();
                $disiplin_id   = $cek_disiplin2['id'];
            endif;
            $tgl_gaji   = htmlspecialchars($this->input->post('tahun_transaksi')) . '-' . htmlspecialchars($this->input->post('bulan_transaksi')) . '-01';
            $data_gaji = array(
                'login_id'    => htmlspecialchars($this->input->post('login_id')),
                'disiplin_id' => $disiplin_id,
                'tgl_gaji'    => $tgl_gaji,
                'gaji_pokok'  => $gaji_pokok,
                'metode'      => htmlspecialchars($this->input->post('metode_bayar')),
                'sts_gaji'    => 'PROSES'
            );
            $this->db->insert('k_gaji', $data_gaji);
            $cek_gaji2 = $this->db->get_where('k_gaji', ['login_id' => htmlspecialchars($this->input->post('login_id')), 'MONTH(tgl_gaji)' => htmlspecialchars($this->input->post('bulan_transaksi')), 'YEAR(tgl_gaji)' => htmlspecialchars($this->input->post('tahun_transaksi'))])->row_array();
            $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Masukkan Rincian Gaji!</div>');
            redirect('keuangan/identitas/detail_gaji/' . $this->encrypt->encode($cek_gaji2['id']));
        };
    }
    public function crud_gaji()
    {
        // Tambah Gaji Baru Bulan Ini
        if (isset($_POST['tambahGajiBaru'])) {
            $bulan = date('m', strtotime(date('Y-m-d')));
            $tahun = date('Y', strtotime(date('Y-m-d')));
            $login_id   = htmlspecialchars($this->input->post('login_id'));
            $data_gaji = $this->db->get_where('k_gaji', ['MONTH(tgl_gaji)' => $bulan, 'YEAR(tgl_gaji)' => $tahun, 'login_id' => $login_id])->row_array();
            if (htmlspecialchars($this->input->post('gaji_pokok')) == 1) :
                $gaji_pokok = htmlspecialchars($this->input->post('gaji_lama'));
            else:
                $gaji_pokok = htmlspecialchars($this->input->post('gaji_pokok_baru'));
            endif;
            $data_disiplin = $this->db->get_where('k_disiplin', ['MONTH(tgl_laporan)' => $bulan, 'YEAR(tgl_laporan)' => $tahun, 'login_id' => $login_id])->row_array();
            if ($data_disiplin == null) :
                $inputan_disiplin = array(
                    'login_id'      => $login_id,
                    'tgl_laporan'   => date('Y-m-d'),
                    'absensi_menit' => htmlspecialchars($this->input->post('total_kerja'))
                );
                $this->db->insert('k_disiplin', $inputan_disiplin);
                $disiplin  = $this->db->get_where('k_disiplin', ['MONTH(tgl_laporan)' => $bulan, 'YEAR(tgl_laporan)' => $tahun, 'login_id' => $login_id])->row_array();
            else:
                $update_disiplin = array(
                    'absensi_menit' => htmlspecialchars($this->input->post('total_kerja')),
                    'updated_at'    => date('Y-m-d H:i:s')
                );
                $this->db->where('id', $data_disiplin['id']);
                $this->db->update('k_disiplin', $update_disiplin);
                $disiplin  = $this->db->get_where('k_disiplin', ['MONTH(tgl_laporan)' => $bulan, 'YEAR(tgl_laporan)' => $tahun, 'login_id' => $login_id])->row_array();
            endif;
            if ($data_gaji == null) :
                // Cek Disiplin ID
                $inputan_gaji_baru = array(
                    'login_id'      => $login_id,
                    'disiplin_id'   => $disiplin['id'],
                    'tgl_gaji'      => date('Y-m-d'),
                    'gaji_pokok'    => $gaji_pokok,
                    'ttl_bonus'     => 0,
                    'ttl_potongan'  => 0,
                    'ttl_gaji'      => 0,
                    'metode'        => htmlspecialchars($this->input->post('metode_bayar')),
                    'sts_gaji'      => 'PROSES'
                );
                $this->db->insert('k_gaji', $inputan_gaji_baru);
                $data_gaji_baru = $this->db->get_where('k_gaji', ['MONTH(tgl_gaji)' => $bulan, 'YEAR(tgl_gaji)' => $tahun, 'login_id' => $login_id])->row_array();
                $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil, Silahkan Masukkan Data Gaji!</div>');
                redirect('keuangan/identitas/detail_gaji/' . $this->encrypt->encode($data_gaji_baru['id']));
            else:
                $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Gaji Bulan Ini Sudah Ada, Silahkan Masuk Ke Detail Gaji!</div>');
                redirect('keuangan/identitas/detail_gaji/' . $this->encrypt->encode($data_gaji['id']));
            endif;
        };
        // Update data gaji pokok Karyawan
        if (isset($_POST['updateGajiPokok'])) {
            $login_id   = htmlspecialchars($this->input->post('login_id'));
            $gaji_pokok = htmlspecialchars($this->input->post('gaji_pokok'));
            $gaji_id    = htmlspecialchars($this->input->post('gaji_id'));
            $data_gaji = array(
                'sb' => $gaji_pokok
            );
            $this->db->where('login_id', $login_id);
            $this->db->update('sistem_identitas', $data_gaji);
            $inputan_gaji    = array(
                'gaji_pokok' => $gaji_pokok
            );
            $this->db->where('id', $gaji_id);
            $this->db->update('k_gaji', $inputan_gaji);
            $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil merubah data gaji pokok!</div>');
            redirect('keuangan/identitas/detail_gaji/' . $this->encrypt->encode($gaji_id));
        };
        // Tambah Detail Gaji Karyawan
        if (isset($_POST['simpanKetGaji'])) {
            // Data Inputan
            $data_inputan = array(
                'gaji_id'  => htmlspecialchars($this->input->post('gaji_id')),
                'ket_gaji' => htmlspecialchars($this->input->post('ket_gaji')),
                'nominal'  => htmlspecialchars($this->input->post('nominal_transaksi')),
                'status'   => htmlspecialchars($this->input->post('jenis_gaji'))
            );
            $this->db->insert('k_dgaji', $data_inputan);
            $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil merubah data gaji pokok!</div>');
            redirect('keuangan/identitas/detail_gaji/' . $this->encrypt->encode($data_inputan['gaji_id']));
        };
        // Ubah data detail gaji Karyawan
        if (isset($_POST['updateDetailGaji'])) {
            // Data Inputan
            $gaji_id  = htmlspecialchars($this->input->post('gaji_id'));
            $data_inputan = array(
                'ket_gaji' => htmlspecialchars($this->input->post('ket_gaji')),
                'nominal'  => htmlspecialchars($this->input->post('nominal_transaksi')),
                'status'   => htmlspecialchars($this->input->post('jenis_gaji'))
            );
            $this->db->where('id', htmlspecialchars($this->input->post('detail_id')));
            $this->db->update('k_dgaji', $data_inputan);
            $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil merubah data gaji pokok!</div>');
            redirect('keuangan/identitas/detail_gaji/' . $this->encrypt->encode($gaji_id));
        };
        // Hapus data detail gaji Karyawan
        if (isset($_POST['deleteDetailGaji'])) {
            // Data Inputan
            $gaji_id  = htmlspecialchars($this->input->post('gaji_id'));
            $this->db->where('id', htmlspecialchars($this->input->post('detail_id')));
            $this->db->delete('k_dgaji');
            $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil merubah data gaji pokok!</div>');
            redirect('keuangan/identitas/detail_gaji/' . $this->encrypt->encode($gaji_id));
        };
        // Gaji Selesai Proses
        if (isset($_POST['gajiSelesai'])) {
            // Data Inputan
            $gaji_id         = htmlspecialchars($this->input->post('gaji_id'));
            $data_gaji_lama  = $this->db->get_where('k_gaji', ['id' => $gaji_id])->row_array();
            $identitas  = $this->db->get_where('sistem_identitas', ['login_id' => $data_gaji_lama['login_id']])->row_array();
            $login      = $this->db->get_where('sistem_login', ['id' => $data_gaji_lama['login_id']])->row_array();
            $role_level = $this->db->get_where('sistem_role_level', ['id' => $login['role_id']])->row_array();
            if ($identitas['sb'] <= '1000000') :
                $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Gaji Pokok Belum Di Setting!</div>');
                redirect('keuangan/identitas/detail_gaji/' . $this->encrypt->encode($gaji_id));
            endif;
            $gaji_bonus     = $this->select_model->vd_bonusGajiKaryawan($gaji_id);
            $gaji_potongan  = $this->select_model->vd_potonganGajiKaryawan($gaji_id);
            $data_selesai = array(
                'gaji_pokok'    => $identitas['sb'],
                'ttl_bonus'     => $gaji_bonus['bonus'],
                'ttl_potongan'  => $gaji_potongan['potongan'],
                'ttl_gaji'      => ($identitas['sb'] + $gaji_bonus['bonus']) - $gaji_potongan['potongan'],
                'sts_gaji'      => 'SELESAI',
                'updated_at'    => date('Y-m-d H:i:s')
            );
            $this->db->where('id', $gaji_id);
            $this->db->update('k_gaji', $data_selesai);
            $data_gaji  = $this->db->get_where('k_gaji', ['id' => $gaji_id])->row_array();
            $cetak_slip = $this->_slipGajiKaryawan($gaji_id, $login, $identitas, $role_level, $data_gaji, $data_selesai);
            $this->_kirimSlipEmail($gaji_id, $login, $cetak_slip);
            $this->insert_model->simpanDataTransaksiOperasionalGaji($data_selesai, $identitas, $data_gaji);
            $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil merubah data gaji pokok!</div>');
            redirect('keuangan/identitas/detail_gaji/' . $this->encrypt->encode($gaji_id));
        };
    }
    // Cek Gaji Pokok Karyawan
    private function _cekGajiPokokKaryawan()
    {
        if (htmlspecialchars($this->input->post('gaji_pokok')) == 1) :
            $cek_gaji_lama = $this->db->get_where('sistem_identitas', ['login_id' => htmlspecialchars($this->input->post('login_id'))])->row_array();
            if ($cek_gaji_lama['sb'] < 1000000) :
                $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Gaji Tidak Boleh Kurang Dari 1.000.000!</div>');
                redirect('keuangan/salery');
            else:
                $gaji_pokok = $cek_gaji_lama['sb'];
            endif;
        else:
            if ($this->input->post('gaji_pokok_baru') < 1000000) :
                $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Gaji Tidak Boleh Kurang Dari 1.000.000!</div>');
                redirect('keuangan/salery');
            else:
                $data_gaji = array(
                    'sb' => htmlspecialchars($this->input->post('gaji_pokok_baru'))
                );
                $this->db->where('login_id', htmlspecialchars($this->input->post('login_id')));
                $this->db->update('sistem_identitas', $data_gaji);
                $cek_gaji_sekarang = $this->db->get_where('sistem_identitas', ['login_id' => htmlspecialchars($this->input->post('login_id'))])->row_array();
                $gaji_pokok = $cek_gaji_sekarang['sb'];
            endif;
        endif;
        return $gaji_pokok;
    }
    private function _slipGajiKaryawan($gaji_id, $login, $identitas, $role_level, $data_gaji, $data_selesai)
    {
        $data_bonus     = $this->db->get_where('k_dgaji', ['gaji_id' => $gaji_id, 'status' => 'TAMBAH'])->result();
        $data_potongan  = $this->db->get_where('k_dgaji', ['gaji_id' => $gaji_id, 'status' => 'POTONG'])->result();
        $data_netral    = $this->db->get_where('k_dgaji', ['gaji_id' => $gaji_id, 'status' => 'NETRAL'])->result();
        // End data nota
        $data = array(
            // Data Identitas Karyawan
            'login'      => $login,
            'identitas'  => $identitas,
            'role_level' => $role_level,
            'data_gaji'  => $data_gaji,
            // Data isi konten
            'bonus'    => $data_bonus,
            'potongan' => $data_potongan,
            'netral'   => $data_netral,
            'selesai'  => $data_selesai
        );
        // filename dari pdf ketika didownload
        $file_pdf = date('Y', strtotime($data_gaji['tgl_gaji'])) . date('m', strtotime($data_gaji['tgl_gaji'])) . $data_gaji['login_id'] . '.pdf';
        // setting paper
        $paper = 'A4';
        //orientasi paper potrait / landscape
        $orientation = "potrait";
        // $this->load->view('nota/nota_bayar_arisan_petugas', $data);
        $lokasi_file = 'assets/slip_gaji/';
        $html = $this->load->view('document/nota/slip_gaji', $data, true);
        $passpdf = date('Y', strtotime($identitas['tgl_lahir'])) . date('m', strtotime($identitas['tgl_lahir'])) . date('d', strtotime($identitas['tgl_lahir']));
        $this->pdfgenerator->generate_gaji($html, $file_pdf, $paper, $lokasi_file, $orientation, $passpdf);
        $data_dokumen = array(
            'lokasi'    => $lokasi_file,
            'nama_file' => $file_pdf,
            'password'  => $passpdf
        );
        return $data_dokumen;
    }
    // Coba Kirim Email
    private function _kirimSlipEmail($gaji_id, $login, $cetak_slip)
    {
        // Data Gaji
        $data_gaji = $this->db->get_where('k_gaji', ['id' => $gaji_id])->row_array();
        // Periode Gaji
        $bulan     = $this->mycustom->bulanIndo(date('m', strtotime($data_gaji['tgl_gaji'])));
        $tahun     = date('Y', strtotime($data_gaji['tgl_gaji']));
        $periode   = $bulan . ' ' . $tahun;
        // PHPMailer object
        $mail = $this->phpmailer_library->load();
        $sett_mail = $this->db->get_where('sistem_mail', ['id' => 1])->row_array();
        // SMTP configuration
        $mail->isSMTP();
        $mail->Host     = $sett_mail['host_mail'];
        $mail->SMTPAuth = true;
        $mail->Username = $sett_mail['user_mail'];
        $mail->Password = $this->encrypt->decode($sett_mail['pass_mail']);
        $mail->SMTPSecure = 'ssl';
        $mail->Port     = 465;

        $mail->setFrom($sett_mail['user_mail'], $sett_mail['ket_mail']);
        $mail->addReplyTo('dev.binaartha@gmail.com', 'Slip Gaji Karyawan');

        // Add a recipient
        $mail->addAddress('ajiw100@gmail.com');
        // Email subject
        $mail->Subject = 'Slip Gaji Karyawan';
        // Set email format to HTML
        $mail->isHTML(true);
        // Email body content
        $mailContent = 'Yth, Bpk/Ibu ' . $login['nm_panggilan'] . ', bersama email ini, kami sampaikan Slip Gaji Karyawan periode ' . $periode . '. <br><br> Silahkan untuk membuka Slip Gaji dengan password Anda.<br><br>
            Password Anda adalah 8 digit tanggal lahir anda dalam format YYYYMMDD, dimana : <br>
                <p>- YYYY : Tahun Kelahiran Anda</p>
                <p>- MM : Bulan Kelahiran Anda</p>
                <p>- DD : Tanggal Kelahiran Anda</p><br>
                Contoh : Tanggal lahir <b>01 Febuari 1980</b>, Maka password : <b>19800201</b><br><br><br>
                Terimakasih,<br><br><br>
                Hormat Kami,<br>
                KSP Bina Artha Prima';
        $mail->Body = $mailContent;
        $url = 'https://siap.kspbinaartha.com/assets/slip_gaji/' . $cetak_slip['nama_file'];
        $mail->addStringAttachment(
            file_get_contents($url),
            'slip_gaji_' . $cetak_slip['nama_file']
        );
    }
}

/* End of file ControllerSalery.php and path \application\controllers\keuangan\kas\ControllerSalery.php */