<?php
namespace App\Controllers\Setup;

use CodeIgniter\Controller;
use Config\Database;

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

    public function store()
    {
        $req = $this->request;
        $db = Database::connect();
        $data = [
            'name_en' => $req->getPost('name_en') ?? '',
            'name_ar' => $req->getPost('name_ar') ?? '',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        if (! $data['name_en']) {
            return redirect()->back()->with('error', 'Class name (EN) is required.');
        }
        try { $db->table('classes')->insert($data); return redirect()->back()->with('success', 'Class added.'); }
        catch (\Throwable $e) { return redirect()->back()->with('error', 'Failed to add class: ' . $e->getMessage()); }
    }
}
