<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\HandoverService;
use MintyPHP\Support\Guard;

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

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

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

$authService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$canManage = $authService->authorize(HelpdeskAuthorizationPolicy::ABILITY_HANDOVERS_MANAGE, ['actor_user_id' => $userId])->isAllowed();

// Non-managers see only handovers assigned to them
if (!$canManage) {
    $filters['assigned_to'] = $userId;
}

// Pass view (open/closed) to repository filter
if (!isset($filters['view']) || !in_array($filters['view'], ['active', 'done'], true)) {
    $filters['view'] = 'active';
}

$service = app(HandoverService::class);
$result = $service->listPaged($tenantId, $filters);

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

$editBaseUrl = lurl('helpdesk/handovers/edit/');

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

    $productName = trim((string) ($row['product_name'] ?? ''));
    $productBcDesc = trim((string) ($row['product_bc_description'] ?? ''));
    $productDisplay = $productName !== '' ? $productName : ($productBcDesc !== '' ? $productBcDesc : (string) ($row['product_code'] ?? ''));

    $preparedRows[] = [
        'id' => $id,
        'domain_url' => (string) ($row['domain_url'] ?? ''),
        'debitor_name' => (string) ($row['debitor_name'] ?? ''),
        'product_display' => $productDisplay,
        'status' => $status,
        'status_label' => HandoverService::statusLabel($status),
        'status_variant' => HandoverService::statusVariant($status),
        'assigned_to_name' => (string) ($row['assigned_to_name'] ?? ''),
        'due_date' => (string) ($row['due_date'] ?? ''),
        'created_at' => (string) ($row['created_at'] ?? ''),
        'created_by_name' => (string) ($row['created_by_name'] ?? ''),
        'edit_url' => $id > 0 ? $editBaseUrl . $id : '',
    ];
}

gridJsonDataResult($preparedRows, $total);
