<?php namespace App\Controllers;
use App\Models\PrestasiModel;

class Madrasah extends BaseController {
    
    protected $prestasiModel;

    public function __construct() {
        $this->prestasiModel = new PrestasiModel();
    }

    public function dashboard() {
        $data['riwayat'] = $this->prestasiModel
                            ->where('id_madrasah', session()->get('user_id'))
                            ->orderBy('created_at', 'DESC')
                            ->findAll();
        return view('madrasah/dashboard', $data);
    }

    public function upload_prestasi() {
        // Validasi input dan ekstensi file anti-shell
        $rules = [
            'nama_siswa'    => 'required|min_length[3]',
            'nisn'          => 'required|numeric|exact_length[10]',
            'nama_prestasi' => 'required',
            'sertifikat'    => 'uploaded[sertifikat]|max_size[sertifikat,2048]|ext_in[sertifikat,pdf,jpg,png]'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->with('error', 'Gagal: Cek kembali format form atau pastikan file PDF/JPG max 2MB.');
        }

        // Proses enkripsi nama file dan pemindahan ke direktori
        $file = $this->request->getFile('sertifikat');
        $namaBerkasBaru = $file->getRandomName();
        $file->move('uploads/sertifikat/', $namaBerkasBaru);

        // Filter XSS sebelum masuk database
        $this->prestasiModel->save([
            'id_madrasah'       => session()->get('user_id'),
            'nama_siswa'        => esc($this->request->getPost('nama_siswa')),
            'nisn'              => esc($this->request->getPost('nisn')),
            'nama_prestasi'     => esc($this->request->getPost('nama_prestasi')),
            'tingkat'           => esc($this->request->getPost('tingkat')),
            'file_sertifikat'   => $namaBerkasBaru,
            'status_verifikasi' => 'pending'
        ]);

        return redirect()->to('/madrasah/dashboard')->with('success', 'Data siswa berhasil dikirim. Menunggu verifikasi kantor.');
    }
}