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

class ControllerArisanMotor extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        check_not_login();
        if ($this->session->userdata('level') != 5) {
            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('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_kotkab           = $this->select_model->vd_kotkab();
        $bulan = date('m');
        $tahun = date('Y');
        // Data Isian Konten
        $arisan_motor_aktif    = $this->select_model->getDataArisanMotorAktif(); // Menampilkan data arisan heboh aktif
        $arisan_motor_belum    = $this->select_model->getDataArisanMotorBelum(); // Menampilkan data arisan heboh aktif
        $tagihan_tunggakan     = $this->select_model->getTagihanArisanMotorTunggakan();  // Menampilkan table tagihan yang status BELUM
        $data_tagihan          = $this->select_model->getTagihanArisanMotor(); // Menampilkan table tagihan yang status BELUM
        $besar_tagihan         = $this->select_model->getBesarTagihanArisanMotor();
        $data_transaksi        = $this->select_model->getTagihanArisanMotorBulanan($bulan, $tahun); // Menampilkan table tagihan yang status BELUM
        $ttl_anggota           = count($data_tagihan);
        $ttl_anggota_tunggakan = count($tagihan_tunggakan);
        $pendapatan_motor      = $this->select_model->getPendapatanArisanMotor();
        $kas_motor_bulan       = $this->select_model->getDataKasArisanMotorBulan();
        $kas_motor_seluruh     = $this->select_model->getDataKasArisanMotorSeluruh();
        $anggota_arisan        = $this->select_model->vd_anggotaArisanMotor();
        $da_arisan             = $this->select_model->vd_detailanggotaArisanMotor();
        $data = array(
            // Untuk memanggil halaman sesuai menu
            'folder'                => 'arisan/motor',
            'page'                  => 'index',
            'judul'                 => 'Kelola Bayar Arisan Motor || Bagian Kasir',
            // Data login aplikasi
            'data_id_login'         => $data_id_login,
            'data_login'            => $data_login,
            'notif'                 => $notif,
            'transaksi_motor'       => $data_transaksi,
            'data_kota'             => $data_kotkab,
            // Data isian Konten
            'pengajuan_verif'       => $data_tagihan,
            'tagihan_verif'         => $besar_tagihan,
            'blm_bayar'             => $ttl_anggota,
            'pendapatan_arisan'     => $pendapatan_motor,
            'kas_motor_bulan'       => $kas_motor_bulan,
            'kas_motor_seluruh'     => $kas_motor_seluruh,
            'arisan_motor'          => $arisan_motor_aktif,
            'arisan_motor_belum'    => $arisan_motor_belum,
            'tagihan_tunggakan'     => $tagihan_tunggakan,
            'ttl_anggota_tunggakan' => $ttl_anggota_tunggakan,
            'anggota_arisan'        => $anggota_arisan,
            'detail_produk'         => $da_arisan
        );
        $this->load->view('kasir/index', $data);
    }
    public function verifikasi($id)
    {
        $kd_invoice      = $this->encrypt->decode($id);
        $data_invoice    = $this->select_model->getDataInvoice($kd_invoice);
        $produk_id       = $data_invoice['produk_id'];
        // Nama Marketing
        $this->update_model->vnota_arisan($kd_invoice);
        $this->_cetakInvoice($kd_invoice, $produk_id);
        $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil Verifikasi Pembayaran!</div>');
        redirect('kasir/arisan/kelompok_motor');
    }
    public function verifikasi_tunggakan($id)
    {
        $kd_invoice      = $this->encrypt->decode($id);
        $data_invoice    = $this->select_model->getDataInvoice($kd_invoice);
        $produk_id       = $data_invoice['produk_id'];
        // Nama Marketing
        $this->update_model->vnota_arisanTunggakan($kd_invoice);
        $this->_cetakInvoice($kd_invoice, $produk_id);
        $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil Verifikasi Pembayaran Tunggakan!</div>');
        redirect('kasir/arisan/kelompok_motor');
    }
    public function crud()
    {
        if (isset($_POST['simpanBayarAnggota'])) {
            $arisan_id     = htmlspecialchars($this->input->post('regist_arisan')); // inputan ID Arisan
            $id_anggota    = htmlspecialchars($this->input->post('id_anggota')); // Inputan Nomor Regist
            $besar_iuran   = htmlspecialchars($this->input->post('besar_iuran')); // Cek Tunggakan
            $jml_tunggakan = htmlspecialchars($this->input->post('jml_tunggakan')); // Cek Tunggakan
            // Cek ttl anggota
            $cek_anggota2  = $this->select_model->gsetDataAnggota($id_anggota, $arisan_id);
            if ($jml_tunggakan > 0) :
                $qty_bayar    = $jml_tunggakan + htmlspecialchars($this->input->post('jml_iuran'));
                $bayar_custom = $besar_iuran * $qty_bayar;
            else :
                $qty_bayar = htmlspecialchars($this->input->post('jml_iuran'));
                $bayar_custom = $besar_iuran * $qty_bayar;
            endif;
            $produk_id   = 22;
            // Cek Jadwal Aktif
            $cek_jadwal = $this->db->get_where('p_arisan_jadwal', ['regist_arisan' => $arisan_id, 'status_undian !=' => 'SELESAI'])->row_array();
            $jadwal_id  = $cek_jadwal['id'];
            // Melihat invoice yang sudah ada dan menambah 1
            $data_invoice           = $this->select_model->getDataTagihanUrutMotor();
            $cek_nomor_urut         = substr($data_invoice['id'], 8, 5);
            $no_invoice_selanjutnya = $cek_nomor_urut + 1;
            $total_huruf            = strlen($no_invoice_selanjutnya);
            // Cek Apakah Anggota sudah bayar atau belum
            $cek_tagihan            = $this->select_model->getDataTagihanAnggota($jadwal_id, $arisan_id, $id_anggota);
            if ($cek_tagihan > 0) :
                $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Anggota Sudah Bayar!</div>');
            else :
                if ($total_huruf == 1) :
                    $nomor_invoice = date('ymd') . $produk_id . '000' . $no_invoice_selanjutnya;
                elseif ($total_huruf == 2) :
                    $nomor_invoice = date('ymd') . $produk_id . '00' . $no_invoice_selanjutnya;
                elseif ($total_huruf == 3) :
                    $nomor_invoice = date('ymd') . $produk_id . '0' . $no_invoice_selanjutnya;
                else :
                    $nomor_invoice = date('ymd') . $produk_id . $no_invoice_selanjutnya;
                endif;
                // Data untuk tabel invoice
                $data_voice = array(
                    'id'              => $nomor_invoice,
                    'produk_id'       => $produk_id,
                    'anggota_id'      => $id_anggota,
                    'tgl_pembayaran'  => date('Y-m-d'),
                    'qty_pembayaran'  => $qty_bayar,
                    'ttl_bayar'       => $bayar_custom,
                    'status_kas'      => 'MASUK',
                    'status_nota'     => 'TERIMA',
                    'petugas'         => $this->session->userdata('isloggedin'),
                    'kasir'           => $this->session->userdata('isloggedin')
                );
                $this->db->insert('nota', $data_voice);
                foreach ($cek_anggota2 as $Anggota) :
                    $data_rinci = array(
                        'nota_id'       => $nomor_invoice,
                        'jadwal_id'     => $jadwal_id,
                        'regist_arisan' => $arisan_id,
                        'regist_undian' => $Anggota->regist_undian,
                        'bayar'         => $Anggota->tagihan_iuran,
                        'status_bayar'  => 'LANCAR',
                    );
                    $this->db->insert('p_arisan_nota', $data_rinci);
                endforeach;
                $kd_invoice = $nomor_invoice;
                $this->_cetakInvoiceKasir($kd_invoice, $produk_id);
                $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil Bayar Tagihan Arisan!</div>');
            endif;
            redirect('kasir/arisan/kelompok_motor');
        }
        if (isset($_POST['simpanAnggotaArisanMotor'])) {
            $alamat_id    = $this->_cekDataAlamat();
            $data_inputan = $this->_inputanDaftarAnggotaMotor($alamat_id);
            $data_anggota = $this->db->get_where('anggota', ['nik' => $data_inputan['nik']])->row_array();
            if ($data_anggota > 0) :
                $anggota_id = $data_anggota['id'];
            else :
                $this->insert_model->simpanCalonAnggotaKoperasi($data_inputan);
                $anggota_baru = $this->db->get_where('anggota', ['nik' => $data_inputan['nik']])->row_array();
                $anggota_id = $anggota_baru['id'];
            endif;
            $data_pengajuan = array(
                'anggota_id'    => $anggota_id,
                'regist_arisan' => $data_inputan['regist_arisan'],
                'rekom_id'      => $this->session->userdata('isloggedin')
            );
            $this->db->insert('p_arisan_pengajuan', $data_pengajuan);
            $this->session->set_flashdata('pesan_berhasil', '<div class="alert alert-success" id="pesan_berhasil" role="alert">Berhasil Mengajukan anggota arisan motor!</div>');
            redirect('kasir/arisan/kelompok_motor');
        }
    }
    // Private function
    private function _cetakInvoice($kd_invoice, $produk_id)
    {
        $data_invoice          = $this->select_model->getDataInvoice($kd_invoice); // DONE
        $data_rinci            = $this->select_model->getDataInvoiceRinci($kd_invoice);
        $tahun = date('Y', strtotime($data_invoice['tgl_pembayaran']));
        $bulan = date('m', strtotime($data_invoice['tgl_pembayaran']));
        $berkas_lama = 'assets/invoice/arisan_motor/' . $tahun . '/' . $bulan . '/' . $data_invoice['invoice_pdf'] . '';
        unlink($berkas_lama);
        // Data Login
        $data_login            = $this->userlogin->user_login();
        $data_id_login         = $this->session->userdata('isloggedin');
        // Nama Marketing
        $data_marketing        = $this->select_model->getDataMarketing($kd_invoice);
        $data_kasir            = $this->select_model->getDataKasir($kd_invoice);
        $data = array(
            // Untuk memanggil halaman sesuai menu
            'title_pdf'           => 'Invoice Pembayaran Arisan Heboh',
            'folder'              => 'arisan/heboh',
            'page'                => 'index',
            'judul'               => 'Kelola Bayar Arisan Heboh || Bagian Kasir',
            'data_id_login'       => $data_id_login,
            'data_login'          => $data_login,
            // 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 = 'invoice_' . $kd_invoice;
        // setting paper
        $paper = 'A5';
        //orientasi paper potrait / landscape
        $orientation = "landscape";
        $html = $this->load->view('document/nota/nota_bayar_arisan_kasir', $data, true);
        // run dompdf
        if ($produk_id == 21) :
            $lokasi_file = 'assets/invoice/arisan_heboh/' . $tahun . '/' . $bulan . '/';
        else :
            $lokasi_file = 'assets/invoice/arisan_motor/' . $tahun . '/' . $bulan . '/';
        endif;
        $this->pdfgenerator->generate($html, $file_pdf, $paper, $lokasi_file, $orientation);
        $data_update22     = array(
            'invoice_pdf' => $file_pdf . '.pdf'
        );
        $this->db->where('id', $kd_invoice);
        $this->db->update('nota', $data_update22);
    }
    // Private function
    private function _cetakInvoiceKasir($kd_invoice, $produk_id)
    {
        $data_invoice          = $this->select_model->getDataInvoice($kd_invoice); // DONE
        $data_rinci            = $this->select_model->getDataInvoiceRinci($kd_invoice);
        $tahun = date('Y', strtotime($data_invoice['tgl_pembayaran']));
        $bulan = date('m', strtotime($data_invoice['tgl_pembayaran']));
        // Data Login
        $data_login            = $this->userlogin->user_login();
        $data_id_login         = $this->session->userdata('isloggedin');
        // Nama Marketing
        $data_marketing        = $this->select_model->getDataMarketing($kd_invoice);
        $data_kasir            = $this->select_model->getDataKasir($kd_invoice);
        $data = array(
            // Untuk memanggil halaman sesuai menu
            'title_pdf'           => 'Invoice Pembayaran Arisan Heboh',
            'folder'              => 'arisan/heboh',
            'page'                => 'index',
            'judul'               => 'Kelola Bayar Arisan Heboh || Bagian Kasir',
            'data_id_login'       => $data_id_login,
            'data_login'          => $data_login,
            // 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 = 'invoice_' . $kd_invoice;
        // setting paper
        $paper = 'A5';
        //orientasi paper potrait / landscape
        $orientation = "landscape";
        $html = $this->load->view('document/nota/nota_bayar_arisan_kasir', $data, true);
        // run dompdf
        if ($produk_id == 21) :
            $lokasi_file = 'assets/invoice/arisan_heboh/' . $tahun . '/' . $bulan . '/';
        else :
            $lokasi_file = 'assets/invoice/arisan_motor/' . $tahun . '/' . $bulan . '/';
        endif;
        $this->pdfgenerator->generate($html, $file_pdf, $paper, $lokasi_file, $orientation);
        $data_update22     = array(
            'invoice_pdf' => $file_pdf . '.pdf'
        );
        $this->db->where('id', $kd_invoice);
        $this->db->update('nota', $data_update22);
        $nama_file = $file_pdf . '.pdf';
        $cek_option = $this->db->get_where('sistem_option')->row_array();
        $this->_notifWABuktiSetorAsli($nama_file, $lokasi_file, $data_invoice, $cek_option);
    }
    private function _cekDataAlamat()
    {
        $cek_alamat = $this->db->get_where('sistem_alamat', ['nm_desa' => htmlspecialchars($this->input->post('tam_dk_ds')), 'nm_kecamatan' => htmlspecialchars($this->input->post('tam_kecamatan_baru')), 'kot_kab' => htmlspecialchars($this->input->post('tam_kota_kabupaten'))])->row_array();
        if ($cek_alamat > 0) :
            $alamat_id = $cek_alamat['id'];
            return $alamat_id;
        else :
            $this->session->set_flashdata('pesan_gagal', '<div class="alert alert-danger" id="pesan_gagal" role="alert">Alamat Tidak di Temukan, silahkan hubungi developer!</div>');
            redirect('kasir/arisan/kelompok_motor');
        endif;
    }
    private function _inputanDaftarAnggotaMotor($alamat_id)
    {

        $regist_arisan     = htmlspecialchars($this->input->post('regist_arisan'));
        $nik               = htmlspecialchars($this->input->post('nik_motor'));
        $nm_anggota        = htmlspecialchars($this->input->post('tam_nm_anggota'));
        $login_id          = htmlspecialchars($this->input->post('login_id'));
        $jk                = htmlspecialchars($this->input->post('tam_jk'));
        $alamat_lengkap    = htmlspecialchars($this->input->post('tam_alamat_lengkap'));
        $kode_pos          = htmlspecialchars($this->input->post('tam_kode_pos'));
        $nm_rt             = htmlspecialchars($this->input->post('tam_nm_rt'));
        $nm_rw             = htmlspecialchars($this->input->post('tam_nm_rw'));
        $tempat_lahir      = htmlspecialchars($this->input->post('tam_tempat_lahir'));
        $tgl_lahir         = htmlspecialchars($this->input->post('tam_tgl_lahir'));
        $no_hp             = htmlspecialchars($this->input->post('tam_no_hp'));
        $pekerjaan         = htmlspecialchars($this->input->post('tam_pekerjaan'));
        $suami_istri       = htmlspecialchars($this->input->post('tam_suami_istri'));
        $foto_ktp          = htmlspecialchars($this->input->post('foto_ktp'));
        $data_inputan = array(
            'regist_arisan'  => $regist_arisan,
            'nik'            => $nik,
            'nm_anggota'     => $nm_anggota,
            'login_id'       => $login_id,
            'jk'             => $jk,
            'alamat_lengkap' => $alamat_lengkap,
            'kode_pos'       => $kode_pos,
            'nm_rt'          => $nm_rt,
            'nm_rw'          => $nm_rw,
            'alamat_id'      => $alamat_id,
            'tempat_lahir'   => $tempat_lahir,
            'tgl_lahir'      => $tgl_lahir,
            'no_hp'          => $no_hp,
            'pekerjaan'      => $pekerjaan,
            'suami_istri'    => $suami_istri,
            'foto_ktp'       => $foto_ktp
        );
        return $data_inputan;
    }
    private function _notifWABuktiSetorAsli($nama_file, $lokasi_file, $data_invoice, $cek_option)
    {
        $cek_nomor = substr($data_invoice['no_hp'], 0, 1);
        if ($cek_nomor == 0) :
            $no_hp = '62' . substr($data_invoice['no_hp'], 1, 20);
        else :
            $no_hp = $data_invoice['no_hp'];
        endif;

        $pesan = 'Hei, *_' . $data_invoice['nm_anggota'] . '_*,

Terimakasih sudah melakukan pembayaran iuran Arisan Motor, Klik link dibawah untuk melihat invoice pembayaran Anda.

Link Invoice : https://siap.kspbinaartha.com/' . $lokasi_file .  $nama_file . '

*Info :* ' . $cek_option['cs_arisan'] . '';

        $body = array(
            "api_key" => $cek_option['api_arisan'],
            "receiver" => $no_hp,
            "data" => array("message" => $pesan)
        );

        $sett_wa = $this->db->get_where('sistem_wa', ['id' => 1])->row_array();
        $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);
    }
}

/* End of file ControllerArisanMotor.php and path \application\controllers\kasir\arisan\ControllerArisanMotor.php */