<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Permission;
use App\Core\Csrf;
use App\Foundation\Foundation;
use App\Runtime\ModuleRuntime;
use App\Kernel\Kernel;

final class KernelController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.kernel.view');

        $snapshot = Kernel::registry()->snapshot();
        $this->view('axiom_kernel/index', [
            'pageTitle' => 'AXIOM Kernel & Registry',
            'kernelVersion' => Kernel::VERSION,
            'snapshot' => $snapshot,
            'runtime' => Foundation::app()->container()->get(ModuleRuntime::class)->snapshot(),
        ]);
    }

    public function toggleModule(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.kernel.view');
        Csrf::verify($_POST['_csrf'] ?? null);
        $code=trim((string)($_POST['code'] ?? ''));
        $enabled=(string)($_POST['enabled'] ?? '0') === '1';
        try { Foundation::app()->container()->get(ModuleRuntime::class)->setEnabled($code, $enabled); $_SESSION['flash_success']='État du module enregistré. Il sera appliqué immédiatement au prochain chargement.'; }
        catch (\Throwable $e) { $_SESSION['flash_error']=$e->getMessage(); }
        $this->redirect('/administration/axiom/kernel');
    }
}
