<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Meta\MetaRepository;
use Throwable;

final class MetaController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.meta.view');
        $repository = new MetaRepository();
        $selectedId = max(0, (int)($_GET['entity'] ?? 0));
        $this->view('axiom_meta/index', [
            'pageTitle' => 'AXIOM Meta Framework',
            'entities' => $repository->entities(),
            'dictionary' => $repository->dictionary(),
            'selected' => $selectedId > 0 ? $repository->entity($selectedId) : null,
            'fields' => $selectedId > 0 ? $repository->fields($selectedId) : [],
            'canManage' => Permission::can('axiom.meta.manage'),
            'flashSuccess' => $_SESSION['axiom_meta_success'] ?? null,
            'flashError' => $_SESSION['axiom_meta_error'] ?? null,
        ]);
        unset($_SESSION['axiom_meta_success'], $_SESSION['axiom_meta_error']);
    }

    public function saveEntity(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.meta.manage');
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            $id = (new MetaRepository())->saveEntity($_POST);
            $_SESSION['axiom_meta_success'] = 'Entité métier enregistrée.';
            $this->redirect('/administration/axiom/meta?entity=' . $id);
        } catch (Throwable $e) {
            $_SESSION['axiom_meta_error'] = $e->getMessage();
            $this->redirect('/administration/axiom/meta');
        }
    }

    public function saveField(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.meta.manage');
        Csrf::verify($_POST['_csrf'] ?? null);
        $entityId = max(0, (int)($_POST['entity_id'] ?? 0));
        try {
            (new MetaRepository())->saveField($_POST);
            $_SESSION['axiom_meta_success'] = 'Champ ajouté au modèle.';
        } catch (Throwable $e) {
            $_SESSION['axiom_meta_error'] = $e->getMessage();
        }
        $this->redirect('/administration/axiom/meta?entity=' . $entityId);
    }

    public function archiveEntity(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.meta.manage');
        Csrf::verify($_POST['_csrf'] ?? null);
        $id = max(0, (int)($_POST['id'] ?? 0));
        (new MetaRepository())->archiveEntity($id);
        $_SESSION['axiom_meta_success'] = 'Entité archivée.';
        $this->redirect('/administration/axiom/meta');
    }
}
