<?php

namespace App\Controllers\PPDB;

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

class Result extends BaseController
{
    public function index()
    {
        return view('ppdb/public/result');
    }

    public function check()
    {
        $regNo = $this->request->getPost('reg_no');
        $nisn  = $this->request->getPost('nisn');

        if (!$regNo || !$nisn) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Data tidak lengkap'
            ]);
        }

        $model = new PpdbModel();
        $row = $model
            ->where('reg_no', $regNo)
            ->where('nisn', $nisn)
            ->first();

        if (!$row) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Data tidak ditemukan'
            ]);
        }

        return $this->response->setJSON([
            'status' => 'ok',
            'data' => [
                'name'   => $row['name'],
                'nisn'   => $row['nisn'],
                'reg_no' => $row['reg_no'],
                'status' => $row['status'],
                'token'  => $row['announcement_token'] ?? null
            ]
        ]);
    }

    // PDF Surat Kelulusan (aman pakai token)
    public function letter($token)
    {
        $model = new PpdbModel();
        $row = $model->where('announcement_token', $token)->first();

        if (!$row || $row['status'] !== 'APPROVED') {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        return view('ppdb/public/letter', [
            'row' => $row
        ]);
    }
}
