<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\EducationModel;

class EducationController extends BaseController
{
    protected $educationModel;

    public function __construct()
    {
        $this->educationModel = new EducationModel();
    }

    /**
     * List educations with search, filter, and pagination
     */
    public function index()
    {
        $request = $this->request;
        
        $search = $request->getGet('q');
        $status = $request->getGet('status');
        $sort   = $request->getGet('sort') ?? 'latest';

        $educations = $this->educationModel->getAdminEducations($search, $status, $sort, 10);

        $data = [
            'title'      => 'Kelola Pendidikan',
            'educations' => $educations,
            'pager'      => $this->educationModel->pager,
            'search'     => $search,
            'status'     => $status,
            'sort'       => $sort,
            'total'      => $this->educationModel->countAllResults(false),
        ];

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

    /**
     * Create form
     */
    public function create()
    {
        $data = [
            'title'     => 'Tambah Pendidikan',
            'education' => null,
        ];

        return view('admin/educations/form', $data);
    }

    /**
     * Store new education
     */
    public function store()
    {
        $rules = [
            'institution' => 'required|min_length[3]|max_length[200]',
            'major'       => 'required|min_length[2]|max_length[150]',
            'degree'      => 'required|max_length[50]',
            'start_year'  => 'required|numeric|exact_length[4]',
            'end_year'    => 'permit_empty|numeric|exact_length[4]',
            'gpa'         => 'permit_empty|decimal',
            'status'      => 'required|in_list[ongoing,completed]',
        ];

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

        $data = [
            'institution' => $this->request->getPost('institution'),
            'major'       => $this->request->getPost('major'),
            'degree'      => $this->request->getPost('degree'),
            'start_year'  => $this->request->getPost('start_year'),
            'end_year'    => $this->request->getPost('end_year') ?: null,
            'gpa'         => $this->request->getPost('gpa') ?: null,
            'description' => $this->request->getPost('description'),
            'status'      => $this->request->getPost('status'),
        ];

        if ($this->educationModel->insert($data)) {
            return redirect()->to('/admin/pendidikan')
                ->with('success', 'Pendidikan berhasil ditambahkan.');
        }

        return redirect()->back()
            ->withInput()
            ->with('error', 'Gagal menambahkan pendidikan.');
    }

    /**
     * Edit form
     */
    public function edit(int $id)
    {
        $education = $this->educationModel->find($id);

        if (!$education) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Pendidikan tidak ditemukan');
        }

        $data = [
            'title'     => 'Edit Pendidikan',
            'education' => $education,
        ];

        return view('admin/educations/form', $data);
    }

    /**
     * Update education
     */
    public function update(int $id)
    {
        $education = $this->educationModel->find($id);

        if (!$education) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Pendidikan tidak ditemukan');
        }

        $rules = [
            'institution' => 'required|min_length[3]|max_length[200]',
            'major'       => 'required|min_length[2]|max_length[150]',
            'degree'      => 'required|max_length[50]',
            'start_year'  => 'required|numeric|exact_length[4]',
            'end_year'    => 'permit_empty|numeric|exact_length[4]',
            'gpa'         => 'permit_empty|decimal',
            'status'      => 'required|in_list[ongoing,completed]',
        ];

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

        $data = [
            'institution' => $this->request->getPost('institution'),
            'major'       => $this->request->getPost('major'),
            'degree'      => $this->request->getPost('degree'),
            'start_year'  => $this->request->getPost('start_year'),
            'end_year'    => $this->request->getPost('end_year') ?: null,
            'gpa'         => $this->request->getPost('gpa') ?: null,
            'description' => $this->request->getPost('description'),
            'status'      => $this->request->getPost('status'),
        ];

        if ($this->educationModel->update($id, $data)) {
            return redirect()->to('/admin/pendidikan')
                ->with('success', 'Pendidikan berhasil diperbarui.');
        }

        return redirect()->back()
            ->withInput()
            ->with('error', 'Gagal memperbarui pendidikan.');
    }

    /**
     * Delete education
     */
    public function delete(int $id)
    {
        $education = $this->educationModel->find($id);

        if (!$education) {
            return redirect()->to('/admin/pendidikan')
                ->with('error', 'Pendidikan tidak ditemukan.');
        }

        if ($this->educationModel->delete($id)) {
            return redirect()->to('/admin/pendidikan')
                ->with('success', 'Pendidikan berhasil dihapus.');
        }

        return redirect()->to('/admin/pendidikan')
            ->with('error', 'Gagal menghapus pendidikan.');
    }
}
