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

class ControllerPembayaranAngsuran extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        check_not_login();
        $this->set_timezone();
        if ($this->session->userdata('level') != 5) {
            redirect();
        }
        $this->load->library('encrypt');
        $this->load->library('form_validation');
        $this->load->library('Mycustom');
        $this->load->library('pdfgenerator');
        $this->load->library('Notifikasi');
        $this->load->model('bagian_kasir/insert_model');
        $this->load->model('bagian_kasir/select_model');
        $this->load->model('bagian_kasir/update_model');
    }
    public function set_timezone()
    {
        date_default_timezone_set("Asia/Jakarta");
    }
    public function index()
    {
        $notif = $this->notifikasi->notif_kasir();
        // Data Login
        $data_login            = $this->userlogin->user_login();
        $data_id_login         = $this->session->userdata('isloggedin');
        // Data Isian Konten 
        // Jumlah permintaan verifikasi storting
        $data_kasmasukharian    = $this->select_model->vd_TagihanKoperasiHarian();
        $data_kasmasukbulanan   = $this->select_model->vd_TagihanKoperasiBulanan();
        $jml_vstortingharian    = $this->select_model->vd_stortingharian();
        $jml_vstortingbulanan   = $this->select_model->vd_stortingbulanan();
        $jml_stortingharian     = $this->select_model->v_stortingharian();
        $jml_stortingbulanan    = $this->select_model->v_stortingbulanan();
        // Melihatkan transaksi koperasi
        $verif_tagihan          = $this->select_model->vd_verifDataTagihan();
        $data_tagihan           = $this->select_model->vd_historiTransaksiDataTagihan();
        // Pinjaman Aktif
        $data_pinjaman                = $this->select_model->vd_PinjamanAktif();
        $data_angsuran                = $this->select_model->vd_AngsuranAktif();
        $data_macet                   = $this->select_model->vd_AngsuranMacet();
        // echo '<pre>';
        // var_dump($data_macet);
        // die;
        $data = array(
            // Untuk memanggil halaman sesuai menu
            'folder'                 => 'pinjaman/pembayaran',
            'page'                   => 'index',
            'judul'                  => 'Kelola Bayar Angsuran Koperasi || Bagian Kasir',
            // Data login aplikasi
            'data_id_login'          => $data_id_login,
            'data_login'             => $data_login,
            // Data isian Konten
            'notif'                  => $notif,
            // Data 1
            'verif_harian'           => $jml_vstortingharian,
            'verif_bulanan'          => $jml_vstortingbulanan,
            'storting_harian'        => $jml_stortingharian,
            'storting_bulanan'       => $jml_stortingbulanan,
            // Data 2
            'verif_data'             => $verif_tagihan,
            'jml_verif'              => count($verif_tagihan),
            'kas_masuk_harian'       => $data_kasmasukharian,
            'kas_masuk_bulanan'      => $data_kasmasukbulanan,
            // Cek Pinjaman Aktif
            'pinjaman_aktif'         => $data_pinjaman,
            'data_transaksi'         => $data_tagihan,
            'data_angsuran'          => $data_angsuran,
            'data_macet'             => $data_macet
        );
        $this->load->view('kasir/index', $data);
    }
    public function verifikasi($id)
    {
        $angsuran_id            = $this->encrypt->decode($id);
        $data_angsuran          = $this->db->get_where('p_koperasi_angsuran', ['id' => $angsuran_id])->row_array();
        $invoice_rinci          = $this->db->get_where('p_koperasi_nota', ['angsuran_id' => $angsuran_id])->row_array();
        $kd_invoice             = $invoice_rinci['nota_id'];
        $rinci_nota             = $this->select_model->getDataInvoiceRinciAngsuran($kd_invoice);
        $data_invoice           = $this->db->get_where('nota', ['id' => $kd_invoice])->row_array();
        $data_kontrak           = $this->db->get_where('p_koperasi_kontrak', ['id' => $data_angsuran['kontrak_id']])->row_array();
        $data_aturan            = $this->db->get_where('p_koperasi_aturan', ['id' => $data_kontrak['aturan_id']])->row_array();
        $kd_nota                = $kd_invoice;
        $jml_bayar              = count($this->select_model->get_vdAngsuranBayar($data_kontrak));
        // Cek anggota
        $tahun = date('Y', strtotime($data_invoice['tgl_pembayaran']));
        $bulan = date('m', strtotime($data_invoice['tgl_pembayaran']));
        // Melihat Produk ID
        if ($data_invoice['produk_id'] == 121) :
            $lokasi_file = 'assets/invoice/koperasi_mingguan/' . $tahun . '/' . $bulan . '/' . $data_invoice['invoice_pdf'] . '';
        elseif ($data_invoice['produk_id'] == 122) :
            $lokasi_file = 'assets/invoice/koperasi_dua_mingguan/' . $tahun . '/' . $bulan . '/' . $data_invoice['invoice_pdf'] . '';
        elseif ($data_invoice['produk_id'] == 123) :
            $lokasi_file = 'assets/invoice/koperasi_bulanan/' . $tahun . '/' . $bulan . '/' . $data_invoice['invoice_pdf'] . '';
        elseif ($data_invoice['produk_id'] == 124) :
            $lokasi_file = 'assets/invoice/koperasi_musiman/' . $tahun . '/' . $bulan . '/' . $data_invoice['invoice_pdf'] . '';
        elseif ($data_invoice['produk_id'] == 125) :
            $lokasi_file = 'assets/invoice/anggota_bulanan/' . $tahun . '/' . $bulan . '/' . $data_invoice['invoice_pdf'] . '';
        elseif ($data_invoice['produk_id'] == 126) :
            $lokasi_file = 'assets/invoice/karyawan_bulanan/' . $tahun . '/' . $bulan . '/' . $data_invoice['invoice_pdf'] . '';
        endif;
        unlink($lokasi_file);
        $data_invoice_baru = array(
            'status_nota' => 'TERIMA',
            'kasir'       => $this->session->userdata('isloggedin')
        );
        $this->db->where('id', $kd_invoice);
        $this->db->update('nota', $data_invoice_baru);
        // Simpanan Koperasi
        $this->_simpananKoperasi($rinci_nota, $data_aturan, $data_kontrak, $data_invoice, $lokasi_file);
        if ($data_kontrak['tempo_pinjaman'] == $jml_bayar) :
            $jml_macet    = count($this->select_model->vd_AngsuranMacetS($data_kontrak));
            if ($jml_macet >= 4) :
                $data_kontrak_baru = array(
                    'status_kontrak' => 'LUNAS_MACET'
                );
                $this->db->where('id', $data_kontrak['id']);
                $this->db->update('p_koperasi_kontrak', $data_kontrak_baru);
            else :
                $data_kontrak_baru = array(
                    'status_kontrak' => 'LUNAS_LANCAR'
                );
                $this->db->where('id', $data_kontrak['id']);
                $this->db->update('p_koperasi_kontrak', $data_kontrak_baru);
            endif;
            $this->_cetakTandaTerimaKasirLunas($kd_nota, $data_invoice);
        else :
            $this->_cetakTandaTerimaKasir($kd_nota, $data_invoice);
        endif;
        $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil Bayar Angsuran!</div>');
        redirect('kasir/koperasi/pembayaran_pinjaman');
    }
    public function invoice($id)
    {
        $invoice_pdf            = $this->encrypt->decode($id);
        $data_nota              = $this->db->get_where('nota', ['invoice_pdf' => $invoice_pdf])->row_array();
        $produk_id              = $data_nota['produk_id'];
        if ($produk_id == 121) :
            $link =  base_url('assets/invoice/koperasi_mingguan/' . date('Y', strtotime($data_nota['tgl_pembayaran'])) . '/' . date('m', strtotime($data_nota['tgl_pembayaran'])) . '/' . $invoice_pdf);
        elseif ($produk_id == 122):
            $link = base_url('assets/invoice/koperasi_dua_mingguan/' . date('Y', strtotime($data_nota['tgl_pembayaran'])) . '/' . date('m', strtotime($data_nota['tgl_pembayaran'])) . '/' . $invoice_pdf);
        elseif ($produk_id == 123):
            $link = base_url('assets/invoice/koperasi_bulanan/' . date('Y', strtotime($data_nota['tgl_pembayaran'])) . '/' . date('m', strtotime($data_nota['tgl_pembayaran'])) . '/' . $invoice_pdf);
        elseif ($produk_id == 124):
            $link = base_url('assets/invoice/koperasi_musiman/' . date('Y', strtotime($data_nota['tgl_pembayaran'])) . '/' . date('m', strtotime($data_nota['tgl_pembayaran'])) . '/' . $invoice_pdf);
        elseif ($produk_id == 125):
            $link = base_url('assets/invoice/anggota_bulanan/' . date('Y', strtotime($data_nota['tgl_pembayaran'])) . '/' . date('m', strtotime($data_nota['tgl_pembayaran'])) . '/' . $invoice_pdf);
        elseif ($produk_id == 126):
            $link = base_url('assets/invoice/karyawan_bulanan/' . date('Y', strtotime($data_nota['tgl_pembayaran'])) . '/' . date('m', strtotime($data_nota['tgl_pembayaran'])) . '/' . $invoice_pdf);
        endif;
        $rinci_nota = $this->db->get_where('p_koperasi_nota', ['nota_id' => $data_nota['id']])->row_array();
        $data_angsuran = $this->db->get_where('p_koperasi_angsuran', ['id' => $rinci_nota['angsuran_id']])->row_array();
        $data_anggota = $this->db->get_where('anggota', ['id' => $data_nota['anggota_id']])->row_array();

        $caption = 'Nota Pembayaran Pinjaman ' . $data_angsuran['kontrak_id'] . ' Angsuran Ke-' . $data_angsuran['angs_ke'];
        $sett_wa = $this->db->get_where('sistem_wa', ['id' => 2])->row_array();
        if ($sett_wa['status'] == 'PASIF') :
            $no_hp = '628159994711';
        else:
            $cek_nomor = substr($data_anggota['no_hp'], 0, 1);
            if ($cek_nomor == 0) :
                $no_hp = '62' . substr($data_anggota['no_hp'], 1, 20);
            else :
                $no_hp = $data_anggota['no_hp'];
            endif;
        endif;
        $footer = '*KSP Bina Artha Prima*';
        $data_inputan = array(
            'api_key'    => $sett_wa['api_key'],
            'sender'     => $sett_wa['no_hp'],
            'number'     => $no_hp,
            'media_type' => 'document',
            'caption'    => $caption,
            'footer'     => $footer,
            'url'        => $link
        );
        $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);
        $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil Kirim Invoice!</div>');
        redirect('kasir/koperasi/pembayaran_pinjaman');
    }
    // Menambahkan tabungan atau simpanan
    private function _simpananKoperasi($rinci_nota, $data_aturan, $data_kontrak, $data_invoice, $lokasi_file)
    {
        foreach ($rinci_nota as $Rinci_nota) :
            $data_simpanan = array(
                'anggota_id'      => $Rinci_nota->anggota_id,
                'tgl_simpanan'    => date('Y-m-d'),
                'status_simpanan' => 'MASUK',
                'besar_transaksi' => $Rinci_nota->bsr_simpanan,
                'ket_transaksi'   => 'Simpanan ' . $Rinci_nota->kontrak_id . ' angsuran Ke ' . $Rinci_nota->angs_ke
            );
            $this->db->insert('p_simpanan', $data_simpanan);
            $data_nota_omset = array(
                'id'              => date("YmdHis") . 10 . $data_aturan['produk_id'],
                'produk_id'       => 10,
                'tgl_pembayaran'  => date('Y-m-d'),
                'qty_pembayaran'  => 1,
                'ttl_bayar'       => $Rinci_nota->bsr_jasa,
                'status_kas'      => 'OMSET',
                'status_nota'     => 'TERIMA',
                'petugas'         => $data_kontrak['login_id'],
                'kasir'           => $this->session->userdata('isloggedin'),
                'ket_nota'        => 'Jasa Pinjaman ' . $Rinci_nota->nm_anggota . ' ' . $Rinci_nota->kontrak_id . ' angsuran Ke ' . $Rinci_nota->angs_ke,
                'invoice_pdf'     => $lokasi_file
            );
            $this->db->insert('nota', $data_nota_omset);
            if ($Rinci_nota->status_angsuran == 'MACET') :
                $data_angsuran = array(
                    'status_angsuran' => 'LUNAS_MACET',
                    'update_at' => date('Y-m-d H:i:s')
                );
                $this->db->where('id', $Rinci_nota->angsuran_id);
                $this->db->update('p_koperasi_angsuran', $data_angsuran);
            else :
                $data_angsuran = array(
                    'status_angsuran' => 'LUNAS_LANCAR',
                    'update_at' => date('Y-m-d H:i:s')
                );
                $this->db->where('id', $Rinci_nota->angsuran_id);
                $this->db->update('p_koperasi_angsuran', $data_angsuran);
            endif;
        endforeach;
    }
    // Koperasi
    private function _cetakTandaTerimaKasir($kd_nota, $data_invoice)
    {
        $kd_invoice            = $kd_nota;
        $data_invoice          = $this->select_model->getDataInvoice($kd_invoice); // DONE
        $data_rinci            = $this->select_model->getDataInvoiceRinciAngsuran($kd_invoice);
        // Detail data nota
        $data_marketing = $this->db->get_where('sistem_login', ['id' => $data_invoice['petugas']])->row_array();
        $data_kasir = $this->db->get_where('sistem_login', ['id' => $data_invoice['kasir']])->row_array();
        // End data nota
        $data = array(
            // Data isi konten
            'data_invoice'        => $data_invoice,
            'data_rinci'          => $data_rinci,
            'data_marketing'      => $data_marketing,
            'data_kasir'          => $data_kasir
        );
        // filename dari pdf ketika didownload
        $file_pdf = $data_invoice['invoice_pdf'];
        // setting paper
        $paper = 'A5';
        //orientasi paper potrait / landscape
        $orientation = "landscape";
        // $this->load->view('nota/nota_bayar_arisan_petugas', $data);
        $html = $this->load->view('document/nota/nota_pinjaman_koperasi_kasir', $data, true);
        $tahun = date('Y', strtotime($data_invoice['tgl_pembayaran']));
        $bulan = date('m', strtotime($data_invoice['tgl_pembayaran']));
        // run dompdf
        if ($data_invoice['produk_id'] == 121) :
            $lokasi_file = 'assets/invoice/koperasi_mingguan/' . $tahun . '/' . $bulan . '/';
        elseif ($data_invoice['produk_id'] == 122) :
            $lokasi_file = 'assets/invoice/koperasi_dua_mingguan/' . $tahun . '/' . $bulan . '/';
        elseif ($data_invoice['produk_id'] == 123) :
            $lokasi_file = 'assets/invoice/koperasi_bulanan/' . $tahun . '/' . $bulan . '/';
        elseif ($data_invoice['produk_id'] == 124) :
            $lokasi_file = 'assets/invoice/koperasi_musiman/' . $tahun . '/' . $bulan . '/';
        elseif ($data_invoice['produk_id'] == 125) :
            $lokasi_file = 'assets/invoice/anggota_bulanan/' . $tahun . '/' . $bulan . '/';
        elseif ($data_invoice['produk_id'] == 126) :
            $lokasi_file = 'assets/invoice/karyawan_bulanan/' . $tahun . '/' . $bulan . '/';
        endif;
        // Membuat folder
        if (!is_dir($lokasi_file))
            mkdir($lokasi_file, 0777, TRUE);
        // Membuat File
        // Membuat File Baru
        $isi_index = $this->_membuatFileBaruIndex();
        $index_file = $lokasi_file . 'index.html';
        if (!file_exists($index_file)) {
            file_put_contents($index_file, $isi_index);
        }
        $this->pdfgenerator->generate_kasir($html, $file_pdf, $paper, $lokasi_file, $orientation);
    }
    private function _cetakTandaTerimaKasirLunas($kd_nota, $data_invoice)
    {
        $kd_invoice            = $kd_nota;
        $data_invoice          = $this->select_model->getDataInvoice($kd_invoice); // DONE
        $data_rinci            = $this->select_model->getDataInvoiceRinciAngsuran($kd_invoice);
        // Detail data nota
        $data_marketing = $this->db->get_where('sistem_login', ['id' => $data_invoice['petugas']])->row_array();
        $data_kasir = $this->db->get_where('sistem_login', ['id' => $data_invoice['kasir']])->row_array();
        // End data nota
        $data = array(
            // Data isi konten
            'data_invoice'        => $data_invoice,
            'data_rinci'          => $data_rinci,
            'data_marketing'      => $data_marketing,
            'data_kasir'          => $data_kasir
        );
        // filename dari pdf ketika didownload
        $file_pdf = $data_invoice['invoice_pdf'];
        // setting paper
        $paper = 'A5';
        //orientasi paper potrait / landscape
        $orientation = "landscape";
        // $this->load->view('nota/nota_bayar_arisan_petugas', $data);
        $html = $this->load->view('document/nota/nota_pinjaman_koperasi_kasir_lunas', $data, true);
        $tahun = date('Y', strtotime($data_invoice['tgl_pembayaran']));
        $bulan = date('m', strtotime($data_invoice['tgl_pembayaran']));
        // run dompdf
        if ($data_invoice['produk_id'] == 121) :
            $lokasi_file = 'assets/invoice/koperasi_mingguan/' . $tahun . '/' . $bulan . '/';
        elseif ($data_invoice['produk_id'] == 122) :
            $lokasi_file = 'assets/invoice/koperasi_dua_mingguan/' . $tahun . '/' . $bulan . '/';
        elseif ($data_invoice['produk_id'] == 123) :
            $lokasi_file = 'assets/invoice/koperasi_bulanan/' . $tahun . '/' . $bulan . '/';
        elseif ($data_invoice['produk_id'] == 124) :
            $lokasi_file = 'assets/invoice/koperasi_musiman/' . $tahun . '/' . $bulan . '/';
        elseif ($data_invoice['produk_id'] == 125) :
            $lokasi_file = 'assets/invoice/anggota_bulanan/' . $tahun . '/' . $bulan . '/';
        elseif ($data_invoice['produk_id'] == 126) :
            $lokasi_file = 'assets/invoice/karyawan_bulanan/' . $tahun . '/' . $bulan . '/';
        endif;
        // Membuat folder
        if (!is_dir($lokasi_file))
            mkdir($lokasi_file, 0777, TRUE);
        // Membuat File
        // Membuat File Baru
        $isi_index = $this->_membuatFileBaruIndex();
        $index_file = $lokasi_file . 'index.html';
        if (!file_exists($index_file)) {
            file_put_contents($index_file, $isi_index);
        }
        $this->pdfgenerator->generate_kasir($html, $file_pdf, $paper, $lokasi_file, $orientation);
    }
    // Kode membuat file
    private function _membuatFileBaruIndex()
    {
        $isi_index = <<<HTML
    <!DOCTYPE html>
    <html>
    <head>
        <title>403 Forbidden</title>
    </head>
    <body>
    <p>Directory access is forbidden.</p>
    </body>
    </html>
    HTML;
        return $isi_index;
    }
}

/* End of file ControllerPembayaranAngsuran.php and path \application\controllers\kasir\koperasi\ControllerPembayaranAngsuran.php */