<?php

namespace App\Controllers;

use App\Models\ModelKelas;
use App\Models\ModelPenghargaan;
use App\Models\ModelRekapPenghargaan;
use App\Models\ModelSiswa;
use App\Models\ModelGuru;

class InputPenghargaan extends BaseController
{
    protected $kelasModel;
    protected $penghargaanModel;
    protected $rekapModel;
    protected $siswaModel;
    protected $guruModel;

    public function __construct()
    {
        $this->kelasModel        = new ModelKelas();
        $this->penghargaanModel  = new ModelPenghargaan();
        $this->rekapModel        = new ModelRekapPenghargaan();
        $this->siswaModel        = new ModelSiswa();
        $this->guruModel         = new ModelGuru();
    }

    /**
     * Halaman Input Penghargaan
     */
    public function index()
    {
        // Cek Token
        if (!session()->get('akses_input')) {
            return redirect()->to('/token?menu=penghargaan');
        }

        $data = [
            'kelas'        => $this->kelasModel->findAll(),
            'guru'         => $this->guruModel->orderBy('nama', 'ASC')->findAll(),
            'penghargaan'  => $this->penghargaanModel->orderBy('nama_penghargaan', 'ASC')->findAll()
        ];

        return view('InputPenghargaan', $data);
    }



    public function simpan()
    {
        if (!session()->get('akses_input')) {
            return redirect()->to('/token?menu=penghargaan');
        }

        $this->rekapModel->insert([
            'id_siswa'            => $this->request->getPost('id_siswa'),
            'id_penghargaan'      => $this->request->getPost('id_penghargaan'),
            'id_guru'             => $this->request->getPost('id_guru'),
            'tanggal'             => date('Y-m-d H:i:s'),
            'keterangan_tambahan' => $this->request->getPost('keterangan_tambahan')
        ]);

        return redirect()->to('/InputPenghargaan')
            ->with('success', 'Penghargaan berhasil disimpan.');
    }

    /**
     * Ajax Ambil Murid berdasarkan Kelas
     */
    public function getSiswa($id_kelas)
    {
        $siswa = $this->siswaModel
            ->where('id_kelas', $id_kelas)
            ->orderBy('nama', 'ASC')
            ->findAll();

        return $this->response->setJSON($siswa);
    }
}
