<?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\PackageCatalogService;
use Throwable;
final class PackageCatalogController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin(); Permission::require('packages.catalog.view');
        $service = new PackageCatalogService();
        $data = $service->catalog([
            'q'=>(string)($_GET['q']??''), 'category'=>(string)($_GET['category']??''),
            'status'=>(string)($_GET['status']??''), 'flag'=>(string)($_GET['flag']??''),
            'view'=>(string)($_GET['view']??'cards'),
        ]);
        $this->view('platform/package_catalog', [
            'pageTitle'=>'Enterprise Package Catalog',
            'catalogPackages'=>$data['packages'], 'catalogMetrics'=>$data['metrics'],
            'catalogCategories'=>$data['categories'], 'catalogStatuses'=>$data['statuses'],
            'catalogFilters'=>$data['filters'], 'catalogCompareOptions'=>$data['compare_options'],
        ]);
    }
    public function preference(): void
    {
        Auth::requireLogin(); Permission::require('packages.catalog.manage'); Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf']??null);
        try {
            (new PackageCatalogService())->setPreference((int)($_POST['registry_id']??0),(string)($_POST['flag']??''),(int)(Auth::user()['id']??0)?:null);
            $_SESSION['success']='Préférence du package mise à jour.';
        } catch (Throwable $e) { $_SESSION['error']='Mise à jour impossible : '.$e->getMessage(); }
        $this->redirect('/administration/plateforme/packages/catalogue');
    }
    public function compare(): void
    {
        Auth::requireLogin(); Permission::require('packages.catalog.compare');
        $result=(new PackageCatalogService())->compare((int)($_GET['left']??0),(int)($_GET['right']??0));
        $this->view('platform/package_catalog_compare', ['pageTitle'=>'Comparaison de packages','catalogComparison'=>$result]);
    }
    public function exportCsv(): void
    {
        Auth::requireLogin(); Permission::require('packages.catalog.view');
        $rows=(new PackageCatalogService())->catalog([])['packages'];
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="axiom_package_catalog_'.date('Ymd_His').'.csv"');
        header('Cache-Control: no-store'); echo "\xEF\xBB\xBF";
        $o=fopen('php://output','wb'); fputcsv($o,['Package','Version','Catégorie','État','Trust','Compatibilité','Favori','Critique','Surveillé'],';');
        foreach($rows as $r) fputcsv($o,[$r['package_name'],$r['version'],$r['category'],$r['package_status'],$r['trust_score'],$r['compatibility_score'],$r['is_favorite'],$r['is_critical'],$r['is_watched']],';');
        fclose($o); exit;
    }
}
