<?php

use MintyPHP\Buffer;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\SoftwareProductService;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(HelpdeskAuthorizationPolicy::ABILITY_SOFTWARE_PRODUCTS_MANAGE);

$request = requestInput();
$returnTarget = requestResolveReturnTarget();
$closeTarget = requestResolveReturnTarget('helpdesk/software-products');

$productCode = rawurldecode(trim((string) ($code ?? '')));
$editTarget = requestPathWithReturnTarget('helpdesk/software-products/edit/' . rawurlencode($productCode), $returnTarget);

$service = app(SoftwareProductService::class);
$product = $service->findByCode($productCode);

if ($product === null) {
    Flash::error(t('Software product not found'), $closeTarget, 'software_product_not_found');
    Router::redirect($closeTarget);
    return;
}

$errorBag = formErrors();
$warnings = [];
$form = $product;

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

if ($request->isMethod('POST')) {
    $name = (string) $request->body('name', '');
    $result = $service->updateNameByCode($productCode, $name);
    $form = $result['form'] ?? $form;
    $errorBag->merge($result['errors'] ?? []);

    $schemaJson = (string) $request->body('handover_schema_json', '');
    $schemaFields = [];
    if ($schemaJson !== '') {
        $decoded = json_decode($schemaJson, true);
        if (is_array($decoded)) {
            $schemaFields = $decoded;
        }
    }
    $schemaResult = $service->saveHandoverSchema($productCode, $schemaFields);
    $errorBag->merge($schemaResult['errors'] ?? []);

    $allOk = ($result['ok'] ?? false) && ($schemaResult['ok'] ?? false);

    if ($allOk && !$errorBag->hasAny()) {
        $product = $service->findByCode($productCode);
        $action = (string) $request->body('action', 'save');
        if ($action === 'save_close') {
            Flash::success(t('Software product updated'), $closeTarget, 'software_product_updated');
            Router::redirect($closeTarget);
        } else {
            Flash::success(t('Software product updated'), $editTarget, 'software_product_updated');
            Router::redirect($editTarget);
        }
        return;
    }
}

$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();
$displayName = trim((string) ($product['name'] ?? '')) !== ''
    ? $product['name']
    : (trim((string) ($product['bc_description'] ?? '')) !== '' ? $product['bc_description'] : null);
$titleText = $displayName !== null ? $displayName : t('Edit software product');
Buffer::set('title', $titleText);
Buffer::set('style_groups', json_encode(['helpdesk']));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Helpdesk'), 'path' => 'helpdesk'],
    ['label' => t('Software products'), 'path' => 'helpdesk/software-products'],
    ['label' => $titleText],
];

$handoverSchemaRaw = $product['handover_protocol_schema'] ?? null;
$handoverSchema = null;
if ($handoverSchemaRaw !== null) {
    $decoded = json_decode($handoverSchemaRaw, true);
    if (is_array($decoded)) {
        $handoverSchema = $decoded;
    }
}
$handoverSchemaFields = $handoverSchema['fields'] ?? [];
