<?php
namespace App\Controllers\Admin;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use App\Models\Kkmodel;
use App\Models\Kolektormodel;
use App\Models\Operatormodel;
use App\Models\Tarifmodel;
use App\Models\Diskonmodel;
use App\Models\Invoicemodel;
use App\Models\Strukmodel;
use App\Models\Strukdetailmodel;
use App\Models\Transaksimodel;
use App\Models\Buktibayarmodel;
use App\Models\Gruptransaksimodel;
use App\Models\Jenispembayaranmodel;
use App\Models\Konfigmodel;
use App\Models\Rekbankmodel;
use App\Models\Usermodeladmin;
use Dompdf\Dompdf;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\RoundBlockSizeMode;
use Endroid\QrCode\Writer\PngWriter;

class Laporan extends BaseController
{
    use ResponseTrait;

    private $user;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) 
    {
        parent::initController($request, $response, $logger);
        $this->user = service("user_data");
    }

    private function check_access(){
        $user = service("user_data");
        if($user->data->group != 'admin'){
            return false;
        }else{
            return true;
        }
    }

    // public function index(){
    //     $data['user'] = $this->user->data;

    //     $db = db_connect();
    //     $data['total_draft'] = $db->table("transaksi")->where("flag_validasi","0")->countAllResults();
    //     $data['total_pending'] = $db->table("transaksi")->where("flag_validasi","1")->countAllResults();
    //     $data['total_completed'] = $db->table("transaksi")->where("flag_validasi","2")->countAllResults();
    //     $data['total_canceled'] = $db->table("transaksi")->where("flag_validasi","3")->countAllResults();

    //     return view('admin/transaksi/index',$data);
    // }

    public function harian($tanggal = ""){
        $data['user'] = $this->user->data;

        if(empty($tanggal)){
            $tanggal = date("Y-m-d");
        }

        $db = db_connect();
        $data['trans_draft'] = $db->table("transaksi")->where("flag_validasi","0")->countAllResults();
        $data['trans_pending'] = $db->table("transaksi")->where("flag_validasi","1")->countAllResults();
        $data['trans_completed'] = $db->table("transaksi")->where("flag_validasi","2")->countAllResults();
        $data['trans_canceled'] = $db->table("transaksi")->where("flag_validasi","3")->countAllResults();
        $data['trans_total'] = $db->table("transaksi")->countAll();

        $data['jenis_pembayaran']['cash'] = 0;
        $data['jenis_pembayaran']['transfer'] = 0;

        $transaksimodel = new Transaksimodel();
        $transaksibuilder = $transaksimodel->builder("vtransaksi");
        $transaksibuilder->where("tanggal",$tanggal);
        $transaksibuilder->where("flag_validasi","2");
        $transaksibuilder->where("jenis_pembayaran","Cash");
        $transaksi = $transaksibuilder->selectSum("total_akhir")->get()->getRow();
        //die(var_dump($transaksibuilder->selectSum("total_akhir")->getCompiledSelect()));
        if($transaksi != null){
            $data['jenis_pembayaran']['cash'] = $transaksi->total_akhir;
        }
        $transaksibuilder->db()->close();

        $transaksimodel = new Transaksimodel();
        $transaksibuilder = $transaksimodel->builder("vtransaksi");
        $transaksibuilder->where("tanggal",$tanggal);
        $transaksibuilder->where("flag_validasi","2");
        $transaksibuilder->where("jenis_pembayaran","Transfer");
        $transaksi = $transaksibuilder->selectSum("total_akhir")->get()->getRow();
        if($transaksi != null){
            $data['jenis_pembayaran']['transfer'] = $transaksi->total_akhir;
        }
        $transaksibuilder->db()->close();

        $data['total_jenis_pembayaran'] = $data['jenis_pembayaran']['cash'] + $data['jenis_pembayaran']['transfer'];

        $gruptransaksimodel = new Gruptransaksimodel();
        $gruptransaksi = $gruptransaksimodel->findAll();
        $data['gruptransaksi'] = array();
        $data['gruptransaksi_total'] = 0;
        $i=0;
        foreach($gruptransaksi as $item){
            $data['gruptransaksi'][$i]['nama'] = $item['nama'];
            $data['gruptransaksi'][$i]['total'] = 0;

            $transaksimodel = new Transaksimodel();
            $transaksibuilder = $transaksimodel->builder("vtransaksi");
            $transaksibuilder->where("id_grup_transaksi",$item['id_grup_transaksi']);
            $transaksibuilder->where("tanggal",$tanggal);
            $transaksibuilder->where("flag_validasi","2");
            $transaksi = $transaksibuilder->selectSum("total_akhir")->get()->getRow();
            if ($transaksi!=null){
                $data['gruptransaksi'][$i]['total'] = $transaksi->total_akhir;
            }
            $data['gruptransaksi_total'] += $data['gruptransaksi'][$i]['total'];
        }

        $data['tanggal'] = $tanggal;
        return view('admin/laporan/harian',$data);
    }

    public function ajax_dt_trans_harian($tanggal=""){
        $data_post = [
            'draw' => $this->request->getPost('draw'),
            'columns' => $this->request->getPost('columns'),
            'order' => $this->request->getPost('order'),
            'start' => $this->request->getPost('start'),
            'length' => $this->request->getPost('length'),
            'search' => $this->request->getPost('search'),
            'searchBuilder' => $this->request->getPost('searchBuilder'),
        ];
        $DataModel = new Transaksimodel();
        $extra = "(tanggal='".$tanggal."')";
        return $DataModel->GetDT($data_post,$extra);
    }

    public function export_voucher_harian($tanggal){
        $data = array();
        $data['user'] = $this->user->data;
        $data["company_name"] = "PT Anugerah Cemara Abadi";
        $data['pembuat'] = $data['user']->nama;
        $data['tanggal'] = $tanggal;
        $data['tanggal_cetak'] = date("d M Y",strtotime($tanggal));

        $konfigmodel = new Konfigmodel();
        $konfig = $konfigmodel->first();
        if(!$konfig){
            die("Invalid konfig!");
        }

        $data['voucher_disetujui'] = $konfig["voucher_disetujui"];
        $data['voucher_diperiksa'] = $konfig["voucher_diperiksa"];

        $rekbankmodel = new Rekbankmodel();
        $data['rekbank'] = $rekbankmodel->where("aktif","1")->findAll();
        $data['no_voucher'] = "CEMARA / IN / ".$tanggal;

        $jenispembayaranmodel = new Jenispembayaranmodel();
        $jenispembayaran = $jenispembayaranmodel->findAll();

        $gruptransaksimodel = new Gruptransaksimodel();
        $gruptransaksi = $gruptransaksimodel->findAll();
        $data['grup'] = array();
        $data['total'] = 0;

        $i=0;
        foreach($gruptransaksi as $item){
            $data['grup'][$i]['nama'] = $item['nama'];
            $data['grup'][$i]['kantor']['data'] = array();
            $data['grup'][$i]['kolektor']['data'] = array();

            $data['grup'][$i]['kantor']['sub_total'] = 0;
            $j=0;
            foreach($jenispembayaran as $item2){
                $data['grup'][$i]['kantor']['data'][$j]['jenis'] = $item2["nama"];
                $data['grup'][$i]['kantor']['data'][$j]['nominal'] = 0;

                $transaksimodel = new Transaksimodel();
                $transaksibuilder = $transaksimodel->builder();
                $transaksibuilder->where("tanggal",$tanggal);
                $transaksibuilder->where("flag_validasi",'2');
                $transaksibuilder->where("id_jenis_pembayaran",$item2['id_jenis_pembayaran']);
                $transaksibuilder->where("(id_kolektor is null || id_kolektor=0)");
                $transaksi = $transaksibuilder->selectSum("total_akhir")->get()->getRow();
                if($transaksi){
                    $data['grup'][$i]['kantor']['data'][$j]['nominal'] = $transaksi->total_akhir;
                }
                $data['grup'][$i]['kantor']['sub_total'] += $data['grup'][$i]['kantor']['data'][$j]['nominal'];
                $j++;
            }

            $data['grup'][$i]['kolektor']['sub_total'] = 0;
            $j=0;
            foreach($jenispembayaran as $item2){
                $data['grup'][$i]['kolektor']['data'][$j]['jenis'] = $item2["nama"];
                $data['grup'][$i]['kolektor']['data'][$j]['nominal'] = 0;

                $transaksimodel = new Transaksimodel();
                $transaksibuilder = $transaksimodel->builder();
                $transaksibuilder->where("tanggal",$tanggal);
                $transaksibuilder->where("flag_validasi",'2');
                $transaksibuilder->where("id_jenis_pembayaran",$item2['id_jenis_pembayaran']);
                $transaksibuilder->where("(id_kolektor is not null and id_kolektor<>'0')");
                $transaksi = $transaksibuilder->selectSum("total_akhir")->get()->getRow();
                if($transaksi){
                    $data['grup'][$i]['kolektor']['data'][$j]['nominal'] = $transaksi->total_akhir;
                }
                $data['grup'][$i]['kolektor']['sub_total'] += $data['grup'][$i]['kolektor']['data'][$j]['nominal'];
                $j++;
            }

            $data['grup'][$i]['sub_total'] = $data['grup'][$i]['kantor']['sub_total'] + $data['grup'][$i]['kolektor']['sub_total'];

            $data['total'] += $data['grup'][$i]['sub_total'];
        }

        $html = view('print/voucher_penerimaan', $data);

        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        // Download file PDF atau tampilkan
        $dompdf->stream('voucher_penerimaan_harian_'.$tanggal.'.pdf', ['Attachment' => true]);
    }

    public function export_penerimaan_harian($tanggal){
        $data = array();
        $data['user'] = $this->user->data;
        $data["company_name"] = "PT Anugerah Cemara Abadi";
        $data['pembuat'] = $data['user']->nama;
        $data['tanggal'] = $tanggal;
        $data['tanggal_penerimaan'] = date("d M Y",strtotime($tanggal));
        $data['tanggal_cetak'] = date("d M Y");
        $data['no_laporan'] = "CEMARA / PENERIMAAN / ".$tanggal;

        $konfigmodel = new Konfigmodel();
        $konfig = $konfigmodel->first();
        if(!$konfig){
            die("Invalid konfig!");
        }

        $data['voucher_disetujui'] = $konfig["voucher_disetujui"];
        $data['voucher_diperiksa'] = $konfig["voucher_diperiksa"];

        $transaksimodel = new Transaksimodel();
        $transaksibuilder = $transaksimodel->builder("vstruk");
        $transaksibuilder->where("tanggal",$tanggal);
        $transaksibuilder->where("flag_validasi","2");
        $transaksibuilder->where("(id_kolektor is null or id_kolektor=0)");
        $transaksi = $transaksibuilder->get()->getResultArray();
        $data['transaksi']['kantor'] = array();
        $data['transaksi']['kantor_sub_total'] = 0;
        $i=0;
        foreach($transaksi as $item){
            $data['transaksi']['kantor'][$i]['grup'] = $item['singkatan'];
            $data['transaksi']['kantor'][$i]['no_kwitansi'] = $item['nomor'];
            $data['transaksi']['kantor'][$i]['kode_kk'] = $item['kode_kk'];
            $data['transaksi']['kantor'][$i]['nama_pemilik'] = $item['nama_pemilik'];
            $data['transaksi']['kantor'][$i]['alamat'] = $item['nama_jalan'].', '.$item['nama_blok'].', No.'.$item['nomor_rumah'];
            $data['transaksi']['kantor'][$i]['jenis_pembayaran'] = $item['jenis_pembayaran'];
            $data['transaksi']['kantor'][$i]['nama_operator'] = $item['nama_operator'];
            $data['transaksi']['kantor'][$i]['nominal'] = $item['total'];
            $data['transaksi']['kantor'][$i]['diskon'] = $item['total_diskon'];
            $data['transaksi']['kantor'][$i]['subtotal'] = $item['total_akhir'];
            $data['transaksi']['kantor_sub_total'] += $item['total_akhir'];
            $i++;
        }

        $transaksimodel = new Transaksimodel();
        $transaksibuilder = $transaksimodel->builder("vstruk");
        $transaksibuilder->where("tanggal",$tanggal);
        $transaksibuilder->where("flag_validasi","2");
        $transaksibuilder->where("(id_kolektor is not null and id_kolektor<>0)");
        $transaksi = $transaksibuilder->get()->getResultArray();
        $data['transaksi']['kolektor'] = array();
        $data['transaksi']['kolektor_sub_total'] = 0;
        $i=0;
        foreach($transaksi as $item){
            $data['transaksi']['kolektor'][$i]['grup'] = $item['singkatan'];
            $data['transaksi']['kolektor'][$i]['no_kwitansi'] = $item['nomor'];
            $data['transaksi']['kolektor'][$i]['kode_kk'] = $item['kode_kk'];
            $data['transaksi']['kolektor'][$i]['nama_pemilik'] = $item['nama_pemilik'];
            $data['transaksi']['kolektor'][$i]['alamat'] = $item['nama_jalan'].', '.$item['nama_blok'].', No.'.$item['nomor_rumah'];
            $data['transaksi']['kolektor'][$i]['jenis_pembayaran'] = $item['jenis_pembayaran'];
            $data['transaksi']['kolektor'][$i]['nama_kolektor'] = $item['nama_kolektor'];
            $data['transaksi']['kolektor'][$i]['nominal'] = $item['total'];
            $data['transaksi']['kolektor'][$i]['diskon'] = $item['total_diskon'];
            $data['transaksi']['kolektor'][$i]['subtotal'] = $item['total_akhir'];
            $data['transaksi']['kolektor_sub_total'] += $item['total_akhir'];
            $i++;
        }

        $html = view('print/penerimaan_harian', $data);

        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        // Download file PDF atau tampilkan
        $dompdf->stream('penerimaan_harian_'.$tanggal.'.pdf', ['Attachment' => true]);
    }

    public function export_bukti_harian($tanggal){
        $data = array();
        $data["company_name"] = "PT Anugerah Cemara Abadi";
        $data["tanggal"] = $tanggal;
        $data["tanggal_cetak"] = date("d M Y",strtotime($tanggal));
        $data['bukti'] = array();

        $buktimodel = new Buktibayarmodel();
        $buktibuilder = $buktimodel->builder("vbuktibayar");
        $buktibuilder->where("tanggal",$tanggal);
        $buktibuilder->where("flag_validasi","2");
        $bukti = $buktibuilder->get()->getResultObject();
        if($bukti == null){
            die("Bukti Not Available!");
        }

        $i=0;
        foreach($bukti as $item){
            $data['bukti'][$i]["nomor"] = $item->kode;
            $data['bukti'][$i]["tanggal"] = (empty($item->tanggal_pembayaran) ? $item->tanggal : $item->tanggal_pembayaran);
            $data['bukti'][$i]["fnama"] = $item->fnama;

            $lokalPath = FCPATH . 'bukti_bayar/' . $item->fnama;
            $type = pathinfo($lokalPath, PATHINFO_EXTENSION);
            $isi_gambar = file_get_contents($lokalPath);
            $base64 = 'data:image/' . $type . ';base64,' . base64_encode($isi_gambar);

            $data['bukti'][$i]["gambar"] = $base64;
            $i++;
        }

        $html = view('print/bukti_bayar_harian', $data);

        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        // Download file PDF atau tampilkan
        $dompdf->stream('bukti_pembayaran_harian'.$tanggal.'.pdf', ['Attachment' => true]);
        //return view('print/bukti_bayar', $data);
    }
}
?>