<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Security\SecurityAuthorizationPolicy;
use MintyPHP\Module\Security\Service\SecurityCheckService;
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_CHECKS_CREATE);

$request = requestInput();
$returnTarget = requestResolveReturnTarget('security/checks');
$closeTarget = requestResolveReturnTarget('security/checks');
$createTarget = requestPathWithReturnTarget('security/checks/create', $returnTarget);

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

$templateService = app(SecurityCheckTemplateService::class);
$checkService = app(SecurityCheckService::class);
$errorBag = formErrors();

$form = [
    'debitor_no' => (string) $request->body('debitor_no', ''),
    'debitor_name' => (string) $request->body('debitor_name', ''),
    'domain_no' => (string) $request->body('domain_no', ''),
    'domain_url' => (string) $request->body('domain_url', ''),
    'product_code' => (string) $request->body('product_code', ''),
    'owner_user_id' => (int) $request->body('owner_user_id', (string) $userId),
];

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

        return;
    }

    $result = $checkService->create($tenantId, [
        'debitor_no' => $form['debitor_no'],
        'debitor_name' => $form['debitor_name'],
        'domain_no' => $form['domain_no'],
        'domain_url' => $form['domain_url'],
        'product_code' => $form['product_code'],
        'owner_user_id' => $form['owner_user_id'],
    ], $userId);

    if ($result['ok'] ?? false) {
        $editUrl = lurl('security/checks/edit/' . (int) $result['id']);
        Flash::success(t('Security check created'), $editUrl, 'security_check_created');
        Router::redirect($editUrl);

        return;
    }

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

$templates = $templateService->listActive($tenantId);
$assignableUsers = $checkService->listAssignableUsers($tenantId);
$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();

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