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

class ControllerKPI extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        //validasi jika user belum login
        check_not_login();
        if ($this->session->userdata('level') != 6) {
            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->model('kabag_marketing/insert_model');
        $this->load->model('kabag_marketing/select_model');
        $this->load->model('kabag_marketing/update_model');
    }
    public function set_timezone()
    {
        date_default_timezone_set("Asia/Jakarta");
    }
    public function index()
    {
        $this->_updateKPIMarketing();
        $this->_notifWADevOpsBerhasil();
        $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil Update KPI!</div>');
        redirect('kabag_marketing/marketing_aktifitas');
    }
    // CRUD Cetak Laporan Storting dan Realisasi
    public function realisasi_stroting()
    {
        if (isset($_POST['harianSemuaMarketingCetak'])) :
            $d = htmlspecialchars($this->input->post('tanggal_transaksi'));
            $m = htmlspecialchars($this->input->post('bulan_transaksi'));
            $y = htmlspecialchars($this->input->post('tahun_transaksi'));
            $tgl = $y . '-' . $m . '-' . $d;
            $this->_cetakSemuaLaporanStortingRealisasiHarian($tgl);
        endif;
        if (isset($_POST['bulananSemuaMarketingCetak'])) :
            $bulan        = htmlspecialchars($this->input->post('bulan_transaksi'));
            $tahun        = htmlspecialchars($this->input->post('tahun_transaksi'));
            $this->_cetakSemuaLaporanStortingRealisasiBulanan($bulan, $tahun);
        endif;
    }
    // Kirim Notifikasi KPI Update
    // Notif WA Berhasil
    private function _notifWADevOpsBerhasil()
    {
        $data_identitas_login      = $this->db->get_where('sistem_login', ['id' => $this->session->userdata('isloggedin')])->row_array();
        $sett_wa = $this->db->get_where('sistem_wa', ['id' => 1])->row_array();
        $no_hp   = $sett_wa['uji_coba'];
        $pesan = '*_Update KPI Marketing :_*

' . date('d-m-Y H:i:s') . '
*_Berhasil di Lakukan_*

' . $data_identitas_login['email'] . '
' . $data_identitas_login['nm_panggilan'];

        $footer = '*KSP Bina Artha Prima*';
        $data_inputan = array(
            'api_key'    => $sett_wa['api_key'],
            'sender'     => $sett_wa['no_hp'],
            'number'     => $no_hp,
            'message'    => $pesan,
            'footer'     => $footer
        );
        $curl = curl_init($sett_wa['endpoint_url']);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data_inputan));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_exec($curl);
        curl_close($curl);
    }
    // Update KPI
    // Marketing 
    private function _updateKPIMarketing()
    {
        // Data Marketing
        $data_marketing = $this->select_model->vd_marketingAktif();
        // Menampilkan data Marketing
        foreach ($data_marketing as $Marketing) :
            $bulan = date('m');
            $tahun = date('Y');
            if ($bulan - 1 == 0) :
                $blnlalu = '12';
                $thnlalu = $tahun - 1;
            else:
                $blncek = $bulan - 1;
                if ($blncek >= 10) :
                    $blnlalu = $blncek;
                else:
                    $blnlalu = '0' . $blncek;
                endif;
                $thnlalu = $tahun;
            endif;
            // Cek Bulan Data yang Lalu
            $data_bulan_lalu = $this->db->get_where('k_hasil', ['login_id' => $Marketing->marketing_id, 'MONTH(bln_kpi)' => $blnlalu, 'YEAR(bln_kpi)' => $thnlalu, 'sts_hasil' => 'PROSES'])->row_array();
            // APakah bulan kemarin nilai sudah selesai atau belum
            if ($data_bulan_lalu != NULL) :
                // Nilai Bulan Kemarin belum selesai
                $hasil_id = $data_bulan_lalu['id'];
                $this->_mulaiUpdateKPI($hasil_id);
                $dblnlalu = array(
                    'sts_hasil'   => 'SELESAI',
                    'updated_at'  => date('Y-m-d H:i:s')
                );
                $this->db->where('id', $hasil_id);
                $this->db->update('k_hasil', $dblnlalu);
            endif;
            // Cek apakah bulan ini sudah ada nilai atau belum
            $data_hasilbulan = $this->db->get_where('k_hasil', ['login_id' => $Marketing->marketing_id, 'MONTH(bln_kpi)' => $bulan, 'YEAR(bln_kpi)' => $tahun])->row_array();
            if ($data_hasilbulan == null) :
                // Jika data nilai masih Null
                $data_hasilbaru = array(
                    'login_id'    => $Marketing->marketing_id,
                    'bln_kpi'     => date('Y-m-d'),
                    'nilai_angka' => 0,
                    'nilai_huruf' => 'D',
                    'sts_hasil'   => 'PROSES'
                );
                $this->db->insert('k_hasil', $data_hasilbaru);
                $data_hasilbulanbaru = $this->db->get_where('k_hasil', ['login_id' => $Marketing->marketing_id, 'MONTH(bln_kpi)' => $bulan, 'YEAR(bln_kpi)' => $tahun])->row_array();
                $hasil_id     = $data_hasilbulanbaru['id'];
                $this->_mulaiUpdateKPI($hasil_id);
            else:
                if ($data_hasilbulan['sts_hasil'] == 'PROSES'):
                    $hasil_id     = $data_hasilbulan['id'];
                    $this->_mulaiUpdateKPI($hasil_id);
                endif;
            endif;
        endforeach;
    }
    // Mulai Update KPI Bulan Ini
    private function _mulaiUpdateKPI($hasil_id)
    {
        $hasil        = $this->db->get_where('k_hasil', ['id' => $hasil_id])->row_array();
        $bulan        = date('m', strtotime($hasil['bln_kpi']));
        $tahun        = date('Y', strtotime($hasil['bln_kpi']));
        // $bulan        = '09';
        // $tahun        = 2024;
        $marketing_id = $hasil['login_id'];
        // Realisasi Bulan ini Individu
        $ttl_realisasi = $this->select_model->vd_totalJmlRealisasi($marketing_id, $bulan, $tahun);
        if ($ttl_realisasi['jml_realisasi'] == null) :
            $jml_realisasi = 0;
        else:
            $jml_realisasi = $ttl_realisasi['jml_realisasi'];
        endif;
        // Realisasi Bulan ini Devisi
        $ttl_realisasi_devisi1 = $this->select_model->vd_totalJmlRealisasiDevisi1($bulan, $tahun);
        $ttl_realisasi_devisi2 = $this->select_model->vd_totalJmlRealisasiDevisi2($bulan, $tahun);
        $ttl_realisasi_devisinew = $ttl_realisasi_devisi1['jml_realisasi'] + $ttl_realisasi_devisi2['jml_realisasi'];
        if ($ttl_realisasi_devisinew == null) :
            $realisasi_devisi = 0;
        else:
            $realisasi_devisi = $ttl_realisasi_devisinew;
        endif;
        // Storting Bulan ini
        $ttl_storting = $this->select_model->vd_totalJmlStorting($marketing_id, $bulan, $tahun);
        if ($ttl_storting['jml_storting'] == null) :
            $jml_storting = 0;
        else:
            $jml_storting = $ttl_storting['jml_storting'];
        endif;
        // Storting Bulan ini Devisi
        $ttl_storting_devisi1 = $this->select_model->vd_totalJmlStortingDevisi1($bulan, $tahun);
        $ttl_storting_devisi2 = $this->select_model->vd_totalJmlStortingDevisi2($bulan, $tahun);
        $ttl_storting_devisi = $ttl_storting_devisi1['jml_storting'] + $ttl_storting_devisi2['jml_storting'];
        if ($ttl_storting_devisi == null) :
            $storting_devisi = 0;
        else:
            $storting_devisi = $ttl_storting_devisi;
        endif;
        // Target Individu bulanan
        // Data Individu Realisasi
        $di_realisasi = $this->db->get_where('k_target', ['login_id' => $marketing_id, 'sts_target' => 'AKTIF', 'faktor_id' => 1])->row_array();
        $data_faktor1 = $this->db->get_where('k_faktor', ['id' => 1])->row_array();
        $nir          = ((($jml_realisasi / $di_realisasi['tgt_kinerja']) * $data_faktor1['pers_faktor']) / 100) * 100;
        if ($nir >= $data_faktor1['pers_faktor']) :
            $nilai_individu_realisasi = $data_faktor1['pers_faktor'];
        else:
            $nilai_individu_realisasi = $nir;
        endif;
        // Data Individu Storting
        $di_storting  = $this->db->get_where('k_target', ['login_id' => $marketing_id, 'sts_target' => 'AKTIF', 'faktor_id' => 2])->row_array();
        $data_faktor2 = $this->db->get_where('k_faktor', ['id' => 2])->row_array();
        $nis          = ((($jml_storting / $di_storting['tgt_kinerja']) * $data_faktor2['pers_faktor']) / 100) * 100;
        if ($nis >= $data_faktor2['pers_faktor']) :
            $nilai_individu_storting = $data_faktor2['pers_faktor'];
        else:
            $nilai_individu_storting = $nis;
        endif;
        // Target Devisi bulanan
        // Data Devisi Realisasi
        $dd_realisasi = $this->db->get_where('k_target', ['login_id' => $marketing_id, 'sts_target' => 'AKTIF', 'faktor_id' => 3])->row_array();
        $data_faktor3 = $this->db->get_where('k_faktor', ['id' => 3])->row_array();
        $ndr          = ((($realisasi_devisi / $dd_realisasi['tgt_kinerja']) * $data_faktor3['pers_faktor']) / 100) * 100;
        if ($ndr >= $data_faktor3['pers_faktor']) :
            $nilai_devisi_realisasi = $data_faktor3['pers_faktor'];
        else:
            $nilai_devisi_realisasi = $ndr;
        endif;
        // Data Devisi Storting
        $dd_storting  = $this->db->get_where('k_target', ['login_id' => $marketing_id, 'sts_target' => 'AKTIF', 'faktor_id' => 5])->row_array();
        $data_faktor4 = $this->db->get_where('k_faktor', ['id' => 5])->row_array();
        $nds          = ((($storting_devisi / $dd_storting['tgt_kinerja']) * $data_faktor4['pers_faktor']) / 100) * 100;
        if ($nds >= $data_faktor4['pers_faktor']) :
            $nilai_devisi_storting = $data_faktor4['pers_faktor'];
        else:
            $nilai_devisi_storting = $nds;
        endif;
        // Target Kedisiplinan
        // Data Disiplin
        $d_disiplin   = $this->db->get_where('k_target', ['login_id' => $marketing_id, 'faktor_id' => 7, 'sts_target' => 'AKTIF'])->row_array();
        $data_faktor5 = $this->db->get_where('k_faktor', ['id' => 7])->row_array();
        $nilai_disiplin = $this->db->get_where('k_disiplin', ['login_id' => $marketing_id, 'MONTH(tgl_laporan)' => $bulan, 'YEAR(tgl_laporan)' => $tahun])->row_array();
        if ($nilai_disiplin == null) :
            $ttl_menit = '0';
        else:
            $ttl_menit = $nilai_disiplin['absensi_menit'];
        endif;
        $nilai_disiplin2 = ((($ttl_menit / $d_disiplin['tgt_kinerja']) * $data_faktor5['pers_faktor']) / 100) * 100;
        if ($nilai_disiplin2 >= $data_faktor5['pers_faktor']) :
            $nilai_disiplin_marketing = $data_faktor5['pers_faktor'];
        else:
            $nilai_disiplin_marketing = $nilai_disiplin2;
        endif;
        // Data Review
        $d_reviews     = $this->db->get_where('k_target', ['login_id' => $marketing_id, 'faktor_id' => 8, 'sts_target' => 'AKTIF'])->row_array();
        $data_faktor6  = $this->db->get_where('k_faktor', ['id' => 8])->row_array();
        $jml_reviews   = count($this->db->get_where('k_rkonsumen', ['login_id' => $marketing_id, 'MONTH(tgl_review)' => $bulan, 'YEAR(tgl_review)' => $tahun])->result());
        $ttl_bintang   = $this->select_model->vd_bintangReviewsPelanggan($marketing_id, $bulan, $tahun);
        if ($jml_reviews == null) :
            $reviews_nilai = 0;
            $nilai_reviews = 0;
        else:
            $reviews_nilai = $ttl_bintang['rate_bintang'] / $jml_reviews;
            $nilai_reviews = (((($ttl_bintang['rate_bintang'] / $jml_reviews) / $d_reviews['tgt_kinerja']) * $data_faktor6['pers_faktor']) / 100) * 100;
        endif;
        if ($nilai_reviews >= $data_faktor6['pers_faktor']) :
            $nilai_reviews_marketing = $data_faktor6['pers_faktor'];
        else:
            $nilai_reviews_marketing = $nilai_reviews;
        endif;
        // echo '<pre>';
        // var_dump($nilai_reviews);
        // die;
        $nilai_angka = round((($nilai_individu_realisasi + $nilai_individu_storting) + ($nilai_devisi_realisasi + $nilai_devisi_storting) + ($nilai_disiplin_marketing + $nilai_reviews_marketing)), 2);
        if ($nilai_angka > 95) :
            $nilai_huruf = 'S+';
        elseif ($nilai_angka >= 91):
            $nilai_huruf = 'S';
        elseif ($nilai_angka >= 86):
            $nilai_huruf = 'A+';
        elseif ($nilai_angka >= 81):
            $nilai_huruf = 'A';
        elseif ($nilai_angka >= 76):
            $nilai_huruf = 'B+';
        elseif ($nilai_angka >= 71):
            $nilai_huruf = 'B';
        elseif ($nilai_angka >= 61):
            $nilai_huruf = 'C';
        elseif ($nilai_angka >= 51):
            $nilai_huruf = 'D';
        elseif ($nilai_angka <= 50):
            $nilai_huruf = 'E';
        endif;
        $bulan_now = date('m');
        if ($bulan == $bulan_now) :
            $sts_hasil = 'PROSES';
        else:
            $sts_hasil = 'SELESAI';
        endif;
        $data_hasil = array(
            'nilai_angka' => $nilai_angka,
            'nilai_huruf' => $nilai_huruf,
            'sts_hasil'   => $sts_hasil,
            'updated_at'  => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $hasil['id']);
        $this->db->update('k_hasil', $data_hasil);
        $this->db->where('hasil_id', $hasil['id']);
        $this->db->delete('k_dhasil');
        // Detail Nilai Realisasi Individu
        $data_dhasil_1 = array(
            'hasil_id'    => $hasil['id'],
            'faktor_id'   => 1,
            'target'      => $di_realisasi['tgt_kinerja'],
            'realisasi'   => $jml_realisasi,
            'persentase'  => $data_faktor1['pers_faktor'],
            'nilai'       => $nilai_individu_realisasi
        );
        $this->db->insert('k_dhasil', $data_dhasil_1);
        // Detail Nilai Storting Individu
        $data_dhasil_2 = array(
            'hasil_id'    => $hasil['id'],
            'faktor_id'   => 2,
            'target'      => $di_storting['tgt_kinerja'],
            'realisasi'   => $jml_storting,
            'persentase'  => $data_faktor2['pers_faktor'],
            'nilai'       => $nilai_individu_storting
        );
        $this->db->insert('k_dhasil', $data_dhasil_2);
        // Detail Nilai Realisasi Devisi
        $data_dhasil_3 = array(
            'hasil_id'    => $hasil['id'],
            'faktor_id'   => 3,
            'target'      => $dd_realisasi['tgt_kinerja'],
            'realisasi'   => $realisasi_devisi,
            'persentase'  => $data_faktor3['pers_faktor'],
            'nilai'       => $nilai_devisi_realisasi
        );
        $this->db->insert('k_dhasil', $data_dhasil_3);
        // Detail Nilai Storting Devisi
        $data_dhasil_4 = array(
            'hasil_id'    => $hasil['id'],
            'faktor_id'   => 5,
            'target'      => $dd_storting['tgt_kinerja'],
            'realisasi'   => $storting_devisi,
            'persentase'  => $data_faktor4['pers_faktor'],
            'nilai'       => $nilai_devisi_storting
        );
        $this->db->insert('k_dhasil', $data_dhasil_4);
        // Detail Nilai Kedisiplinan
        $data_dhasil_5 = array(
            'hasil_id'    => $hasil['id'],
            'faktor_id'   => 7,
            'target'      => $d_disiplin['tgt_kinerja'],
            'realisasi'   => $ttl_menit,
            'persentase'  => $data_faktor5['pers_faktor'],
            'nilai'       => $nilai_disiplin_marketing
        );
        $this->db->insert('k_dhasil', $data_dhasil_5);
        // Detail Nilai Review Konsumen
        $data_dhasil_6 = array(
            'hasil_id'    => $hasil['id'],
            'faktor_id'   => 8,
            'target'      => $d_reviews['tgt_kinerja'],
            'realisasi'   => $reviews_nilai,
            'persentase'  => $data_faktor6['pers_faktor'],
            'nilai'       => $nilai_reviews_marketing
        );
        $this->db->insert('k_dhasil', $data_dhasil_6);
    }
    // Private Function Cetak Laporan Storting dan Realisasi
    private function _cetakSemuaLaporanStortingRealisasiHarian($tgl)
    {
        $opt                       = $this->db->get_where('sistem_option')->row_array();
        $data_marketing            = $this->select_model->vd_marketingAktf();
        $data_realisasi            = $this->select_model->vd_realisasiSemua($tgl);
        $data_target_storting      = $this->select_model->vd_targetStortingSemua($tgl);
        $data_storting             = $this->select_model->vd_stortingSemua($tgl);
        // View Data Total
        // View Data Realisasi
        $jml_realisasi             = $this->select_model->jml_realisasisemua($tgl);
        $jml_target_storting       = $this->select_model->jml_targetStortingSemua($tgl);
        $jml_storting              = $this->select_model->jml_stortingSemua($tgl);
        // echo '<pre>';
        // var_dump($jml_realisasi);
        // die;
        $data = array(
            // Untuk memanggil halaman sesuai menu
            'title_pdf'           => 'Laporan Storting & Realisasi Pinjaman ' . date('d', strtotime($tgl)) . ' ' . $this->mycustom->bulanIndo(date('m', strtotime($tgl))) . ' ' .  date('Y', strtotime($tgl)),
            // Identitas Marketing
            'option'              => $opt,
            'tanggal'             => $tgl,
            // Data Marketing
            'marketing'           => $data_marketing,
            'realisasi'           => $data_realisasi,
            'target_storting'     => $data_target_storting,
            'storting'            => $data_storting,
            // Data Total Jumlah
            'jml_realisasi'       => $jml_realisasi,
            'jml_target_storting' => $jml_target_storting,
            'jml_storting'        => $jml_storting
        );
        // filename dari pdf ketika didownload
        $this->load->view('document/laporan/koperasi_pinjaman/semua_cetak_storting_realisasi_harian', $data);
    }
    private function _cetakSemuaLaporanStortingRealisasiBulanan($bulan, $tahun)
    {
        $opt                       = $this->db->get_where('sistem_option')->row_array();
        $data_marketing            = $this->select_model->vd_marketingAktf();
        $data_realisasi            = $this->select_model->vd_realisasiSemuaBulanan($bulan, $tahun);
        $data_target_storting      = $this->select_model->vd_targetStortingSemuaBulanan($bulan, $tahun);
        $data_storting             = $this->select_model->vd_stortingSemuaBulanan($bulan, $tahun);
        // View Data Total
        // View Data Realisasi
        $jml_realisasi             = $this->select_model->jml_realisasisemuaBulanan($bulan, $tahun);
        $jml_target_storting       = $this->select_model->jml_targetStortingSemuaBulanan($bulan, $tahun);
        $jml_storting              = $this->select_model->jml_stortingSemuaBulanan($bulan, $tahun);
        // echo '<pre>';
        // var_dump($jml_realisasi);
        // die;
        $data = array(
            // Untuk memanggil halaman sesuai menu
            'title_pdf'           => 'Laporan Storting & Realisasi Pinjaman ' . $this->mycustom->bulanIndo(date('m', $bulan)) . ' ' .  $tahun,
            // Identitas Marketing
            'option'              => $opt,
            'bulan'               => $bulan,
            'tahun'               => $tahun,
            // Data Marketing
            'marketing'           => $data_marketing,
            'realisasi'           => $data_realisasi,
            'target_storting'     => $data_target_storting,
            'storting'            => $data_storting,
            // Data Total Jumlah
            'jml_realisasi'       => $jml_realisasi,
            'jml_target_storting' => $jml_target_storting,
            'jml_storting'        => $jml_storting
        );
        // filename dari pdf ketika didownload
        $this->load->view('document/laporan/koperasi_pinjaman/semua_cetak_storting_realisasi_bulanan', $data);
    }
}

/* End of file ControllerKPI.php and path \application\controllers\kabag_marketing\ControllerKPI.php */