<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Services\LabelDefinitionService;
use Throwable;

final class LabelDefinitionController
{
    public function handle(): void
    {
        Auth::requireLogin();
        require_permission('admin.label_definitions.edit');

        $service = new LabelDefinitionService(DB::pdo());
        $errors = [];

        if (Request::isPost()) {
            try {
                Csrf::verify();
                $service->save(Request::all());
                Response::flash('success', 'تم حفظ تعريفات الاختصارات بنجاح.');
                Response::redirect('/admin/label-definitions');
                return;
            } catch (Throwable $e) {
                $errors[] = $e->getMessage();
            }
        }

        if ($service->tableReady()) {
            $service->ensureDefaults();
        }

        Response::view('pages/admin/label_definitions', [
            'page_title' => 'تعريفات الاختصارات',
            'breadcrumbs' => [
                ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
                ['label' => 'الإدارة'],
                ['label' => 'تعريفات الاختصارات'],
            ],
            'ready' => $service->tableReady(),
            'groups' => $service->grouped(),
            'errors' => $errors,
        ]);
    }
}
