<?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\Services\Certification\PackageCertificationService;
use Throwable;
final class PackageCertificationController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('updates.certification.view');
        $dashboard = (new PackageCertificationService())->dashboard();
        $this->view('platform/package_certification_center', [
            'pageTitle' => 'Certification Center',
            'certificates' => (array)($dashboard['certificates'] ?? []),
            'certificationGeneratedAt' => (string)($dashboard['generated_at'] ?? ''),
        ]);
    }

    public function certify(): void
    {
        Auth::requireLogin();
        Permission::require('updates.certification.manage');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            $result = (new PackageCertificationService())->certifyPackage(
                (int)($_POST['package_id'] ?? 0),
                (int)(Auth::user()['id'] ?? 0) ?: null
            );
            $_SESSION[$result['decision'] === 'REJECTED' ? 'error' : 'success'] =
                'Certification Center : '.$result['decision'].' — '.$result['score'].'/100.';
        } catch (Throwable $e) {
            $_SESSION['error'] = 'Certification impossible : '.$e->getMessage();
        }
        $this->redirect('/administration/plateforme/certification-packages');
    }

    public function revoke(): void
    {
        Auth::requireLogin();
        Permission::require('updates.certification.manage');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            (new PackageCertificationService())->revokeCertificate(
                (int)($_POST['certificate_id'] ?? 0),
                trim((string)($_POST['reason'] ?? '')),
                (int)(Auth::user()['id'] ?? 0) ?: null
            );
            $_SESSION['success'] = 'Certificat révoqué.';
        } catch (Throwable $e) {
            $_SESSION['error'] = 'Révocation impossible : '.$e->getMessage();
        }
        $this->redirect('/administration/plateforme/certification-packages');
    }
}
