<?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\ObjectModel\ObjectRepository;
use Throwable;

final class ObjectModelController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.objects.view');
        $repository = new ObjectRepository();
        $entityId = max(0, (int)($_GET['entity'] ?? 0));
        $search = trim((string)($_GET['q'] ?? ''));
        $uuid = trim((string)($_GET['object'] ?? ''));
        $this->view('axiom_objects/index', [
            'pageTitle' => 'AXIOM Object Model',
            'entities' => $repository->entities(),
            'objects' => $repository->objects($entityId ?: null, $search),
            'selected' => $uuid !== '' ? $repository->object($uuid) : null,
            'events' => $uuid !== '' ? $repository->events($uuid) : [],
            'entityId' => $entityId,
            'search' => $search,
            'canManage' => Permission::can('axiom.objects.manage'),
            'flashSuccess' => $_SESSION['axiom_objects_success'] ?? null,
            'flashError' => $_SESSION['axiom_objects_error'] ?? null,
        ]);
        unset($_SESSION['axiom_objects_success'], $_SESSION['axiom_objects_error']);
    }

    public function save(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.objects.manage');
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            $uuid = (new ObjectRepository())->save($_POST, isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null);
            $_SESSION['axiom_objects_success'] = 'Objet AXIOM enregistré et versionné.';
            $this->redirect('/administration/axiom/objects?object=' . urlencode($uuid));
        } catch (Throwable $e) {
            $_SESSION['axiom_objects_error'] = $e->getMessage();
            $this->redirect('/administration/axiom/objects');
        }
    }

    public function archive(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.objects.manage');
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            (new ObjectRepository())->archive(trim((string)($_POST['uuid'] ?? '')), isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null);
            $_SESSION['axiom_objects_success'] = 'Objet AXIOM archivé.';
        } catch (Throwable $e) {
            $_SESSION['axiom_objects_error'] = $e->getMessage();
        }
        $this->redirect('/administration/axiom/objects');
    }
}
