<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Security\SecurityAuthorizationPolicy;
use MintyPHP\Module\Security\Service\SecurityCheckTemplateService;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

$request = requestInput();
$returnTarget = requestResolveReturnTarget();
$closeTarget = requestResolveReturnTarget('security/templates');
$templateId = (int) ($id ?? 0);
$editTarget = requestPathWithReturnTarget('security/templates/edit/' . $templateId, $returnTarget);

$session = app(SessionStoreInterface::class)->all();
$tenantId = (int) ($session['current_tenant']['id'] ?? 0);
$userId = (int) ($session['user']['id'] ?? 0);

$service = app(SecurityCheckTemplateService::class);
$template = $service->findById($tenantId, $templateId);

if ($template === null) {
    Flash::error(t('Template not found'), $closeTarget, 'template_not_found');
    Router::redirect($closeTarget);

    return;
}

$errorBag = formErrors();

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

        return;
    }

    $name = (string) $request->body('product_name', '');
    $active = $request->body('active', '') !== '';

    $metaResult = $service->updateMeta($tenantId, $templateId, $name, $active, $userId);
    $errorBag->merge($metaResult['errors'] ?? []);

    $items = [];
    $schemaJson = (string) $request->body('tech_schema_json', '');
    if ($schemaJson !== '') {
        $decoded = json_decode($schemaJson, true);
        if (is_array($decoded)) {
            $items = $decoded;
        }
    }
    $schemaResult = $service->saveTechSchema($tenantId, $templateId, $items, $userId);
    $errorBag->merge($schemaResult['errors'] ?? []);

    if (!$errorBag->hasAny()) {
        $action = (string) $request->body('action', 'save');
        $target = $action === 'save_close' ? $closeTarget : $editTarget;
        Flash::success(t('Template saved'), $target, 'template_saved');
        Router::redirect($target);

        return;
    }

    flashFormErrors($errorBag, $editTarget, 'template_save_failed');
    Router::redirect($editTarget);

    return;
}

$schema = $service->decodeSchema($template);
$schemaItems = $schema['items'] ?? [];

$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();

$titleText = trim((string) ($template['product_name'] ?? '')) !== ''
    ? (string) $template['product_name']
    : t('Edit template');
Buffer::set('title', $titleText);
Buffer::set('style_groups', json_encode(['security']));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Security'), 'path' => 'security/checks'],
    ['label' => t('Check templates'), 'path' => 'security/templates'],
    ['label' => $titleText],
];
