<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SubjectModel;

class Subject extends BaseController
{
    protected $model;

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

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        $role = session()->get('user_role');
        if (!in_array($role, ['superadmin', 'admin'])) {
            return redirect()->to('/dashboard')->with('error', 'Akses ditolak!');
        }
        return null;
    }

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

        $data = [
            'title'    => 'Mata Pelajaran',
            'subjects' => $this->model->orderBy('name', 'ASC')->findAll(),
        ];

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

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

        $rules = [
            'name' => 'required|max_length[100]|is_unique[subjects.name]',
            'code' => 'permit_empty|max_length[20]|is_unique[subjects.code]',
        ];

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

        $this->model->insert([
            'code'        => $this->request->getPost('code'),
            'name'        => $this->request->getPost('name'),
            'level'       => $this->request->getPost('level') ?: 'ALL',
            'description' => $this->request->getPost('description'),
        ]);

        return redirect()->to('/subject')
            ->with('success', 'Mata pelajaran berhasil ditambahkan!');
    }

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

        $rules = [
            'name' => "required|max_length[100]|is_unique[subjects.name,id,{$id}]",
            'code' => "permit_empty|max_length[20]|is_unique[subjects.code,id,{$id}]",
        ];

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

        $this->model->update($id, [
            'code'        => $this->request->getPost('code'),
            'name'        => $this->request->getPost('name'),
            'level'       => $this->request->getPost('level') ?: 'ALL',
            'description' => $this->request->getPost('description'),
        ]);

        return redirect()->to('/subject')
            ->with('success', 'Mata pelajaran berhasil diupdate!');
    }

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

        $db = \Config\Database::connect();
        
        $schoolSubjectCount = $db->table('school_subjects')
            ->where('subject_id', $id)
            ->where('deleted_at', null)
            ->countAllResults();

        if ($schoolSubjectCount > 0) {
            return redirect()->to('/subject')
                ->with('error', "Tidak dapat menghapus mata pelajaran ini karena masih digunakan sebagai mata pelajaran sekolah!");
        }

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

        return redirect()->to('/subject')
            ->with('success', 'Mata pelajaran berhasil dihapus!');
    }
}