<?php
namespace App\Controllers\Setup;

use CodeIgniter\Controller;
use Config\Database;

class NationalityController extends Controller
{
    public function index()
    {
        $db = Database::connect();
        $items = [];
        try { $items = $db->table('nationalities')->orderBy('id', 'desc')->get()->getResultArray(); } catch (\Throwable $e) { $items = []; }
        return view('setup/nationalities', [ 'title' => 'Nationalities 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', 'Nationality (EN) is required.');
        }
        try { $db->table('nationalities')->insert($data); return redirect()->back()->with('success', 'Nationality added.'); }
        catch (\Throwable $e) { return redirect()->back()->with('error', 'Failed to add nationality: ' . $e->getMessage()); }
    }
}
