@extends('layouts.admin')

@section('title', 'Edit template: ' . $template->name)

@section('page-title', 'Edit email template')

@section('breadcrumbs')
    <a href="{{ route('admin.reminders.email-templates.index') }}" class="hover:text-primary">Templates</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">{{ $template->name }}</span>
@endsection

@section('content')
<div class="max-w-6xl mx-auto">
    @if(session('success'))
        <div class="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800 mb-6">{{ session('success') }}</div>
    @endif

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="lg:col-span-2 space-y-6">
            <form method="POST" action="{{ route('admin.reminders.email-templates.update', $template) }}" class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 space-y-4">
                @csrf
                @method('PUT')

                <div>
                    <label for="name" class="block text-sm font-medium text-gray-700 mb-1">Name</label>
                    <input type="text" name="name" id="name" value="{{ old('name', $template->name) }}" required class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:ring-1 focus:ring-primary">
                    @error('name')<p class="text-xs text-red-600 mt-1">{{ $message }}</p>@enderror
                </div>

                <div>
                    <label for="subject" class="block text-sm font-medium text-gray-700 mb-1">Subject</label>
                    <input type="text" name="subject" id="subject" value="{{ old('subject', $template->subject) }}" required class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:ring-1 focus:ring-primary">
                    @error('subject')<p class="text-xs text-red-600 mt-1">{{ $message }}</p>@enderror
                </div>

                <div>
                    <label for="body" class="block text-sm font-medium text-gray-700 mb-1">HTML body</label>
                    <textarea name="body" id="body" rows="18" required class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm font-mono focus:border-primary focus:ring-1 focus:ring-primary">{{ old('body', $template->body) }}</textarea>
                    @error('body')<p class="text-xs text-red-600 mt-1">{{ $message }}</p>@enderror
                </div>

                <div class="flex items-center gap-2">
                    <input type="hidden" name="is_active" value="0">
                    <input type="checkbox" name="is_active" value="1" id="is_active" class="rounded border-gray-300 text-primary focus:ring-primary" @checked(old('is_active', $template->is_active))>
                    <label for="is_active" class="text-sm text-gray-700">Template active</label>
                </div>

                <div class="flex flex-wrap gap-3 pt-2">
                    <button type="submit" class="px-5 py-2.5 rounded-lg bg-primary text-white text-sm font-semibold">Save</button>
                    <button type="button" id="tpl-preview-btn" class="px-5 py-2.5 rounded-lg border border-gray-300 text-sm font-semibold text-gray-700 hover:bg-gray-50">Preview</button>
                </div>
            </form>

            <form method="POST" action="{{ route('admin.reminders.email-templates.reset', $template) }}" onsubmit="return confirm('Reset this template to the default from the seeder?');" class="bg-amber-50 rounded-xl border border-amber-200 p-4 flex flex-wrap items-center justify-between gap-3">
                @csrf
                <p class="text-sm text-amber-900">Restore default HTML and subject from <code class="text-xs bg-white/80 px-1 rounded">ReminderSystemSeeder</code>.</p>
                <button type="submit" class="px-4 py-2 rounded-lg bg-amber-600 text-white text-sm font-semibold shrink-0">Reset to default</button>
            </form>

            <div id="tpl-preview-panel" class="hidden bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h3 class="text-sm font-bold text-gray-900 mb-2">Preview</h3>
                <p class="text-xs text-gray-500 mb-3" id="tpl-preview-subject"></p>
                <div class="border border-gray-200 rounded-lg p-4 max-h-[480px] overflow-auto text-sm prose prose-sm max-w-none" id="tpl-preview-body"></div>
            </div>
        </div>

        <aside class="space-y-4">
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5 sticky top-4">
                <h3 class="text-sm font-bold text-gray-900 mb-3">Placeholders</h3>
                <p class="text-xs text-gray-500 mb-3">Use curly braces: <code class="bg-gray-100 px-1 rounded">{key}</code>. Legacy <code class="bg-gray-100 px-1">{{ '{{key}}' }}</code> also works.</p>
                <ul class="text-xs text-gray-600 space-y-2 font-mono">
                    <li class="font-sans font-semibold text-gray-800 text-[11px] uppercase tracking-wide">General</li>
                    <li>{customer_name}</li>
                    <li>{company_name}</li>
                    <li>{company_email}</li>
                    <li>{company_phone}</li>
                    <li>{company_address}</li>
                    <li>{today_date}</li>
                    <li class="font-sans font-semibold text-gray-800 text-[11px] uppercase tracking-wide pt-2">Invoice</li>
                    <li>{invoice_number}</li>
                    <li>{invoice_total}</li>
                    <li>{invoice_due_date}</li>
                    <li>{invoice_status}</li>
                    <li>{invoice_balance}</li>
                    <li>{invoice_view_link}</li>
                    <li class="font-sans font-semibold text-gray-800 text-[11px] uppercase tracking-wide pt-2">Quotation</li>
                    <li>{quotation_number}</li>
                    <li>{quotation_total}</li>
                    <li>{quotation_expiry_date}</li>
                    <li>{quotation_view_link}</li>
                    <li class="font-sans font-semibold text-gray-800 text-[11px] uppercase tracking-wide pt-2">Payment</li>
                    <li>{payment_amount}</li>
                    <li>{payment_date}</li>
                    <li>{payment_reference}</li>
                    <li class="font-sans font-semibold text-gray-800 text-[11px] uppercase tracking-wide pt-2">Purchase</li>
                    <li>{purchase_order_number}</li>
                    <li>{supplier_name}</li>
                    <li>{purchase_total}</li>
                </ul>
            </div>
        </aside>
    </div>
</div>

@push('scripts')
<script>
(function () {
    var btn = document.getElementById('tpl-preview-btn');
    var panel = document.getElementById('tpl-preview-panel');
    var subEl = document.getElementById('tpl-preview-subject');
    var bodyEl = document.getElementById('tpl-preview-body');
    var bodyInput = document.getElementById('body');
    var subjectInput = document.getElementById('subject');
    if (!btn || !panel) return;
    btn.addEventListener('click', function () {
        var token = document.querySelector('meta[name="csrf-token"]');
        var fd = new FormData();
        fd.append('_token', token ? token.content : '');
        fd.append('subject', subjectInput ? subjectInput.value : '');
        fd.append('body', bodyInput ? bodyInput.value : '');
        fetch('{{ route('admin.reminders.email-templates.preview', $template) }}', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
            body: fd
        }).then(function (r) { return r.json(); })
        .then(function (data) {
            panel.classList.remove('hidden');
            if (subEl) subEl.textContent = data.subject || '';
            if (bodyEl) bodyEl.innerHTML = data.body || '';
        }).catch(function () {
            alert('Preview failed');
        });
    });
})();
</script>
@endpush
@endsection
