<?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('security/templates');
$closeTarget = requestResolveReturnTarget('security/templates');
$createTarget = requestPathWithReturnTarget('security/templates/create', $returnTarget);

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

$service = app(SecurityCheckTemplateService::class);
$errorBag = formErrors();

$form = [
    'product_code' => (string) $request->body('product_code', ''),
    'product_name' => (string) $request->body('product_name', ''),
];

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

        return;
    }

    $result = $service->create($tenantId, $form['product_code'], $form['product_name'], $userId);
    if ($result['ok'] ?? false) {
        $editUrl = lurl('security/templates/edit/' . (int) $result['id']);
        Flash::success(t('Template created'), $editUrl, 'template_created');
        Router::redirect($editUrl);

        return;
    }

    $errorBag->merge($result['errors'] ?? []);
}

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

Buffer::set('title', t('New template'));
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' => t('New template')],
];
