<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\MajorModel;

class Major extends BaseController
{
    protected $model;

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

    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 Jurusan',
            'majors' => $this->model->orderBy('name', 'ASC')->findAll(),
        ];

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

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

        $rules = [
            'name' => 'required|max_length[50]|is_unique[majors.name]',
        ];

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

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

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

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

        $rules = [
            'name' => "required|max_length[50]|is_unique[majors.name,id,{$id}]",
        ];

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

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

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

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

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

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