<?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\PackageManager\PackageRegistryService;
use Throwable;

final class PackageManagerController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('packages.view');
        $dashboard = (new PackageRegistryService())->dashboard([
            'q' => $_GET['q'] ?? '',
            'category' => $_GET['category'] ?? '',
            'status' => $_GET['status'] ?? '',
        ], isset($_GET['package_id']) ? (int)$_GET['package_id'] : null);
        $this->view('platform/package_manager', [
            'pageTitle' => 'Enterprise Package Manager',
            'packageManagerPackages' => $dashboard['packages'],
            'packageManagerSelected' => $dashboard['selected'],
            'packageManagerMetrics' => $dashboard['metrics'],
            'packageManagerCategories' => $dashboard['categories'],
            'packageManagerStatuses' => $dashboard['statuses'],
            'packageManagerRecentOperations' => $dashboard['recent_operations'],
            'packageManagerGeneratedAt' => $dashboard['generated_at'],
            'packageManagerFilters' => [
                'q' => (string)($_GET['q'] ?? ''),
                'category' => (string)($_GET['category'] ?? ''),
                'status' => (string)($_GET['status'] ?? ''),
            ],
        ]);
    }

    public function synchronize(): void
    {
        Auth::requireLogin();
        Permission::require('packages.manage');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            $result = (new PackageRegistryService())->synchronize((int)(Auth::user()['id'] ?? 0) ?: null);
            $_SESSION['success'] = (int)$result['synchronized'].' package(s) synchronisé(s) dans le registre Enterprise.';
        } catch (Throwable $e) {
            $_SESSION['error'] = 'Synchronisation impossible : '.$e->getMessage();
        }
        $this->redirect('/administration/plateforme/packages');
    }

    public function exportCsv(): void
    {
        Auth::requireLogin();
        Permission::require('packages.export');
        $rows = (new PackageRegistryService())->exportRows();
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="axiom_package_registry_'.date('Ymd_His').'.csv"');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        echo "\xEF\xBB\xBF";
        $out = fopen('php://output', 'wb');
        fputcsv($out, ['ID','Package','Catégorie','Version','État','Trust','Compatibilité','Certification','Policy','Installé le'], ';');
        foreach ($rows as $row) {
            fputcsv($out, [$row['id'],$row['package_name'],$row['category'],$row['version'],$row['package_status'],$row['trust_score'],$row['compatibility_score'],$row['certification_status'],$row['policy_decision'],$row['installed_at']], ';');
        }
        fclose($out);
        exit;
    }
}
