<?php
namespace App\Controllers\Setup;

use CodeIgniter\Controller;
use Config\Database;

class SchoolYearController extends Controller
{
    public function index()
    {
        $db = Database::connect();
        $items = [];
        try {
            $items = $db->table('school_years')->orderBy('id', 'desc')->get()->getResultArray();
        } catch (\Throwable $e) {
            $items = [];
        }
        return view('setup/school_years', [
            'title' => 'School Year Setup',
            'items' => $items,
        ]);
    }

    public function store()
    {
        $req = $this->request;
        $db = Database::connect();
        $data = [
            'sno' => $req->getPost('sno') ?? '',
            'school_year' => $req->getPost('school_year') ?? '',
            'status' => $req->getPost('status') ?? 'active',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        if (! $data['sno'] || ! $data['school_year']) {
            return redirect()->back()->with('error', 'S/No and School Year are required.');
        }
        try {
            $db->table('school_years')->insert($data);
            return redirect()->back()->with('success', 'School Year added.');
        } catch (\Throwable $e) {
            return redirect()->back()->with('error', 'Failed to add School Year: ' . $e->getMessage());
        }
    }
}
