<?php
namespace App\Controllers\Setup;

use CodeIgniter\Controller;
use Config\Database;

class SectionController extends Controller
{
    public function index()
    {
        $db = Database::connect();
        $items = $classes = [];
        try { $items = $db->table('sections')->select('sections.*, classes.name_en as class_name')->join('classes', 'classes.id = sections.class_id')->orderBy('sections.id', 'desc')->get()->getResultArray(); } catch (\Throwable $e) { $items = []; }
        try { $classes = $db->table('classes')->orderBy('id', 'asc')->get()->getResultArray(); } catch (\Throwable $e) { $classes = []; }
        return view('setup/sections', [ 'title' => 'Sections Setup', 'items' => $items, 'classes' => $classes ]);
    }

    public function store()
    {
        $req = $this->request;
        $db = Database::connect();
        $data = [
            'class_id' => (int) ($req->getPost('class_id') ?? 0),
            '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['class_id'] || ! $data['name_en']) {
            return redirect()->back()->with('error', 'Class and Section name (EN) are required.');
        }
        try { $db->table('sections')->insert($data); return redirect()->back()->with('success', 'Section added.'); }
        catch (\Throwable $e) { return redirect()->back()->with('error', 'Failed to add section: ' . $e->getMessage()); }
    }
}
