<?php

declare(strict_types=1);

/**
 * Helpers for contract details view (Get contract API).
 */

function contract_details_display_value(mixed $value): string
{
    if ($value === null || $value === '') {
        return '—';
    }

    if (is_bool($value)) {
        return $value ? 'true' : 'false';
    }

    if (is_scalar($value)) {
        return (string)$value;
    }

    $json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

    return $json !== false ? $json : '—';
}

function contract_details_is_url(string $value): bool
{
    return filter_var($value, FILTER_VALIDATE_URL) !== false;
}

/** @param array<string,mixed> $contract */
function contract_details_address(array $contract): string
{
    $street = trim((string)($contract['street_address'] ?? ''));
    $zipCity = trim((string)($contract['zip_city'] ?? ''));
    $parts = array_filter([$street, $zipCity]);

    return $parts !== [] ? implode(', ', $parts) : '—';
}

/** @param array<string,mixed> $rows */
function contract_details_render_field_rows(array $rows): void
{
    foreach ($rows as $label => $value) {
        $isLink = is_string($value) && $value !== '—' && contract_details_is_url($value);
        ?>
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-1 sm:gap-4 py-3 border-b border-karvi-100 last:border-0">
            <dt class="text-xs font-semibold uppercase tracking-wide text-karvi-500"><?= e((string)$label) ?></dt>
            <dd class="sm:col-span-2 text-sm text-karvi-950 break-all">
                <?php if ($isLink): ?>
                <a href="<?= e($value) ?>" target="_blank" rel="noopener noreferrer" class="text-karvi-800 underline hover:text-karvi-950"><?= e($value) ?></a>
                <?php else: ?>
                <?= e(contract_details_display_value($value)) ?>
                <?php endif; ?>
            </dd>
        </div>
        <?php
    }
}

/** @param array<string,mixed> $raw */
function contract_details_render_raw_data(array $raw, int $depth = 0): void
{
    if ($raw === []) {
        echo '<p class="text-sm text-karvi-500">—</p>';
        return;
    }

    echo '<dl class="space-y-0">';
    foreach ($raw as $key => $value) {
        $label = (string)$key;
        if (is_array($value)) {
            ?>
            <div class="py-3 border-b border-karvi-100 last:border-0" style="margin-left: <?= (int)min($depth * 12, 48) ?>px">
                <p class="text-xs font-semibold uppercase tracking-wide text-karvi-500 mb-2"><?= e($label) ?></p>
                <?php contract_details_render_raw_data($value, $depth + 1); ?>
            </div>
            <?php
            continue;
        }

        $display = contract_details_display_value($value);
        $isLink = is_string($value) && $display !== '—' && contract_details_is_url($display);
        ?>
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-1 sm:gap-4 py-2 border-b border-karvi-50 last:border-0" style="margin-left: <?= (int)min($depth * 12, 48) ?>px">
            <dt class="text-xs font-medium text-karvi-600"><?= e($label) ?></dt>
            <dd class="sm:col-span-2 text-sm text-karvi-900 break-all font-mono">
                <?php if ($isLink): ?>
                <a href="<?= e($display) ?>" target="_blank" rel="noopener noreferrer" class="font-sans underline"><?= e($display) ?></a>
                <?php else: ?>
                <?= e($display) ?>
                <?php endif; ?>
            </dd>
        </div>
        <?php
    }
    echo '</dl>';
}

/** @return list<string> */
function contract_edit_owner_names_list(mixed $ownerName): array
{
    if (is_array($ownerName)) {
        $names = [];
        foreach ($ownerName as $name) {
            $name = trim((string)$name);
            if ($name !== '') {
                $names[] = $name;
            }
        }

        return $names;
    }

    $value = trim((string)$ownerName);
    if ($value === '') {
        return [''];
    }

    if (str_contains($value, ',')) {
        return array_values(array_filter(array_map('trim', explode(',', $value)), static fn(string $n): bool => $n !== ''));
    }

    return [$value];
}

function contract_edit_owner_name_json(mixed $ownerName): string
{
    if (is_array($ownerName)) {
        $json = json_encode($ownerName, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

        return $json !== false ? $json : '[]';
    }

    return '';
}

function contract_edit_raw_data_json(array $rawData): string
{
    if ($rawData === []) {
        return '';
    }

    $json = json_encode($rawData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

    return $json !== false ? $json : '';
}

function contract_edit_nullable_field_value(mixed $value): string
{
    if ($value === null) {
        return '';
    }

    if (is_bool($value)) {
        return $value ? '1' : '0';
    }

    return trim((string)$value);
}
