<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Security\SecurityAuthorizationPolicy;
use MintyPHP\Module\Security\Service\SecurityCheckProcess;
use MintyPHP\Module\Security\Service\SecurityCheckTemplateService;
use MintyPHP\Support\Guard;

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

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

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

$result = app(SecurityCheckTemplateService::class)->listPaged($tenantId, $filters);
$rows = $result['rows'] ?? [];
$total = (int) ($result['total'] ?? 0);

$editBaseUrl = lurl('security/templates/edit/');

$preparedRows = [];
foreach ($rows as $row) {
    $id = (int) ($row['id'] ?? 0);
    $items = SecurityCheckProcess::techCheckItems(
        is_array(json_decode((string) ($row['tech_schema_json'] ?? ''), true)) ? json_decode((string) ($row['tech_schema_json'] ?? ''), true) : []
    );
    $preparedRows[] = [
        'id' => $id,
        'product_code' => (string) ($row['product_code'] ?? ''),
        'product_name' => (string) ($row['product_name'] ?? ''),
        'item_count' => count($items),
        'active' => (int) ($row['active'] ?? 0) === 1,
        'updated_at' => (string) ($row['updated_at'] ?? ($row['created_at'] ?? '')),
        'edit_url' => $id > 0 ? $editBaseUrl . $id : '',
    ];
}

gridJsonDataResult($preparedRows, $total);
