<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\GradeModel;

class Grade extends BaseController
{
    protected $model;

    public function __construct()
    {
        $this->model = new GradeModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        return null;
    }

    public function index()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $data = [
            'title'  => 'Master Tingkat',
            'grades' => $this->model->orderBy('order', 'ASC')->findAll(),
        ];

        return view('grade/index', $data);
    }

    public function store()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'name'  => 'required|max_length[20]|is_unique[grades.name]',
            'order' => 'required|integer',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        $this->model->insert([
            'name'  => $this->request->getPost('name'),
            'order' => $this->request->getPost('order'),
        ]);

        return redirect()->to('/grade')
            ->with('success', 'Tingkat berhasil ditambahkan!');
    }

    public function update($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'name'  => "required|max_length[20]|is_unique[grades.name,id,{$id}]",
            'order' => 'required|integer',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        $this->model->update($id, [
            'name'  => $this->request->getPost('name'),
            'order' => $this->request->getPost('order'),
        ]);

        return redirect()->to('/grade')
            ->with('success', 'Tingkat berhasil diupdate!');
    }

    public function delete($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $this->model->delete($id);

        return redirect()->to('/grade')
            ->with('success', 'Tingkat berhasil dihapus!');
    }
}