<?php

namespace App\Controllers\PPDB;

use App\Controllers\BaseController;
use App\Models\PpdbModel;
use App\Models\DaftarUlangModel;
use Dompdf\Dompdf;

class DaftarUlang extends BaseController
{
    protected $table = 'ppdb_daftar_ulang'; // 🔥 INI WAJIB BENAR
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'ppdb_id',
        'tanggal_daftar',
        'keterangan',
        'created_at'
    ];

    protected $useTimestamps = true;
    protected $createdField = 'created_at';


    public function index()
    {
        return view('ppdb/daftarulang/index');
    }

    public function data()
    {
        $ppdb = new PpdbModel();

        $rows = $ppdb
            ->select('ppdb_registrations.*, du.id AS daftar_ulang_id, du.tanggal_daftar')
            ->join('ppdb_daftar_ulang du', 'du.ppdb_id = ppdb_registrations.id', 'left')
            ->where('ppdb_registrations.status', 'APPROVED')
            ->findAll();

        return $this->response->setJSON(['data' => $rows]);
    }

    public function save()
    {
        $model = new DaftarUlangModel();

        $exists = $model
            ->where('ppdb_id', $this->request->getPost('ppdb_id'))
            ->first();

        if ($exists) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'Siswa sudah daftar ulang'
            ]);
        }

        $model->insert([
            'ppdb_id' => $this->request->getPost('ppdb_id'),
            'tanggal_daftar' => date('Y-m-d'),
            'keterangan' => $this->request->getPost('keterangan'),
        ]);

        return $this->response->setJSON([
            'status' => true,
            'message' => 'Daftar ulang berhasil'
        ]);
    }

    // ================= CETAK PDF =================
    public function print($id)
    {
        $model = new DaftarUlangModel();

        $data = $model
            ->select('ppdb_daftar_ulang.*, ppdb_registrations.*')
            ->join(
                'ppdb_registrations',
                'ppdb_registrations.id = ppdb_daftar_ulang.ppdb_id'
            )
            ->where('ppdb_daftar_ulang.ppdb_id', $id)
            ->first();

        if (!$data) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $nomorSurat = 'DU/PPDB/' . date('Y') . '/' . str_pad($data['id'], 4, '0', STR_PAD_LEFT);

        $dompdf = new \Dompdf\Dompdf();
        $dompdf->loadHtml(view('ppdb/daftarulang/print', [
            'data' => $data,
            'nomorSurat' => $nomorSurat
        ]));
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        $dompdf->stream('Bukti-Daftar-Ulang.pdf', ['Attachment' => false]);
    }
}
