@extends('layouts.app')
@section('title','Review Contract Template')
@section('content')
@php
    $isPdf=$template->isPdf();
    $blocksById=collect($template->blocks ?? [])->keyBy('id');
    $mappingRows=old('mappings',$template->mappings ?? []);
    $startExtra=count($mappingRows);
    $pageCount=max(1,count($template->blocks ?? []));
@endphp
<x-ui.form-shell :title="'Review · '.$template->name" :description="$isPdf ? 'Finalize every system field and its exact PDF position here. These saved rules are used automatically when loans generate contracts.' : 'Finalize field placement and spacing in the uploaded Word contract here. These saved rules are used automatically when loans generate contracts.'" :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Contract Templates','url'=>route('admin.contract-templates.index')],['label'=>$template->name]]">
<form method="POST" action="{{ route('admin.contract-templates.update',$template) }}" class="mf-form">@csrf @method('PUT')
<x-ui.form-section title="Template settings" description="Control availability, default usage and signature requirements.">
<x-ui.form-grid>
<div class="mf-col-5"><label class="mf-field-label">Template name</label><input class="mf-input" name="name" value="{{ old('name',$template->name) }}" required></div>
<div class="mf-col-3"><label class="mf-field-label">Status</label><select class="mf-input" name="status">@foreach(['draft'=>'Draft','active'=>'Active','inactive'=>'Inactive'] as $value=>$label)<option value="{{ $value }}" @selected(old('status',$template->status)===$value)>{{ $label }}</option>@endforeach</select></div>
<div class="mf-col-4 flex items-end"><label class="mf-option w-full"><input type="checkbox" name="make_default" value="1" @checked(old('make_default',$template->is_default))><span><strong>Default loan contract</strong><small class="block text-muted-foreground">Used automatically when a loan does not already have a template snapshot.</small></span></label></div>
<div class="mf-col-12"><div class="flex flex-wrap items-center gap-2 text-xs text-muted-foreground"><span class="mf-badge mf-badge-muted">{{ strtoupper($isPdf?'pdf':'docx') }}</span><span>{{ $template->original_name }}</span><span>·</span>@if($isPdf)<span>{{ $pageCount }} PDF page{{ $pageCount===1?'':'s' }}</span>@else<span>{{ count($template->blocks ?? []) }} extracted blocks</span>@endif<span>·</span><span>{{ count($template->mappings ?? []) }} mapped fields</span><span>·</span><a class="text-primary hover:underline" href="{{ route('admin.contract-templates.download',$template) }}">Download original {{ strtoupper($isPdf?'PDF':'DOCX') }}</a></div></div>
</x-ui.form-grid>
<div class="mt-4 grid gap-2 sm:grid-cols-2 lg:grid-cols-3">@foreach($signatories as $value=>$label)<label class="mf-option"><input type="checkbox" name="required_signatories[]" value="{{ $value }}" @checked(in_array($value,old('required_signatories',$template->required_signatories ?? []),true))><span>{{ $label }}</span></label>@endforeach</div>
<div class="mt-4 rounded-md border p-3 text-xs"><strong>Finalize the contract here.</strong><div class="mt-1 text-muted-foreground">Loan users do not edit contract values, spacing or positions. When they click Generate Contract, the system fills this saved template automatically using the loan, customer, guarantor, collateral and business data already stored in the system.</div></div>
</x-ui.form-section>

@if($isPdf)
<x-ui.form-section title="Original PDF" description="Use the original pages below as your positioning reference. X and Y are millimetres measured from the top-left corner of each PDF page.">
<div class="overflow-hidden rounded-md border bg-muted/20"><iframe src="{{ route('admin.contract-templates.preview-source',$template,false) }}" class="h-[720px] w-full bg-white" title="Original PDF contract"></iframe></div>
</x-ui.form-section>

<x-ui.form-section title="PDF overlay fields" description="Add every system value that should appear on the PDF and finalize its exact position and size. These saved positions are used directly for every generated loan contract.">
<div class="mb-3 rounded-md border p-3 text-xs text-muted-foreground"><strong class="text-foreground">Position guide:</strong> Page selects the PDF page. X moves left/right, Y moves up/down, Width controls wrapping space, Font controls text size, and Line controls multiline spacing. Values are in millimetres except Font, which is in points.</div>
<div class="space-y-2">
@foreach($mappingRows as $i=>$mapping)
<div class="grid gap-2 rounded-md border p-2 md:grid-cols-12">
<div class="md:col-span-3"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">System field</label><select class="mf-input" name="mappings[{{ $i }}][field]"><option value="">Remove / do not fill</option>@foreach($fields as $field=>$label)<option value="{{ $field }}" @selected(($mapping['field'] ?? '')===$field)>{{ $label }}</option>@endforeach</select><input type="hidden" name="mappings[{{ $i }}][label]" value="{{ $mapping['label'] ?? 'PDF overlay' }}"></div>
<div class="md:col-span-1"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Page</label><input class="mf-input" type="number" min="1" max="{{ $pageCount }}" name="mappings[{{ $i }}][page]" value="{{ $mapping['page'] ?? 1 }}"></div>
<div class="md:col-span-1"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">X mm</label><input class="mf-input" type="number" step="0.5" min="0" name="mappings[{{ $i }}][x]" value="{{ $mapping['x'] ?? 20 }}"></div>
<div class="md:col-span-1"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Y mm</label><input class="mf-input" type="number" step="0.5" min="0" name="mappings[{{ $i }}][y]" value="{{ $mapping['y'] ?? 20 }}"></div>
<div class="md:col-span-2"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Width mm</label><input class="mf-input" type="number" step="0.5" min="5" name="mappings[{{ $i }}][width]" value="{{ $mapping['width'] ?? 80 }}"></div>
<div class="md:col-span-1"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Font</label><input class="mf-input" type="number" step="0.5" min="6" max="30" name="mappings[{{ $i }}][font_size]" value="{{ $mapping['font_size'] ?? 10 }}"></div>
<div class="md:col-span-1"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Line</label><input class="mf-input" type="number" step="0.5" min="3" max="20" name="mappings[{{ $i }}][line_height]" value="{{ $mapping['line_height'] ?? 5 }}"></div>
<div class="md:col-span-2"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Align</label><select class="mf-input" name="mappings[{{ $i }}][align]">@foreach($pdfAligns as $value=>$label)<option value="{{ $value }}" @selected(($mapping['align'] ?? 'L')===$value)>{{ $label }}</option>@endforeach</select></div>
</div>
@endforeach
@for($j=0;$j<12;$j++) @php $i=$startExtra+$j; @endphp
<div class="grid gap-2 rounded-md border border-dashed p-2 md:grid-cols-12">
<div class="md:col-span-3"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Add system field</label><select class="mf-input" name="mappings[{{ $i }}][field]"><option value="">Select field</option>@foreach($fields as $field=>$label)<option value="{{ $field }}">{{ $label }}</option>@endforeach</select><input type="hidden" name="mappings[{{ $i }}][label]" value="PDF overlay"></div>
<div class="md:col-span-1"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Page</label><input class="mf-input" type="number" min="1" max="{{ $pageCount }}" name="mappings[{{ $i }}][page]" value="1"></div>
<div class="md:col-span-1"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">X mm</label><input class="mf-input" type="number" step="0.5" min="0" name="mappings[{{ $i }}][x]" value="20"></div>
<div class="md:col-span-1"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Y mm</label><input class="mf-input" type="number" step="0.5" min="0" name="mappings[{{ $i }}][y]" value="20"></div>
<div class="md:col-span-2"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Width mm</label><input class="mf-input" type="number" step="0.5" min="5" name="mappings[{{ $i }}][width]" value="80"></div>
<div class="md:col-span-1"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Font</label><input class="mf-input" type="number" step="0.5" min="6" max="30" name="mappings[{{ $i }}][font_size]" value="10"></div>
<div class="md:col-span-1"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Line</label><input class="mf-input" type="number" step="0.5" min="3" max="20" name="mappings[{{ $i }}][line_height]" value="5"></div>
<div class="md:col-span-2"><label class="mb-1 block text-[10px] uppercase text-muted-foreground">Align</label><select class="mf-input" name="mappings[{{ $i }}][align]">@foreach($pdfAligns as $value=>$label)<option value="{{ $value }}">{{ $label }}</option>@endforeach</select></div>
</div>
@endfor
</div>
</x-ui.form-section>
@else
<x-ui.form-section title="Detected mappings & spacing" description="Fine-tune how each system value sits in the original Word line. Before/After are exact spaces. Turn on Trim source spacing when the uploaded contract already has unwanted spaces around the blank area. These settings are final for generated loan contracts.">
<div class="mf-table-frame"><table class="mf-table" style="width:1380px;min-width:1380px;table-layout:fixed"><colgroup><col style="width:440px"><col style="width:260px"><col style="width:210px"><col style="width:350px"><col style="width:120px"></colgroup><thead><tr><th>Contract location</th><th>System field</th><th>Fill method</th><th>Spacing</th><th>Remove</th></tr></thead><tbody>
@forelse($mappingRows as $i=>$mapping)
@php $block=$blocksById->get($mapping['block_id'] ?? ''); $mode=$mapping['mode'] ?? 'replace_blank'; $defaultBefore=$mode==='append'?1:0; @endphp
<tr><td style="min-width:440px"><input type="hidden" name="mappings[{{ $i }}][block_id]" value="{{ $mapping['block_id'] ?? '' }}"><input type="hidden" name="mappings[{{ $i }}][segment_index]" value="{{ $mapping['segment_index'] ?? -1 }}"><input type="hidden" name="mappings[{{ $i }}][label]" value="{{ $mapping['label'] ?? '' }}"><div class="text-xs font-medium">{{ $mapping['label'] ?? 'Detected field' }} · {{ $mapping['block_id'] ?? '' }}</div><div class="mt-1 max-w-xl text-xs text-muted-foreground">{{ str($block['text'] ?? ($mapping['source_text'] ?? ''))->limit(180) }}</div></td>
<td style="min-width:260px"><select class="mf-input" style="width:100%;min-width:0" name="mappings[{{ $i }}][field]"><option value="">Do not fill</option>@foreach($fields as $field=>$label)<option value="{{ $field }}" @selected(($mapping['field'] ?? '')===$field)>{{ $label }}</option>@endforeach</select></td>
<td style="min-width:210px"><select class="mf-input" style="width:100%;min-width:0" name="mappings[{{ $i }}][mode]">@foreach($modes as $value=>$label)<option value="{{ $value }}" @selected($mode===$value)>{{ $label }}</option>@endforeach</select></td>
<td style="width:350px;min-width:350px"><div style="display:grid;grid-template-columns:90px 90px 126px;gap:10px;min-width:326px"><div><label class="mb-1 block whitespace-nowrap text-[10px] uppercase text-muted-foreground">Before</label><input type="number" min="0" max="10" class="mf-input" style="width:90px" name="mappings[{{ $i }}][spaces_before]" value="{{ $mapping['spaces_before'] ?? $defaultBefore }}"></div><div><label class="mb-1 block whitespace-nowrap text-[10px] uppercase text-muted-foreground">After</label><input type="number" min="0" max="10" class="mf-input" style="width:90px" name="mappings[{{ $i }}][spaces_after]" value="{{ $mapping['spaces_after'] ?? 0 }}"></div><div><label class="mb-1 block whitespace-nowrap text-[10px] uppercase text-muted-foreground">Trim</label><select class="mf-input" style="width:126px" name="mappings[{{ $i }}][trim_surrounding]"><option value="0" @selected(!($mapping['trim_surrounding'] ?? false))>No</option><option value="1" @selected((bool)($mapping['trim_surrounding'] ?? false))>Yes</option></select></div></div></td>
<td style="min-width:120px;white-space:nowrap"><label class="inline-flex items-center gap-2 text-xs"><input type="checkbox" onchange="if(this.checked){this.closest('tr').querySelector('select[name$=&quot;[field]&quot;]').value='';}"> Clear</label></td></tr>
@empty<tr><td colspan="5" class="text-center text-muted-foreground">No fields were confidently detected. Use the manual mapping rows below.</td></tr>@endforelse
</tbody></table></div>
</x-ui.form-section>

<x-ui.form-section title="Additional manual mappings" description="Use these rows when the extractor missed a field. Spacing controls here are saved as the final defaults for every generated contract using this template.">
<div class="space-y-2">@for($j=0;$j<8;$j++) @php $i=$startExtra+$j; @endphp
<div class="grid gap-2 md:grid-cols-12 rounded-md border p-2"><div class="md:col-span-4"><select class="mf-input" name="mappings[{{ $i }}][block_id]"><option value="">Select extracted contract text</option>@foreach(($template->blocks ?? []) as $block)<option value="{{ $block['id'] }}">{{ $block['id'] }} · {{ str($block['text'])->squish()->limit(95) }}</option>@endforeach</select><input type="hidden" name="mappings[{{ $i }}][segment_index]" value="-1"><input type="hidden" name="mappings[{{ $i }}][label]" value="Manual mapping"></div><div class="md:col-span-3"><select class="mf-input" name="mappings[{{ $i }}][field]"><option value="">Select system field</option>@foreach($fields as $field=>$label)<option value="{{ $field }}">{{ $label }}</option>@endforeach</select></div><div class="md:col-span-2"><select class="mf-input" name="mappings[{{ $i }}][mode]">@foreach($modes as $value=>$label)<option value="{{ $value }}">{{ $label }}</option>@endforeach</select></div><div class="md:col-span-1"><input type="number" min="0" max="10" class="mf-input" name="mappings[{{ $i }}][spaces_before]" value="0" title="Spaces before"></div><div class="md:col-span-1"><input type="number" min="0" max="10" class="mf-input" name="mappings[{{ $i }}][spaces_after]" value="0" title="Spaces after"></div><div class="md:col-span-1"><select class="mf-input" name="mappings[{{ $i }}][trim_surrounding]" title="Trim source spacing"><option value="0">Keep</option><option value="1">Trim</option></select></div></div>
@endfor</div>
</x-ui.form-section>
<x-ui.form-section title="Extracted contract text" description="Read-only extraction for checking the uploaded Word content. Final contract generation always uses the original DOCX file, not this text preview."><pre class="max-h-[420px] overflow-auto whitespace-pre-wrap rounded-md border bg-muted/20 p-3 text-xs leading-5">{{ $template->extracted_text }}</pre></x-ui.form-section>
@endif

<x-ui.form-actions><a class="mf-btn" href="{{ route('admin.contract-templates.index') }}">Back</a><button class="mf-btn mf-btn-primary">{{ $isPdf?'Save PDF Field Positions':'Save Mapping & Spacing' }}</button></x-ui.form-actions>
</form></x-ui.form-shell>
@endsection