<?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\Reporting\EnterpriseCompatibilityReportService;
use Throwable;

final class EnterpriseCompatibilityReportController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('updates.report.view');
        $reportId = isset($_GET['report_id']) ? (int)$_GET['report_id'] : null;
        $dashboard = (new EnterpriseCompatibilityReportService())->dashboard($reportId);
        $this->view('platform/enterprise_compatibility_report', [
            'pageTitle' => 'Enterprise Compatibility Report',
            'enterpriseReports' => (array)($dashboard['reports'] ?? []),
            'selectedEnterpriseReport' => $dashboard['selected'] ?? null,
            'enterpriseAvailablePackages' => (array)($dashboard['packages'] ?? []),
            'enterpriseReportGeneratedAt' => (string)($dashboard['generated_at'] ?? ''),
        ]);
    }

    public function evaluate(): void
    {
        Auth::requireLogin();
        Permission::require('updates.report.evaluate');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            $packageId = $this->resolvePackageId();
            $result = (new EnterpriseCompatibilityReportService())->evaluatePackageId($packageId, (int)(Auth::user()['id'] ?? 0) ?: null, true);
            $_SESSION[$result['decision'] === 'INSTALLATION_REFUSEE' ? 'error' : 'success'] = 'Rapport Enterprise : '.$result['decision'].' — '.(int)$result['scores']['global'].'/100.';
            $this->redirect('/administration/plateforme/rapport-compatibilite?report_id='.(int)($result['report_id'] ?? 0));
            return;
        } catch (Throwable $e) {
            $_SESSION['error'] = 'Analyse impossible : '.$e->getMessage();
        }
        $this->redirect('/administration/plateforme/rapport-compatibilite');
    }

    private function resolvePackageId(): int
    {
        $candidates = [
            $_POST['package_id'] ?? null,
            $_POST['selected_package_id'] ?? null,
            $_POST['package'] ?? null,
            $_GET['package_id'] ?? null,
        ];

        foreach ($candidates as $candidate) {
            if (is_int($candidate) && $candidate > 0) {
                return $candidate;
            }
            if (is_string($candidate)) {
                $candidate = trim($candidate);
                if ($candidate !== '' && ctype_digit($candidate) && (int)$candidate > 0) {
                    return (int)$candidate;
                }
            }
        }

        throw new \RuntimeException('Aucun package valide n’a été transmis. Utilisez le bouton Analyser associé au package souhaité.');
    }

    public function exportCsv(): void
    {
        Auth::requireLogin();
        Permission::require('updates.report.export');
        $rows = (new EnterpriseCompatibilityReportService())->csvRows();
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="axiom_enterprise_compatibility_reports_'.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','Date','Package','Version','Score global','Trust','Compatibilité','Certification','Politique','Décision'], ';');
        foreach ($rows as $row) {
            fputcsv($out, [$row['id'],$row['created_at'],$row['nom_package'],$row['version_cible'],$row['global_score'],$row['trust_score'],$row['compatibility_score'],$row['certification_score'],$row['policy_score'],$row['decision']], ';');
        }
        fclose($out);
        exit;
    }

    public function report(): void
    {
        Auth::requireLogin();
        Permission::require('updates.report.export');
        try {
            $report = (new EnterpriseCompatibilityReportService())->report((int)($_GET['report_id'] ?? 0));
        } catch (Throwable $e) {
            http_response_code(404);
            exit('Rapport introuvable.');
        }
        $this->view('platform/enterprise_compatibility_report_print', [
            'pageTitle' => 'Rapport Enterprise',
            'enterprisePrintReport' => $report,
        ]);
    }
}
