<?php

namespace App\Core\Modules\Controllers;

use App\Controllers\BaseController;
use App\Core\Audit\Services\AuditService;
use App\Core\Modules\Models\ModuleModel;
use App\Core\Modules\Services\ModuleManager;

class ModuleController extends BaseController
{
    public function index()
    {
        $manager = new ModuleManager();
        $manager->sync();

        return view('core/modules/index', [
            'title' => 'Modules',
            'modules' => (new ModuleModel())->orderBy('label')->findAll(),
        ]);
    }

    public function toggle(string $name)
    {
        $enabled = (bool) $this->request->getPost('enabled');
        (new ModuleManager())->setEnabled($name, $enabled);
        (new AuditService())->log('module.toggle', 'module', $name, $enabled ? 'Module activé' : 'Module désactivé');

        return redirect()->back()->with('success', 'Statut du module mis à jour.');
    }
}
