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

class ControllerBeranda extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        check_not_login();
        if ($this->session->userdata('level') != 7) {
            redirect();
        }
        $this->load->library('encrypt');
        $this->load->library('form_validation');
        $this->load->library('mycustom');
        $this->load->model('marketing/insert_model');
        $this->load->model('marketing/select_model');
        $this->load->model('marketing/update_model');
        $this->set_timezone();
    }
    public function set_timezone()
    {
        date_default_timezone_set("Asia/Jakarta");
    }
    public function index()
    {
        // Data Login
        $data_login                   = $this->userlogin->user_login();
        $data_id_login                = $this->session->userdata('isloggedin');
        $data_kotkab                  = $this->select_model->vd_kotkab();
        // Data Isian Konten
        $jenis_pinjaman               = $this->select_model->vd_jenisPinjamanAktif();
        // Data Jenis Pinjaman
        $data_tagihan                 = $this->select_model->vd_tagihanHariIni();
        $data_transaksi               = $this->select_model->vd_transaksiBulanan();
        $target_tagihan_harian        = $this->select_model->vd_jmlTagihanHariIni();
        $masuk_tagihan_harian         = $this->select_model->vd_jmlNotaHariIni();
        $target_tagihan_bulanan       = $this->select_model->vd_jmlTagihanBulanan();
        $masuk_tagihan_bulanan        = $this->select_model->vd_jmlNotaBulanan();
        $tagihan_bulanan = 0;
        foreach ($masuk_tagihan_bulanan as $Masuk_tagihan_bulanan) :
            $tagihan_bulanan += $Masuk_tagihan_bulanan->ttl_bayar;
        endforeach;
        // Data KPI
        $bulan = date('m');
        $tahun = date('Y');
        $data_kpi = $this->db->get_where('k_hasil', ['login_id' => $data_id_login, 'MONTH(bln_kpi)' => $bulan, 'YEAR(bln_kpi)' => $tahun,])->row_array();
        // echo '<pre>';
        // var_dump($data_id_login);
        // die;
        $data = array(
            // Untuk memanggil halaman sesuai menu
            'folder'              => 'beranda',
            'page'                => 'index',
            'judul'               => 'Beranda Bagian Marketing || Bagian Marketing',
            'data_id_login'       => $data_id_login,
            'data_login'          => $data_login,
            'data_kota'           => $data_kotkab,
            'jenis_pinjaman'      => $jenis_pinjaman,
            // Isi dalam konten
            'data_pinjaman'       => $data_tagihan,
            'data_transaksi'      => $data_transaksi,
            'target_harian'       => $target_tagihan_harian,
            'masuk_harian'        => $masuk_tagihan_harian,
            'target_bulanan'      => $target_tagihan_bulanan,
            'masuk_bulanan'       => $tagihan_bulanan,
            'data_kpi'            => $data_kpi
        );
        $this->load->view('marketing/index', $data);
    }
    public function crud()
    {
        if (isset($_POST['simpanPengajuanPinjaman'])) {
            $data_inputan       = $this->_dataInputanAnggotaKoperasi();
            $anggota_id         = $this->_cekAnggotaPinjamanAktif($data_inputan);
            $detail_kontrak     = $this->_dataIdentitasPinjaman($data_inputan, $anggota_id);
            $this->insert_model->tambahPengajuanPinjaman($detail_kontrak);
            $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil Mengajukan Pinjaman!</div>');
            redirect('marketing/kegiatan/pengajuan_pinjaman');
        }
    }
    // Private Funtion
    private function _dataInputanAnggotaKoperasi()
    {
        // Cek Alamat
        $cek_alamat = $this->db->get_where('sistem_alamat', [
            'nm_desa' => htmlspecialchars($this->input->post('tambah_dk_ds')),
            'nm_kecamatan' => htmlspecialchars($this->input->post('tambah_kecamatan_baru')),
            'kot_kab' => htmlspecialchars($this->input->post('tambah_kota_kabupaten'))
        ])->row_array();
        if ($cek_alamat > 0) :
            $alamat_id = $cek_alamat['id'];
        else :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Alamat Tidak Tersedia, Hubungi Developer!</div>');
            redirect('marketing');
        endif;
        // Cek Jenis Kelamin
        if (htmlspecialchars($this->input->post('jk')) == 'ok') :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-success" id="pesan_gagal" role="alert">Silahkan Pilih Jenis Kelamin!</div>');
            redirect('marketing');
        endif;
        // Cek Kabupaten
        if (htmlspecialchars($this->input->post('tambah_kota_kabupaten')) == 'PILIH') :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-success" id="pesan_gagal" role="alert">Silahkan Pilih Kota / Kabupaten yang benar!</div>');
            redirect('marketing');
        endif;
        // Cek Status Hubungan
        if (htmlspecialchars($this->input->post('status_hubungan')) == 0) :
            $suami_istri = 'BELUM MENIKAH';
        elseif (htmlspecialchars($this->input->post('status_hubungan')) == 1) :
            $suami_istri = htmlspecialchars($this->input->post('tambah_suami_istri'));
        elseif (htmlspecialchars($this->input->post('status_hubungan')) == 2) :
            $suami_istri = 'DUDA/JANDA';
        endif;
        $data_inputan = array(
            'nik'            => htmlspecialchars($this->input->post('tambah_nik_anggota')),
            'login_id'       => htmlspecialchars($this->input->post('login_id')),
            'nomor_kk'       => htmlspecialchars($this->input->post('tambah_nomor_kk')),
            'nm_anggota'     => htmlspecialchars($this->input->post('tambah_nm_anggota')),
            'jk'             => htmlspecialchars($this->input->post('tambah_jk')),
            'alamat_lengkap' => htmlspecialchars($this->input->post('tambah_alamat_lengkap')),
            'kode_pos'       => htmlspecialchars($this->input->post('tambah_kode_pos')),
            'nm_rt'          => htmlspecialchars($this->input->post('tambah_nm_rt')),
            'nm_rw'          => htmlspecialchars($this->input->post('tambah_nm_rw')),
            'alamat_id'      => $alamat_id,
            'tempat_lahir'   => htmlspecialchars($this->input->post('tambah_tempat_lahir')),
            'tgl_lahir'      => htmlspecialchars($this->input->post('tambah_tgl_lahir')),
            'no_hp'          => htmlspecialchars($this->input->post('tambah_no_hp')),
            'pekerjaan'      => htmlspecialchars($this->input->post('tambah_pekerjaan')),
            'suami_istri'    => $suami_istri,
            'foto_ktp'       => htmlspecialchars($this->input->post('foto_ktp')),
            'produk_id'      => htmlspecialchars($this->input->post('produk_id')),
            'pokok_pinjaman' => htmlspecialchars($this->input->post('pokok_pinjaman'))
        );
        return $data_inputan;
    }
    private function _cekAnggotaPinjamanAktif($data_inputan)
    {
        $alamat_id = $data_inputan['alamat_id'];
        // Cek Apakah Anggota sudah terdaftar dalam database
        $cek_anggota = $this->db->get_where('anggota', ['nik' => $data_inputan['nik']])->row_array();
        if ($cek_anggota > 0) :
            $anggota_id = $cek_anggota['id'];
            $cek_pengajuan = $this->db->get_where('p_koperasi_kontrak', ['anggota_id' => $anggota_id, 'status_kontrak' => 'KONFIRMASI'])->row_array();
            if ($cek_pengajuan > 0) :
                $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Sudah Melakukan Pengajuan Pinjaman!</div>');
                redirect('marketing');
            endif;
            $cek_terima = $this->db->get_where('p_koperasi_kontrak', ['anggota_id' => $anggota_id, 'status_kontrak' => 'TERIMA'])->row_array();
            if ($cek_terima > 0) :
                $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Menunggu Untuk Melakukan Pencairan Pinjaman!</div>');
                redirect('marketing');
            endif;
            $cek_aktif = $this->db->get_where('p_koperasi_kontrak', ['anggota_id' => $anggota_id, 'status_kontrak' => 'AKTIF'])->row_array();
            if ($cek_aktif > 0) :
                $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Masih Ada Pinjaman Aktif!</div>');
                redirect('marketing');
            endif;
            $cek_macet = $this->db->get_where('p_koperasi_kontrak', ['anggota_id' => $anggota_id, 'status_kontrak' => 'MACET'])->row_array();
            if ($cek_macet > 0) :
                $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Masih Ada Pinjaman Aktif!</div>');
                redirect('marketing');
            endif;
            return $anggota_id;
        else :
            $this->_cekKTPAnggota($data_inputan);
            $this->_validasiComboBox($data_inputan);
            $this->_validasiNomorHP($data_inputan);
            $anggota_id = $this->insert_model->simpanDataPengajuanKoperasi($data_inputan, $alamat_id);
            $this->update_model->menambahFotoKKAnggota($anggota_id);
            return $anggota_id;
        endif;
    }
    // Validasi KTP
    private function _cekKTPAnggota($data_inputan)
    {
        $nik = $data_inputan['nik'];
        // Cek Apakah 16 karakter
        $hitung_nik      = strlen($nik);
        if ($hitung_nik != 16) :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">NIK Harus 16 Karakter!</div>');
            redirect('marketing');
        endif;
    }
    // Validasi Inputan Combo Box
    private function _validasiComboBox($data_inputan)
    {
        if ($data_inputan['jk'] == 'ok') :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Jenis Kelamin Harus Di Isi!</div>');
            redirect('marketing');
        endif;
        if ($data_inputan['nm_rt'] == 'ok') :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Kolom RT Harus Diisi!</div>');
            redirect('marketing');
        endif;
        if ($data_inputan['nm_rw'] == 'ok') :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Kolom RW Harus Diisi!</div>');
            redirect('marketing');
        endif;
    }
    private function _validasiNomorHP($data_inputan)
    {
        $cek_nomor = $this->db->get_where('anggota', ['no_hp' => $data_inputan['no_hp']])->row_array();
        if ($cek_nomor > 0) :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Nomor HP Sudah Di Gunakan Anggota Lain!</div>');
            redirect('marketing');
        endif;
        $cek_nomor_cadangan = $this->db->get_where('anggota_hp_cadangan', ['no_hp' => $data_inputan['no_hp']])->row_array();
        if ($cek_nomor_cadangan > 0) :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Nomor HP Sudah Di Gunakan Anggota Lain!</div>');
            redirect('marketing');
        endif;
    }
    // Menunjukkan data identitas pinjaman
    private function _dataIdentitasPinjaman($data_inputan, $anggota_id)
    {
        $cek_ap             = $this->db->get_where('p_koperasi_aturan', ['produk_id' => $data_inputan['produk_id']])->row_array();
        $nomor_kontrak      = $data_inputan['login_id'] . $data_inputan['produk_id'] . date('ymdhis');
        // Potongan Awal saat pencairan
        $pot_admin          = $data_inputan['pokok_pinjaman'] * $cek_ap['administrasi'] / 100;
        $pot_rk             = $data_inputan['pokok_pinjaman'] * $cek_ap['rk'] / 100;
        // Besaran Pokok Setiap kali Pembayaran
        $pokok_angsuran    = $data_inputan['pokok_pinjaman'] / $cek_ap['tempo'];
        $pokokangsuran     = ceil($pokok_angsuran);
        $bsr_pokok         = round($pokokangsuran, -2);
        // Simpanan atau tabungan setiap pembayaran
        $b_simpanan        = ($data_inputan['pokok_pinjaman'] * $cek_ap['simpanan'] / 100) / $cek_ap['tempo'];
        $simpananpokok     = ceil($b_simpanan);
        $bsr_simpanan      = round($simpananpokok, -2);
        // Besar Angsuran setiap bulan
        // Biaya Jasa Setiap transaksi pembayaran
        $bsr_jasa          = ($data_inputan['pokok_pinjaman'] * $cek_ap['jasa'] / 100) / $cek_ap['tempo'];
        // Biaya yang harus di bayar
        $bsr_angsuran      = $bsr_pokok + $bsr_simpanan + $bsr_jasa;
        // Total Pembayaran sampai lunas
        $ttl_bayar         = $bsr_angsuran * $cek_ap['tempo'];
        $detail_kontrak = array(
            'id'              => $nomor_kontrak,
            'anggota_id'      => $anggota_id,
            'aturan_id'       => $cek_ap['id'],
            'pokok_pinjaman'  => $data_inputan['pokok_pinjaman'],
            'bsr_admin'       => $pot_admin,
            'bsr_rk'          => $pot_rk,
            'bsr_pokok'       => $bsr_pokok,
            'bsr_simpanan'    => $bsr_simpanan,
            'bsr_jasa'        => $bsr_jasa,
            'bsr_angsuran'    => $bsr_angsuran,
            'tempo_pinjaman'  => $cek_ap['tempo'],
            'ttl_bayar'       => $ttl_bayar,
            'status_kontrak'  => 'KONFIRMASI',
            'login_id'        => $data_inputan['login_id']
        );
        return $detail_kontrak;
    }
}

/* End of file ControllerBeranda.php and path \application\controllers\marketing\ControllerBeranda.php */