<?php

use MintyPHP\Buffer;
use MintyPHP\Module\Security\SecurityAuthorizationPolicy;
use MintyPHP\Module\Security\Service\SecurityReportLogoService;
use MintyPHP\Module\Security\Service\SecurityReportSettingsGateway;
use MintyPHP\Module\Security\Service\SecurityReportTemplateService;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(SecurityAuthorizationPolicy::ABILITY_SETTINGS_MANAGE);

$request = requestInput();
$reportSettings = app(SecurityReportSettingsGateway::class);
$logoService = app(SecurityReportLogoService::class);
$templateService = app(SecurityReportTemplateService::class);

if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
    Flash::error(t('Form expired, please try again'), 'security/report-design', 'csrf_expired');
    Router::redirect('security/report-design');

    return;
}

if ($request->isMethod('POST')) {
    $action = (string) $request->body('action', 'save');

    if ($action === 'delete_logo') {
        $logoService->delete();
        Flash::success(t('Report logo removed'), 'security/report-design', 'report_logo_removed');
        Router::redirect('security/report-design');

        return;
    }

    $errorBag = formErrors();

    if (!$reportSettings->setTemplateHtml((string) $request->body('template_html', ''))) {
        $errorBag->add('template_html', t('The template is too large.'));
    }

    // Only touch the logo when a file was actually submitted.
    $upload = $request->filesAll()['logo'] ?? [];
    if (is_array($upload) && (int) ($upload['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
        $result = $logoService->saveUpload($upload);
        if (!($result['ok'] ?? false)) {
            $errorBag->addGlobal((string) ($result['error'] ?? t('Upload failed')));
        }
    }

    if ($errorBag->hasAny()) {
        flashFormErrors($errorBag, 'security/report-design', 'report_design_error');
    } else {
        Flash::success(t('Settings saved'), 'security/report-design', 'report_design_saved');
    }

    Router::redirect('security/report-design');

    return;
}

$hasCustomTemplate = $reportSettings->hasCustomTemplate();
// Prefill the editor with the built-in default scaffold when nothing is stored,
// so the admin has a working baseline to customise.
$templateHtml = $hasCustomTemplate ? $reportSettings->getTemplateHtml() : $templateService->defaultTemplateHtml();
$variables = $templateService->availableVariables();

$hasLogo = $logoService->hasLogo();
$logoVersion = '';
if ($hasLogo) {
    $logoPath = $logoService->findLogoPath(256);
    $logoVersion = ($logoPath && is_file($logoPath)) ? (string) filemtime($logoPath) : '';
}

Buffer::set('title', t('Customer report design'));
Buffer::set('style_groups', json_encode(['security']));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Security'), 'path' => 'security/checks'],
    ['label' => t('Customer report design')],
];
