<?php

use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\SoftwareProductService;
use MintyPHP\Support\Guard;

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

$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/software-products/filter-schema.php');

$service = app(SoftwareProductService::class);
$result = $service->listPaged($filters);

$rows = $result['rows'] ?? [];
$total = $result['total'] ?? 0;

$editBaseUrl = lurl('helpdesk/software-products/edit/');

$preparedRows = [];
foreach ($rows as $row) {
    $code = (string) ($row['code'] ?? '');
    $active = (int) ($row['active'] ?? 1);

    $preparedRows[] = [
        'code' => $code,
        'bc_description' => (string) ($row['bc_description'] ?? ''),
        'name' => (string) ($row['name'] ?? ''),
        'active' => $active,
        'active_label' => $active ? t('Active') : t('Inactive'),
        'active_variant' => $active ? 'success' : 'neutral',
        'synced_at' => (string) ($row['synced_at'] ?? ''),
        'edit_url' => $code !== '' ? $editBaseUrl . rawurlencode($code) : '',
    ];
}

gridJsonDataResult($preparedRows, $total);
