<?php

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

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

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

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

if (!isset($filters['view']) || !in_array($filters['view'], ['active', 'done'], true)) {
    $filters['view'] = 'active';
}

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

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

$preparedRows = [];
foreach ($rows as $row) {
    $id = (int) ($row['id'] ?? 0);
    $status = (string) ($row['status'] ?? 'open');

    $preparedRows[] = [
        'id' => $id,
        'debitor_name' => (string) ($row['debitor_name'] ?? ''),
        'domain_url' => (string) ($row['domain_url'] ?? ''),
        'product_name' => (string) ($row['product_name'] ?? ($row['product_code'] ?? '')),
        'status' => $status,
        'status_label' => t(SecurityCheckProcess::statusLabel($status)),
        'status_variant' => SecurityCheckProcess::statusVariant($status),
        'owner_name' => (string) ($row['owner_name'] ?? ''),
        'created_at' => (string) ($row['created_at'] ?? ''),
        'edit_url' => $id > 0 ? $editBaseUrl . $id : '',
    ];
}

gridJsonDataResult($preparedRows, $total);
