<?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\Jeniskkmodel;
use App\Models\Kkmodel;

use Dompdf\Dompdf;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\Writer\ValidationException;

class Kk 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/kk/index',$data);
    }

    public function ajax_dt(){
        $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 Kkmodel();
        return $DataModel->GetDT($data_post);
    }

    public function add() {
        $data['user'] = $this->user->data;
        
        // $jkk_model = new Jeniskkmodel();

        // $data['jenis_kk'] = $jkk_model->findAll();

        return view('admin/kk/add',$data);
    }

    public function add_save()
    {
        $data = array();
        $data['status'] = 'success';

        $request = [
            'kode' => $this->request->getPost('kode',FILTER_SANITIZE_ADD_SLASHES),
            'id_jenis_kk' => $this->request->getPost('id_jenis_kk',FILTER_SANITIZE_ADD_SLASHES),
            'nama_pemilik' => $this->request->getPost('nama_pemilik',FILTER_SANITIZE_ADD_SLASHES),
            'jalan' => $this->request->getPost('jalan',FILTER_SANITIZE_ADD_SLASHES),
            'blok' => $this->request->getPost('blok',FILTER_SANITIZE_ADD_SLASHES),
            // 'id_blok' => $this->request->getPost('id_blok',FILTER_SANITIZE_ADD_SLASHES),
            'nomor_rumah' => $this->request->getPost('nomor_rumah',FILTER_SANITIZE_ADD_SLASHES),
            'area' => $this->request->getPost('area',FILTER_SANITIZE_ADD_SLASHES),
            'keterangan' => $this->request->getPost('keterangan',FILTER_SANITIZE_ADD_SLASHES),
            'created_by' => $this->user->data->id_auth,
            'updated_by' => $this->user->data->id_auth
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('kode', 'Jenis KK', 'is_unique[kk.kode]');
        $validation->setRule('id_jenis_kk', 'Jenis KK', 'required');
        $validation->setRule('nama_pemilik', 'Nama Pemilik', 'required');
        $validation->setRule('jalan', 'Jalan', 'required');
        $validation->setRule('blok', 'Blok', 'required');
        // $validation->setRule('id_blok', 'Blok', 'required');
        $validation->setRule('nomor_rumah', 'Nomor Rumah', 'required');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            //die(var_dump($request));
            $tmodel = new Kkmodel();
            if ($tmodel->insert($request, false))
            {
                $id = $tmodel->getInsertID();
                if(empty($request['kode'])){
                    $kode_kk = "CMRKK".str_pad($id,5,"0",STR_PAD_LEFT);
                    $update = [
                        "kode" => $kode_kk
                    ];
                    $tmodel->update($id,$update);
                }
                
                return $this->respond($data,200);
            }else{
                return $this->fail($tmodel->errors(),400,null,'db');
            }
        }
    }

    public function view($id) {
        $data['user'] = $this->user->data;
        $tmodel = new Kkmodel();
        // $jkk_model = new Jeniskkmodel();

        // $data['jenis_kk'] = $jkk_model->findAll();

        $builder = $tmodel->builder("vkk");
        $data['data'] = $builder->where("id_kk",$id)->get()->getRow();

        $writer = new PngWriter();
        $qrCode = new QrCode(
            data: base_url().'warga/'.$data['data']->kode,
            encoding: new Encoding('UTF-8'),
            errorCorrectionLevel: ErrorCorrectionLevel::Low,
            size: 300,
            margin: 10,
            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['qr'] = $imgSrc;
        
        return view('admin/kk/view',$data);
    }

    public function update()
    {
        $data = array();
        $data['status'] = 'success';

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        $request = [
            'kode' => $this->request->getPost('kode',FILTER_SANITIZE_ADD_SLASHES),
            'id_jenis_kk' => $this->request->getPost('id_jenis_kk',FILTER_SANITIZE_ADD_SLASHES),
            'nama_pemilik' => $this->request->getPost('nama_pemilik',FILTER_SANITIZE_ADD_SLASHES),
            'jalan' => $this->request->getPost('jalan',FILTER_SANITIZE_ADD_SLASHES),
            'blok' => $this->request->getPost('blok',FILTER_SANITIZE_ADD_SLASHES),
            // 'id_blok' => $this->request->getPost('id_blok',FILTER_SANITIZE_ADD_SLASHES),
            'nomor_rumah' => $this->request->getPost('nomor_rumah',FILTER_SANITIZE_ADD_SLASHES),
            'area' => $this->request->getPost('area',FILTER_SANITIZE_ADD_SLASHES),
            'keterangan' => $this->request->getPost('keterangan',FILTER_SANITIZE_ADD_SLASHES),
            'updated_by' => $this->user->data->id_auth
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('kode', 'Jenis KK', 'required|is_unique[kk.kode,kk.id_kk,'.$id.']');
        $validation->setRule('id_jenis_kk', 'Jenis KK', 'required');
        $validation->setRule('nama_pemilik', 'Nama Pemilik', 'required');
        $validation->setRule('jalan', 'Jalan', 'required');
        $validation->setRule('blok', 'Blok', 'required');
        // $validation->setRule('id_blok', 'Blok', 'required');
        $validation->setRule('nomor_rumah', 'Nomor Rumah', 'required');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            $tmodel = new Kkmodel();
            if ($tmodel->update($id,$request))
            {
                return $this->respond($data,200);
            }else{
                return $this->fail(["error" => "Database Error!"],400,null,'db');
            }
        }
    }

    public function delete()
    {
        $data = array();
        $data['status'] = 'success';

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);

        $tmodel = new Kkmodel();
        if ($tmodel->delete($id))
        {
            return $this->respond($data,200);
        }else{
            return $this->fail(["error" => "Database Error!"],400,null,'db');
        }
    }

    public function count_warga() {
        $db = db_connect();
        $total = $db->table("kk")->countAll();
        return $this->response->setJSON([
            'success' => true,
            'total' => $total
        ]);
    }

    public function cetak_kartu($id) {
        $data['user'] = $this->user->data;
        $kkm = new Kkmodel();
        
        $builder = $kkm->builder("vkk");
        $data_kk = $builder->where("id_kk",$id)->get()->getRow();
        
        if($data_kk == null){
            die("-");
        }
        
        // ===== Data Transaksi ===== //
        $qr_text = base_url().'warga/'.$data_kk->kode;

        // ===== Buat QR Code ===== //
        $writer = new PngWriter();
        $qrCode = new QrCode(
            data: $qr_text,
            encoding: new Encoding('UTF-8'),
            errorCorrectionLevel: ErrorCorrectionLevel::Low,
            size: 300,
            margin: 10,
            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;

        // ===== HTML STRUK (Thermal 58mm Style) ===== //
        $html = '
        <html>
        <head>
        <style>
            @page { size: 58mm auto; margin: 0; }
            body { font-family: monospace; font-size: 10px; margin: 10px; padding:5px; border:1px solid; }
            .center { text-align: center; }
            .bold { font-weight: bold; }
            table { width: 100%; border-collapse: collapse; }
            td { padding: 2px 0; }
            .qr { margin-top: 5px; }
        </style>
        </head>
        <body>
        <div class="center bold">KARTU PEMBAYARAN</div>
        <div class="center">Pengelola Perumahan Cemara Asri</div>
        <hr>
        <table>
            <tr><td>Kode</td><td>:</td><td>'.$data_kk->kode.'</td></tr>
            <tr><td>Nama Pemilik</td><td>:</td><td>'.$data_kk->nama_pemilik.'</td></tr>
        </table>
        <div class="center qr">
            <img src="' . $imgSrc . '" width="180">
            <div>Scan untuk akses layanan online.</div>
        </div>
        </body>
        </html>
        ';

        // ===== Generate PDF ===== //
        //die(var_dump($html));

        while (ob_get_level()) {
            ob_end_clean();
        }
        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper([0, 0, 164, 250], 'portrait'); // 58mm = ~164pt
        $dompdf->render();
        $dompdf->stream("kartu_warga_".$data_kk->kode.".pdf", ["Attachment" => false]);

        // Optional: hapus QR sementara
        //unlink($qrPath);
    }
}
?>