<?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 Dompdf\Options;
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 Exportlaporan 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;

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

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

        return view('admin/export/export_penerimaan',$data);
    }

    public function export_penerimaan_proses(){
        $data = array();
        $data['user'] = $this->user->data;
        $data["company_name"] = "PT Anugerah Cemara Abadi";
        $data['pembuat'] = $data['user']->nama;

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

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

        $startdate = $this->request->getPost('start_date');
        $enddate   = $this->request->getPost('end_date');

        // Cek jika kedua tanggal valid
        if (!$startdate || !$enddate) {
            die("Tanggal tidak lengkap!");
        }

        $current = strtotime($startdate);
        $end = strtotime($enddate);

        if ($current > $end) {
            die("Tanggal mulai harus lebih kecil atau sama dengan tanggal akhir.");
        }

        $data['harian'] = [];
        $indeks1 = 0;
        while ($current <= $end) {
            $tanggal = date("Y-m-d", $current);

            $data['harian'][$indeks1]['tanggal'] = $tanggal;
            $data['harian'][$indeks1]['tanggal_penerimaan'] = date("d M Y",strtotime($tanggal));
            $data['harian'][$indeks1]['tanggal_cetak'] = date("d M Y");
            $data['harian'][$indeks1]['no_laporan'] = "CEMARA / PENERIMAAN / ".$tanggal;

            $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['harian'][$indeks1]['transaksi']['kantor'] = array();
            $data['harian'][$indeks1]['transaksi']['kantor_sub_total'] = 0;

            $i=0;
            foreach($transaksi as $item){
                $data['harian'][$indeks1]['transaksi']['kantor'][$i]['grup'] = $item['singkatan'];
                $data['harian'][$indeks1]['transaksi']['kantor'][$i]['no_kwitansi'] = $item['nomor'];
                $data['harian'][$indeks1]['transaksi']['kantor'][$i]['kode_kk'] = $item['kode_kk'];
                $data['harian'][$indeks1]['transaksi']['kantor'][$i]['nama_pemilik'] = $item['nama_pemilik'];
                $data['harian'][$indeks1]['transaksi']['kantor'][$i]['alamat'] = $item['jalan'].', '.$item['blok'].', No.'.$item['nomor_rumah'];
                $data['harian'][$indeks1]['transaksi']['kantor'][$i]['jenis_pembayaran'] = $item['jenis_pembayaran'];
                $data['harian'][$indeks1]['transaksi']['kantor'][$i]['nama_operator'] = $item['nama_operator'];
                $data['harian'][$indeks1]['transaksi']['kantor'][$i]['nominal'] = $item['total'];
                $data['harian'][$indeks1]['transaksi']['kantor'][$i]['diskon'] = $item['total_diskon'];
                $data['harian'][$indeks1]['transaksi']['kantor'][$i]['subtotal'] = $item['total_akhir'];
                $data['harian'][$indeks1]['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['harian'][$indeks1]['transaksi']['kolektor'] = array();
            $data['harian'][$indeks1]['transaksi']['kolektor_sub_total'] = 0;
            $i=0;
            foreach($transaksi as $item){
                $data['harian'][$indeks1]['transaksi']['kolektor'][$i]['grup'] = $item['singkatan'];
                $data['harian'][$indeks1]['transaksi']['kolektor'][$i]['no_kwitansi'] = $item['nomor'];
                $data['harian'][$indeks1]['transaksi']['kolektor'][$i]['kode_kk'] = $item['kode_kk'];
                $data['harian'][$indeks1]['transaksi']['kolektor'][$i]['nama_pemilik'] = $item['nama_pemilik'];
                $data['harian'][$indeks1]['transaksi']['kolektor'][$i]['alamat'] = $item['jalan'].', '.$item['blok'].', No.'.$item['nomor_rumah'];
                $data['harian'][$indeks1]['transaksi']['kolektor'][$i]['jenis_pembayaran'] = $item['jenis_pembayaran'];
                $data['harian'][$indeks1]['transaksi']['kolektor'][$i]['nama_kolektor'] = $item['nama_kolektor'];
                $data['harian'][$indeks1]['transaksi']['kolektor'][$i]['nominal'] = $item['total'];
                $data['harian'][$indeks1]['transaksi']['kolektor'][$i]['diskon'] = $item['total_diskon'];
                $data['harian'][$indeks1]['transaksi']['kolektor'][$i]['subtotal'] = $item['total_akhir'];
                $data['harian'][$indeks1]['transaksi']['kolektor_sub_total'] += $item['total_akhir'];
                $i++;
            }

            $indeks1++;
            $current = strtotime("+1 day", $current);
        }

        $html = view('print/export/penerimaan_harian', $data);
        while (ob_get_level()) {
            ob_end_clean();
        }
        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

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

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

        return view('admin/export/export_voucher_penerimaan',$data);
    }

    public function export_voucher_penerimaan_proses(){
        $data = array();
        $data['user'] = $this->user->data;
        $data["company_name"] = "PT Anugerah Cemara Abadi";
        $data['pembuat'] = $data['user']->nama;

        $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();
    
        $jenispembayaranmodel = new Jenispembayaranmodel();
        $jenispembayaran = $jenispembayaranmodel->findAll();

        $gruptransaksimodel = new Gruptransaksimodel();
        $gruptransaksi = $gruptransaksimodel->findAll();

        $startdate = $this->request->getPost('start_date');
        $enddate   = $this->request->getPost('end_date');

        // Cek jika kedua tanggal valid
        if (!$startdate || !$enddate) {
            die("Tanggal tidak lengkap!");
        }

        $current = strtotime($startdate);
        $end = strtotime($enddate);

        if ($current > $end) {
            die("Tanggal mulai harus lebih kecil atau sama dengan tanggal akhir.");
        }

        $data['harian'] = [];
        $indeks1 = 0;
        while ($current <= $end) {
            $tanggal = date("Y-m-d", $current);
            $data['harian'][$indeks1]['tanggal'] = $tanggal;
            $data['harian'][$indeks1]['tanggal_cetak'] = date("d M Y",strtotime($tanggal));
            $data['harian'][$indeks1]['no_voucher'] = "CEMARA / IN / ".$tanggal;

            $data['harian'][$indeks1]['grup'] = array();
            $data['harian'][$indeks1]['total'] = 0;

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

                $data['harian'][$indeks1]['grup'][$i]['kantor']['sub_total'] = 0;
                $j=0;
                foreach($jenispembayaran as $item2){
                    $data['harian'][$indeks1]['grup'][$i]['kantor']['data'][$j]['jenis'] = $item2["nama"];
                    $data['harian'][$indeks1]['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['harian'][$indeks1]['grup'][$i]['kantor']['data'][$j]['nominal'] = $transaksi->total_akhir;
                    }
                    $data['harian'][$indeks1]['grup'][$i]['kantor']['sub_total'] += $data['harian'][$indeks1]['grup'][$i]['kantor']['data'][$j]['nominal'];
                    $j++;
                }

                $data['harian'][$indeks1]['grup'][$i]['kolektor']['sub_total'] = 0;
                $j=0;
                foreach($jenispembayaran as $item2){
                    $data['harian'][$indeks1]['grup'][$i]['kolektor']['data'][$j]['jenis'] = $item2["nama"];
                    $data['harian'][$indeks1]['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['harian'][$indeks1]['grup'][$i]['kolektor']['data'][$j]['nominal'] = $transaksi->total_akhir;
                    }
                    $data['harian'][$indeks1]['grup'][$i]['kolektor']['sub_total'] += $data['harian'][$indeks1]['grup'][$i]['kolektor']['data'][$j]['nominal'];
                    $j++;
                }

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

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

            $indeks1++;
            $current = strtotime("+1 day", $current);
        }

        $html = view('print/export/voucher_penerimaan', $data);
        while (ob_get_level()) {
            ob_end_clean();
        }
        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        // Download file PDF atau tampilkan
        $dompdf->stream('voucher_penerimaan_harian_'.$startdate.'_'.$enddate.'.pdf', ['Attachment' => true]);
    }
    
    public function export_kwitansi(){
        $data['user'] = $this->user->data;

        return view('admin/export/export_kwitansi',$data);
    }

    public function export_kwitansi_proses(){
        $user = $this->user->data;
        $data = array();
        $data["company_name"] = COMPANY_NAME;
        $data["company_logo"] = base_url("img/logo_company.png");
        $data['struks'] = array();
        
        $id_kk = $this->request->getPost('id_kk');
        $startdate = $this->request->getPost('start_date');
        $enddate   = $this->request->getPost('end_date');
        $jenis   = $this->request->getPost('jenis_kwitansi');

        // Cek jika kedua tanggal valid
        if (!$startdate || !$enddate) {
            die("Tanggal tidak lengkap!");
        }

        $current = strtotime($startdate);
        $end = strtotime($enddate);

        if ($current > $end) {
            die("Tanggal mulai harus lebih kecil atau sama dengan tanggal akhir.");
        }

        $strukmodel = new Strukmodel();
        $strukbuilder = $strukmodel->builder("vstruk");
        if(!empty($id_kk)){
            $strukbuilder->where("id_kk",$id_kk);
        }
        $strukbuilder->where("tanggal between '".$startdate."' and '".$enddate."'");
        if($jenis == '1'){
            $strukbuilder->where("((id_kolektor is null) or (id_kolektor='0'))");
        }elseif($jenis == '2'){
            $strukbuilder->where("((id_kolektor is not null) and (id_kolektor>0))");
        }
        $strukbuilder->where("flag_validasi","2");
        $struk = $strukbuilder->get()->getResultObject();
        if($struk == null){
            die("Struk Not Available!");
        }

        $i=0;
        foreach($struk as $item){
            $data['struks'][$i]["tanggal"] = $item->tanggal;
            $data['struks'][$i]["nomor_transaksi"] = $item->kode_transaksi;
            $data['struks'][$i]["nomor_struk"] = $item->nomor;
            $data['struks'][$i]['kode_rumah'] = $item->kode_kk;
            $data['struks'][$i]['nama_pemilik'] = $item->nama_pemilik;
            $data['struks'][$i]['alamat'] = $item->jalan.', '.$item->blok.', No. '.$item->nomor_rumah;
            $data['struks'][$i]['nominal'] = $item->total_akhir;
            $data['struks'][$i]['operator'] = empty($item->nama_operator) ? $user->nama : $item->nama_operator;
            $data['struks'][$i]['kolektor'] = $item->nama_kolektor;
            $data['struks'][$i]['jenis_pembayaran'] = $item->jenis_pembayaran;
            $data['struks'][$i]['tanggal_pembayaran'] = $item->tanggal_pembayaran;
            $data['struks'][$i]['receiver'] = $item->pembayar;
            $data['struks'][$i]['no_telp'] = $item->no_telp;

             // ===== Data Transaksi ===== //
            $qr_text = base_url().'vwarga/struk/'.$item->id_struk;

            // ===== Buat QR Code ===== //
            $writer = new PngWriter();
            $qrCode = new QrCode(
                data: $qr_text,
                encoding: new Encoding('UTF-8'),
                errorCorrectionLevel: ErrorCorrectionLevel::Low,
                size: 100,
                margin: 0,
                roundBlockSizeMode: RoundBlockSizeMode::Margin,
                foregroundColor: new Color(0, 0, 0),
                backgroundColor: new Color(255, 255, 255)
            );

            $result = $writer->write($qrCode);

            ob_start();
            $result->saveToFile('php://output');
            $imageData = ob_get_clean();
            $base64 = base64_encode($imageData);
            $imgSrc = 'data:image/png;base64,' . $base64;
            
            $data['struks'][$i]['qr_code'] = $imgSrc;

            $periode = array();
            $invoice = array();

            $strukdetailmodel = new Strukdetailmodel();
            $strukdetailbuilder = $strukdetailmodel->builder("vstrukdetail");
            $strukdetail = $strukdetailbuilder->where("id_struk",$item->id_struk)->get()->getResultArray();
            foreach($strukdetail as $item){
                $periode[] = $item['bulan'].'-'.$item['tahun'];
                $invoice[] = $item["nomor_invoice"];
            }
            $data['struks'][$i]["periode"] = implode(", ",$periode);
            $data['struks'][$i]["nomor_invoice"] = implode(", ",$invoice);

            $i++;
        }

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

        while (ob_get_level()) {
            ob_end_clean();
        }

        $options = new Options();
        $options->set('isRemoteEnabled', true);
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper([0, 0, 93.2, 241.3], 'portrait'); // 1/3 folio
        $dompdf->render();
        if($jenis=='0'){
            $dompdf->stream('struk_pembayaran_all.pdf', ['Attachment' => true]);
        }elseif($jenis=='1'){
            $dompdf->stream('struk_pembayaran_kantor.pdf', ['Attachment' => true]);
        }elseif($jenis=='2'){
            $dompdf->stream('struk_pembayaran_kolektor.pdf', ['Attachment' => true]);
        }
    }

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

        return view('admin/export/export_kwitansi_rekap',$data);
    }

    public function export_kwitansi_rekap_proses(){
        $user = $this->user->data;
        $data = array();
        $data["company_name"] = COMPANY_NAME;
        $data["company_logo"] = base_url("img/logo_company.png");
        $data['struks'] = array();
        
        $id_kk = $this->request->getPost('id_kk');
        $startdate = $this->request->getPost('start_date');
        $enddate   = $this->request->getPost('end_date');
        $jenis   = $this->request->getPost('jenis_kwitansi');

        // Cek jika kedua tanggal valid
        if (!$startdate || !$enddate) {
            die("Tanggal tidak lengkap!");
        }

        $current = strtotime($startdate);
        $end = strtotime($enddate);

        if ($current > $end) {
            die("Tanggal mulai harus lebih kecil atau sama dengan tanggal akhir.");
        }

        $strukmodel = new Strukmodel();
        $strukbuilder = $strukmodel->builder("vstruk");
        if(!empty($id_kk)){
            $strukbuilder->where("id_kk",$id_kk);
        }
        $strukbuilder->where("tanggal between '".$startdate."' and '".$enddate."'");
        if($jenis == '1'){
            $strukbuilder->where("((id_kolektor is null) or (id_kolektor='0'))");
        }elseif($jenis == '2'){
            $strukbuilder->where("((id_kolektor is not null) and (id_kolektor>0))");
        }
        $strukbuilder->where("flag_validasi","2");
        $struk = $strukbuilder->get()->getResultObject();
        if($struk == null){
            die("Struk Not Available!");
        }

        $i=0;
        foreach($struk as $item){
            $data['struks'][$i]["tanggal"] = $item->tanggal;
            $data['struks'][$i]["nomor_transaksi"] = $item->kode_transaksi;
            $data['struks'][$i]["nomor_struk"] = $item->nomor;
            $data['struks'][$i]['kode_rumah'] = $item->kode_kk;
            $data['struks'][$i]['nama_pemilik'] = $item->nama_pemilik;
            $data['struks'][$i]['alamat'] = $item->jalan.', '.$item->blok.', No. '.$item->nomor_rumah;
            $data['struks'][$i]['nominal'] = $item->total_akhir;
            $data['struks'][$i]['operator'] = empty($item->nama_operator) ? $user->nama : $item->nama_operator;
            $data['struks'][$i]['kolektor'] = $item->nama_kolektor;
            $data['struks'][$i]['jenis_pembayaran'] = $item->jenis_pembayaran;
            $data['struks'][$i]['tanggal_pembayaran'] = $item->tanggal_pembayaran;
            $data['struks'][$i]['receiver'] = $item->pembayar;
            $data['struks'][$i]['no_telp'] = $item->no_telp;

             // ===== Data Transaksi ===== //
            $qr_text = base_url().'vwarga/struk/'.$item->id_struk;

            // ===== Buat QR Code ===== //
            $writer = new PngWriter();
            $qrCode = new QrCode(
                data: $qr_text,
                encoding: new Encoding('UTF-8'),
                errorCorrectionLevel: ErrorCorrectionLevel::Low,
                size: 100,
                margin: 0,
                roundBlockSizeMode: RoundBlockSizeMode::Margin,
                foregroundColor: new Color(0, 0, 0),
                backgroundColor: new Color(255, 255, 255)
            );

            $result = $writer->write($qrCode);

            ob_start();
            $result->saveToFile('php://output');
            $imageData = ob_get_clean();
            $base64 = base64_encode($imageData);
            $imgSrc = 'data:image/png;base64,' . $base64;
            
            $data['struks'][$i]['qr_code'] = $imgSrc;

            $periode = array();
            $invoice = array();

            $strukdetailmodel = new Strukdetailmodel();
            $strukdetailbuilder = $strukdetailmodel->builder("vstrukdetail");
            $strukdetail = $strukdetailbuilder->where("id_struk",$item->id_struk)->get()->getResultArray();
            foreach($strukdetail as $item){
                $periode[] = $item['bulan'].'-'.$item['tahun'];
                $invoice[] = $item["nomor_invoice"];
            }
            $data['struks'][$i]["periode"] = implode(", ",$periode);
            $data['struks'][$i]["nomor_invoice"] = implode(", ",$invoice);

            $i++;
        }

        $html = view('print/export/multiple_struk_rekap', $data);
        //return $html;

        while (ob_get_level()) {
            ob_end_clean();
        }

        $options = new Options();
        $options->set('isRemoteEnabled', true);
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper([0, 0, 612, 312], 'portrait'); // 1/3 folio
        $dompdf->render();
        if($jenis=='0'){
            $dompdf->stream('struk_pembayaran_all.pdf', ['Attachment' => true]);
        }elseif($jenis=='1'){
            $dompdf->stream('struk_pembayaran_kantor.pdf', ['Attachment' => true]);
        }elseif($jenis=='2'){
            $dompdf->stream('struk_pembayaran_kolektor.pdf', ['Attachment' => true]);
        }
    }
}
?>