@php
    /** @var \App\Support\Witness\WitnessQuestionnaire $questionnaire */
    /** @var array $answers  keyed "section.question" => [value, origin, review_status, provenance] */

    $fmt = function ($value) {
        if (is_bool($value)) {
            return $value ? 'Yes' : 'No';
        }
        if (is_array($value)) {
            // repeater rows or multiselect
            if ($value !== [] && is_array(reset($value))) {
                return null; // handled as table
            }
            return implode(', ', array_filter($value, fn ($v) => $v !== null && $v !== ''));
        }
        return (string) $value;
    };
@endphp
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        * { box-sizing: border-box; }
        body { font-family: 'Georgia', 'Times New Roman', serif; color: #1a1a1a; font-size: 11.5pt; line-height: 1.5; }
        h1 { font-size: 18pt; margin: 0 0 4px; }
        h2 { font-size: 13pt; border-bottom: 1.5px solid #333; padding-bottom: 4px; margin: 22px 0 10px; }
        h3 { font-size: 11.5pt; margin: 14px 0 4px; color: #333; }
        .muted { color: #666; font-size: 9.5pt; }
        .meta-table { width: 100%; border-collapse: collapse; margin: 10px 0 4px; }
        .meta-table td { padding: 3px 6px; vertical-align: top; }
        .meta-table td.k { width: 34%; color: #555; }
        .qa { margin: 0 0 10px; }
        .qa .q { font-weight: bold; font-size: 10.5pt; }
        .qa .a { margin: 2px 0 0; white-space: pre-wrap; }
        .rep { width: 100%; border-collapse: collapse; margin-top: 4px; font-size: 10pt; }
        .rep th, .rep td { border: 1px solid #bbb; padding: 4px 6px; text-align: left; }
        .exhibits li { margin-bottom: 4px; }
        .truth { margin-top: 24px; padding: 12px; border: 1px solid #333; }
        .cover { page-break-after: always; }
    </style>
</head>
<body>

@if($coverLetter)
    <section class="cover">
        <p>{{ now()->format('d F Y') }}</p>
        <p>
            {{ $client->fullName }}<br>
            @if($answers['client_details.current_address']['value'] ?? null){!! nl2br(e($answers['client_details.current_address']['value'])) !!}@endif
        </p>
        <p>Dear {{ $client->name_first ?? 'Sir/Madam' }},</p>
        <h3>Re: Your Witness Statement — Scottish Redress Scheme application {{ $claim->case_number }}</h3>
        <p>
            Please find enclosed your witness statement prepared in support of your application to the Scottish Redress
            Scheme. Please read it carefully, check that it is accurate and reflects your account in your own words, and
            let us know of any amendments. Once you are satisfied it is correct, please sign and date the statement of
            truth at the end.
        </p>
        <p>Yours sincerely,</p>
        <p>{{ $solicitor->name ?? 'MMA Legal' }}</p>
    </section>
@endif

<header>
    <h1>Witness Statement</h1>
    <div class="muted">
        Scottish Redress Scheme · Application {{ $claim->case_number }} · Version {{ $versionNumber }}
        · Generated {{ now()->format('d/m/Y') }}
    </div>
</header>

<table class="meta-table">
    <tr><td class="k">Applicant</td><td>{{ $client->fullName }}</td></tr>
    <tr><td class="k">Date of birth</td><td>{{ optional($client->date_of_birth)->format('d F Y') }}</td></tr>
    <tr><td class="k">Application reference</td><td>{{ $claim->case_number }}</td></tr>
</table>

@foreach($questionnaire->groups() as $group)
    @php
        $groupSections = $questionnaire->sectionsForGroup($group);
        // Does this group have any answered content?
        $hasContent = $groupSections->flatMap(fn ($s) => $s->questions->map(fn ($q) => $answers[$s->key.'.'.$q->key]['value'] ?? null))
            ->contains(fn ($v) => $v !== null && $v !== '' && $v !== []);
    @endphp
    @continue(! $hasContent)

    <h2>{{ $loop->iteration }}. {{ $group }}</h2>

    @foreach($groupSections as $section)
        @php
            $sectionHas = $section->questions->contains(fn ($q) => ! in_array($answers[$section->key.'.'.$q->key]['value'] ?? null, [null, '', []], true));
        @endphp
        @continue(! $sectionHas)

        <h3>{{ $section->title }}</h3>

        @foreach($section->questions as $question)
            @php $answer = $answers[$section->key.'.'.$question->key] ?? null; @endphp
            @php $value = $answer['value'] ?? null; @endphp
            @continue($value === null || $value === '' || $value === [])

            @if($question->type === 'repeater' && is_array($value))
                <div class="qa">
                    <div class="q">{{ $question->label }}</div>
                    <table class="rep">
                        <thead><tr>@foreach($question->fields as $sub)<th>{{ $sub->label }}</th>@endforeach</tr></thead>
                        <tbody>
                        @foreach($value as $row)
                            <tr>@foreach($question->fields as $sub)<td>{{ $row[$sub->key] ?? '' }}</td>@endforeach</tr>
                        @endforeach
                        </tbody>
                    </table>
                </div>
            @else
                <div class="qa">
                    <div class="q">{{ $question->label }}</div>
                    <div class="a">{{ $fmt($value) }}</div>
                </div>
            @endif
        @endforeach
    @endforeach
@endforeach

@if(! empty($exhibits))
    <h2>Schedule of Exhibits</h2>
    <ul class="exhibits">
        @foreach($exhibits as $exhibit)
            <li>
                <strong>{{ $exhibit['exhibit_ref'] }}</strong> —
                {{ $exhibit['document_name'] ?? 'Document' }}@if($exhibit['page']), page {{ $exhibit['page'] }}@endif
                @if($exhibit['label'])<br><span class="muted">{{ $exhibit['label'] }}</span>@endif
            </li>
        @endforeach
    </ul>
@endif

<div class="truth">
    <h3 style="margin-top:0;">Statement of Truth</h3>
    <p>I believe that the facts stated in this Witness Statement are true to the best of my knowledge and recollection.</p>
    <table class="meta-table">
        <tr><td class="k">Signed</td><td>___________________________</td></tr>
        <tr><td class="k">Name</td><td>{{ $answers['declaration.signed_name']['value'] ?? $client->fullName }}</td></tr>
        <tr><td class="k">Date</td><td>{{ $answers['declaration.signed_date']['value'] ?? '_______________' }}</td></tr>
    </table>
</div>

</body>
</html>
