<?php

use Google\Service\AndroidPublisher\Timestamp;

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

class Insert_model extends CI_Model
{
    // Menu Kelola Pinjaman
    // Pengajuan pinjaman
    function tambahPengajuanPinjaman($detail_kontrak)
    {
        if (htmlspecialchars($this->input->post('pakai_jaminan')) == 'N') :
            $jaminan        = 'N';
            $status_kontrak = 'KONFIRMASI';
        else :
            $jaminan        = 'Y';
            $status_kontrak = 'PROSES';
        endif;
        $data_kontrak = array(
            'id'             => $detail_kontrak['id'],
            'anggota_id'     => $detail_kontrak['anggota_id'],
            'aturan_id'      => $detail_kontrak['aturan_id'],
            'pokok_pinjaman' => $detail_kontrak['pokok_pinjaman'],
            'bsr_admin'      => $detail_kontrak['bsr_admin'],
            'bsr_rk'         => $detail_kontrak['bsr_rk'],
            'bsr_pokok'      => $detail_kontrak['bsr_pokok'],
            'bsr_simpanan'   => $detail_kontrak['bsr_simpanan'],
            'bsr_jasa'       => $detail_kontrak['bsr_jasa'],
            'bsr_angsuran'   => $detail_kontrak['bsr_angsuran'],
            'tempo_pinjaman' => $detail_kontrak['tempo_pinjaman'],
            'ttl_bayar'      => $detail_kontrak['ttl_bayar'],
            'jaminan'        => $jaminan,
            'status_kontrak' => $status_kontrak,
            'login_id'       => $detail_kontrak['login_id']
        );
        $this->db->insert('p_koperasi_kontrak', $data_kontrak);
        $data_progress = array(
            'kontrak_id' => $detail_kontrak['id'],
            'tgl_pengajuan' => date('Y-m-d')
        );
        if (htmlspecialchars($this->input->post('pakai_jaminan')) == 'Y') :
            $data_jaminan = array(
                'kontrak_id' =>  $detail_kontrak['id'],
                'nm_agungan' => htmlspecialchars($this->input->post('tambah_pakai_jaminan'))
            );
            $this->db->insert('p_koperasi_agungan', $data_jaminan);
        endif;
        $this->db->insert('p_koperasi_progres', $data_progress);
    }
    function tambah_detail_anggota_keluarga($data_inputan)
    {
        $data = array(
            'kk_id'           => $data_inputan['no_kk'],
            'anggota_id'      => $data_inputan['id_anggota'],
            'status_keluarga' => 'anak'
        );
        $this->db->insert('anggota_keluarga_detail', $data);
    }
    function tambah_anggota_keluarga($data_inputan)
    {
        $data_kk = array(
            'nomor_kk'     => $data_inputan['no_kk'],
            'anggota_id'   => $data_inputan['id_anggota'],
            'jml_keluarga' => 1
        );
        $this->db->insert('anggota_keluarga', $data_kk);
        $data = array(
            'kk_id'           => $data_inputan['no_kk'],
            'anggota_id'      => $data_inputan['id_anggota'],
            'status_keluarga' => 'suami_istri'
        );
        $this->db->insert('anggota_keluarga_detail', $data);
        $this->db->where('kk_id', $data_inputan['no_kk_lama']);
        $this->db->delete('anggota_keluarga_detail');
        $this->db->where('nomor_kk', $data_inputan['no_kk_lama']);
        $this->db->delete('anggota_keluarga');
    }
    // Proses Pengajuan Pinjaman
    function ajukanPengajuanPinjaman($inputan, $nomor_kontrak)
    {
        $cek_anggota = $this->db->get_where('tbl_anggota', ['nik' => $inputan['nik']])->row_array();
        $ap = $this->db->get_where('koperasi_aturan', ['sub_idkategori' => $inputan['sub_idkategori']])->row_array();
        $b_admin = $inputan['pokok_pinjaman'] * $ap['administrasi'] / 100;
        $b_rk = $inputan['pokok_pinjaman'] * $ap['rk'] / 100;
        $pokok_angsuran = $inputan['pokok_pinjaman'] /  $ap['tempo'];
        // Pembulatan Pokok Angsuran
        $pokokangsuran = ceil($pokok_angsuran);
        $b_angsuran    = round($pokokangsuran, -2);
        // End Pembulatan Pokok Angsuran
        $b_jasa = ($inputan['pokok_pinjaman'] * $ap['jasa'] / 100) / $ap['tempo'];
        $b_simpanan = ($inputan['pokok_pinjaman'] * $ap['simpanan'] / 100) / $ap['tempo'];
        // Pembulatan Simpanan Wajib
        $simpananpokok = ceil($b_simpanan);
        $simpanan_asli = round($simpananpokok, -2);
        // End Pembulatan Simpanan Wajib
        $data_kontrak = array(
            'id'                => $nomor_kontrak,
            'anggota_id'        => $cek_anggota['id'],
            'sub_idkategori'    => $inputan['sub_idkategori'],
            'pokok_pinjaman'    => $inputan['pokok_pinjaman'],
            'tgl_pengajuan'     => date('Y-m-d'),
            'tgl_konfirmasi'    => date('Y-m-d'),
            'tgl_realisasi'     => date('Y-m-d'),
            'administrasi'      => $b_admin,
            'rk'                => $b_rk,
            'pokok'             => $b_angsuran,
            'jasa'              => $b_jasa,
            'simpanan'          => $simpanan_asli,
            'bsr_angsuran'      => $b_angsuran + $b_jasa + $simpanan_asli,
            'lama_angsuran'     => $ap['tempo'],
            'ttl_angsuran'      => ($b_angsuran + $b_jasa + $simpanan_asli) * $ap['tempo'],
            'status_kontrak'    => 'PENGAJUAN',
            'marketing_id'      => $this->session->userdata('isloggedin')
        );

        // Pengulangan
        $a = 1;
        while ($a <= $ap['tempo']) :
            $angs_ke = $a;
            $data_buku = array(
                'kontrak_id' => $nomor_kontrak,
                'angs_ke'       => $angs_ke,
                'tgl_tagih'     => date('Y-m-d', strtotime('+' . (7 * $angs_ke) . ' day', strtotime(date('Y-m-d')))),
                'jasa_pinjam'   => $b_jasa,
                'simp_pkok'     => $simpanan_asli,
                'ttl_angsuran'  => ($b_angsuran + $b_jasa + $simpanan_asli),
                'status_bayar'  => 'AKTIF'
            );
            $a++;
            echo '<pre>';
            var_dump($data_buku);
        endwhile;
        die;
    }
    // Tambah Data Pengajuan Pinjaman Koperasi
    function simpanDataPengajuanKoperasi($data_inputan, $alamat_id, $isi_index)
    {
        // Upload Gambar Dulu
        // Upload KTP
        $lk_file = './assets/foto_ktp';
        if (!is_dir($lk_file))
            mkdir($lk_file, 0777, TRUE);
        // Membuat File Baru
        $index_file = $lk_file . 'index.html';
        if (!file_exists($index_file)) {
            file_put_contents($index_file, $isi_index);
        }
        $config['upload_path']   = './assets/foto_ktp';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['encrypt_name']  = true;
        $config['overwrite']     = true;
        $config['quality']       = '50%';
        $config['max_size']      = 10024; // 10MB
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('foto_ktp')) :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Foto KTP Tidak Berhasil di Upload!</div>');
            redirect('marketing/kegiatan/pengajuan_pinjaman');
        else :
            $_FILES['file']['name'] = $_FILES['foto_ktp']['name'];
            $_FILES['file']['type'] = $_FILES['foto_ktp']['type'];
            $_FILES['file']['tmp_name'] = $_FILES['foto_ktp']['tmp_name'];
            $_FILES['file']['size'] = $_FILES['foto_ktp']['size'];
            $uploadDataKTP = $this->upload->data();
            $data_anggota = array(
                'nik'            => $data_inputan['nik'],
                'nm_anggota'     => $data_inputan['nm_anggota'],
                'jk'             => $data_inputan['jk'],
                'alamat_lengkap' => $data_inputan['alamat_lengkap'],
                'nm_rt'          => $data_inputan['nm_rt'],
                'nm_rw'          => $data_inputan['nm_rw'],
                'id_alamat'      => $alamat_id,
                'tempat_lahir'   => $data_inputan['tempat_lahir'],
                'tgl_lahir'      => $data_inputan['tgl_lahir'],
                'no_hp'          => $data_inputan['no_hp'],
                'pekerjaan'      => $data_inputan['pekerjaan'],
                'suami_istri'    => $data_inputan['suami_istri'],
                'foto_ktp'       => $uploadDataKTP['file_name'],
                'status_anggota' => 'CALON_ANGGOTA'
            );
            $this->db->insert('anggota', $data_anggota);
        endif;
        $cek_anggota = $this->db->get_where('anggota', ['nik' => $data_inputan['nik']])->row_array();
        $anggota_id = $cek_anggota['id'];
        return $anggota_id;
    }
    function uploadGambarKK($data_inputan, $anggota_id)
    {
        $lk_file = './assets/foto_kk';
        if (!is_dir($lk_file))
            mkdir($lk_file, 0777, TRUE);
        $config['upload_path']   = './assets/foto_kk';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['encrypt_name']  = true;
        $config['overwrite']     = true;
        $config['quality']       = '50%';
        $config['max_size']      = 10024; // 10MB
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('foto_kk')) :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Foto KK Tidak Berhasil di Upload!</div>');
            $data_anggota = array(
                'foto_kk'       => 'Default.png'
            );
            $this->db->where('id', $anggota_id);
            $this->db->update('anggota', $data_anggota);
        else :
            $_FILES['file']['name'] = $_FILES['foto_kk']['name'];
            $_FILES['file']['type'] = $_FILES['foto_kk']['type'];
            $_FILES['file']['tmp_name'] = $_FILES['foto_kk']['tmp_name'];
            $_FILES['file']['size'] = $_FILES['foto_kk']['size'];
            $uploadDataKK = $this->upload->data();
            $data_anggota = array(
                'foto_kk'       => $uploadDataKK['file_name'],
            );
            $this->db->where('id', $anggota_id);
            $this->db->update('anggota', $data_anggota);
        endif;
    }
    // Tambah Nota Angsuran Pinjaman
    function md_NotaAngsuran($status_nota, $angsuran_id, $nomor_invoice, $data_aturan, $data_kontrak)
    {
        $data_nota = array(
            'id'             => $nomor_invoice,
            'produk_id'      => $data_aturan['produk_id'],
            'anggota_id'     => $data_kontrak['anggota_id'],
            'tgl_pembayaran' => date('Y-m-d'),
            'qty_pembayaran' => 1,
            'ttl_bayar'      => $data_kontrak['bsr_angsuran'],
            'status_kas'     => 'MASUK',
            'status_nota'    => 'PROSES',
            'petugas'        => $this->session->userdata('isloggedin')
        );
        $this->db->insert('nota', $data_nota);
        $data_rincian_nota = array(
            'nota_id'        => $nomor_invoice,
            'angsuran_id'    => $angsuran_id,
            'bayar'          => $data_kontrak['bsr_angsuran'],
            'status_bayar'   => $status_nota
        );
        $this->db->insert('p_koperasi_nota', $data_rincian_nota);
    }
    // Menambahkan kas keluar koperasi pinjaman
    function pencairanKasKeluar()
    {
        $cek_kontrak   = $this->db->get_where('p_koperasi_kontrak', ['id' => htmlspecialchars($this->input->post('kontrak_id'))])->row_array();
        $cek_aturan    = $this->db->get_where('p_koperasi_aturan', ['id' => $cek_kontrak['aturan_id']])->row_array();
        $cek_progress  = $this->db->get_where('p_koperasi_progres', ['kontrak_id' => htmlspecialchars($this->input->post('kontrak_id'))])->row_array();
        $data_kas = array(
            'id'              => date('ymdhis'),
            'produk_id'       => $cek_aturan['produk_id'],
            'anggota_id'      => $cek_kontrak['anggota_id'],
            'tgl_pembayaran'  => date('Y-m-d'),
            'qty_pembayaran'  => 1,
            'ttl_bayar'       => $cek_kontrak['pokok_pinjaman'],
            'status_kas'      => 'OPERASIONAL',
            'status_nota'     => 'TERIMA',
            'petugas'         => $this->session->userdata('isloggedin'),
            'kasir'           => $this->session->userdata('isloggedin'),
            'ket_nota'        => 'Realisasi Pinjaman Nomor Kontrak ' . htmlspecialchars($this->input->post('kontrak_id')),
            'invoice_pdf'     => $cek_progress['bukti_terima']
        );
        $this->db->insert('nota', $data_kas);
    }
    function omsetPencairanKasMasuk($nama_file, $cek_kontrak, $cek_aturan)
    {
        $cek_aturan    = $this->db->get_where('p_koperasi_aturan', ['id' => $cek_kontrak['aturan_id']])->row_array();
        $data_kas2 = array(
            'id'              => date('ymdhiss'),
            'produk_id'       => $cek_aturan['produk_id'],
            'anggota_id'      => $cek_kontrak['anggota_id'],
            'tgl_pembayaran'  => date('Y-m-d'),
            'qty_pembayaran'  => 1,
            'ttl_bayar'       => $cek_kontrak['bsr_admin'] + $cek_kontrak['bsr_rk'],
            'status_kas'      => 'OMSET',
            'status_nota'     => 'TERIMA',
            'petugas'         => $this->session->userdata('isloggedin'),
            'kasir'           => $this->session->userdata('isloggedin'),
            'ket_nota'        => 'Biaya Admin dan RK Pinjaman Nomor Kontrak ' . htmlspecialchars($this->input->post('kontrak_id')),
            'invoice_pdf'     => $nama_file
        );
        $this->db->insert('nota', $data_kas2);
    }
    // Ubah data karyawan
    function tambahDataIdentitasKaryawan($data_inputan, $alamat_id)
    {
        $config['upload_path']   = './assets/ptgs_id';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['encrypt_name']  = true;
        $config['overwrite']     = true;
        $config['quality']       = '50%';
        $config['max_size']      = 10024; // 10MB
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('foto_ktp')) :
            $data_login = array(
                'email'             => $data_inputan['email_baru'],
                'no_hp'             => $data_inputan['no_hp_baru'],
                'nm_panggilan'      => $data_inputan['nm_panggilan']
            );
            $this->db->where('id', $data_inputan['login_id']);
            $this->db->update('sistem_login', $data_login);
            $data_identitas = array(
                'login_id'        => $data_inputan['login_id'],
                'nik'             => $data_inputan['nik'],
                'jk'              => $data_inputan['jk'],
                'tempat_lahir'    => $data_inputan['tempat_lahir'],
                'tgl_lahir'       => $data_inputan['tgl_lahir'],
                'alamat_id'       => $alamat_id,
                'tgl_gabung'      => $data_inputan['tgl_gabung']
            );
            $this->db->insert('sistem_identitas', $data_identitas);
        else :
            $_FILES['file']['name'] = $_FILES['foto_ktp']['name'];
            $_FILES['file']['type'] = $_FILES['foto_ktp']['type'];
            $_FILES['file']['tmp_name'] = $_FILES['foto_ktp']['tmp_name'];
            $_FILES['file']['size'] = $_FILES['foto_ktp']['size'];
            $uploadData = $this->upload->data();
            // Inputan
            $data_login = array(
                'email'             => $data_inputan['email_baru'],
                'no_hp'             => $data_inputan['no_hp_baru'],
                'nm_panggilan'      => $data_inputan['nm_panggilan']
            );
            $this->db->where('id', $data_inputan['login_id']);
            $this->db->update('sistem_login', $data_login);
            $data_identitas = array(
                'login_id'        => $data_inputan['login_id'],
                'nik'             => $data_inputan['nik'],
                'jk'              => $data_inputan['jk'],
                'tempat_lahir'    => $data_inputan['tempat_lahir'],
                'tgl_lahir'       => $data_inputan['tgl_lahir'],
                'alamat_id'       => $alamat_id,
                'foto_ktp'        => $uploadData['file_name'],
                'tgl_gabung'      => $data_inputan['tgl_gabung']
            );
            $this->db->insert('sistem_identitas', $data_identitas);
        endif;
    }
}
