<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\StudyProgramModel;

class StudyProgramController extends BaseController
{
    public function index()
    {
        return view('admin/programs/index', [
            'title'    => 'Program Studi',
            'programs' => model(StudyProgramModel::class)->orderBy('name')->findAll(),
        ]);
    }

    public function store()
    {
        if (! $this->validate([
            'name' => 'required|max_length[150]',
            'code' => 'required|max_length[20]|is_unique[study_programs.code]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        model(StudyProgramModel::class)->insert([
            'name' => trim($this->request->getPost('name')),
            'code' => strtoupper(trim($this->request->getPost('code'))),
        ]);

        return redirect()->back()->with('success', 'Program studi ditambahkan.');
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name' => 'required|max_length[150]',
            'code' => 'required|max_length[20]',
        ])) {
            return redirect()->back()->with('errors', $this->validator->getErrors());
        }

        model(StudyProgramModel::class)->update($id, [
            'name' => trim($this->request->getPost('name')),
            'code' => strtoupper(trim($this->request->getPost('code'))),
        ]);

        return redirect()->back()->with('success', 'Program studi diperbarui.');
    }

    public function delete(int $id)
    {
        model(StudyProgramModel::class)->delete($id);
        return redirect()->back()->with('success', 'Program studi dihapus.');
    }
}
