@extends('admin.layout')

@section('title', 'Edit Certificate Template')

@push('styles')
<style>
    .cert-edit-grid {
        display: grid;
        grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr);
        gap: 1.25rem;
        align-items: start;
    }
    .cert-edit-card {
        padding: 1.35rem 1.5rem;
    }
    .cert-edit-card h2 {
        font-size: 1rem;
        font-weight: 700;
        margin: 0 0 1.15rem;
    }
    .form-grid-2 {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 1rem;
    }
    .req::after { content: " *"; color: #EF4444; }
    .role-checks {
        display: flex;
        flex-wrap: wrap;
        gap: .55rem .85rem;
    }
    .role-checks label {
        display: inline-flex;
        align-items: center;
        gap: .4rem;
        font-size: .875rem;
        font-weight: 500;
        color: var(--ink);
        cursor: pointer;
    }
    .placeholder-hint {
        font-size: .78rem;
        color: var(--muted);
        line-height: 1.45;
        margin-top: .45rem;
    }
    .placeholder-hint code {
        font-family: "JetBrains Mono", ui-monospace, monospace;
        font-size: .72rem;
        background: #F1F5F9;
        padding: .1rem .35rem;
        border-radius: 4px;
        color: #334155;
    }
    .upload-zone {
        border: 2px dashed var(--border);
        border-radius: 12px;
        padding: 1.15rem;
        text-align: center;
        background: #FAFBFC;
        font-size: .82rem;
        color: var(--muted);
        cursor: pointer;
        display: block;
    }
    .upload-zone:hover { border-color: var(--primary); color: var(--ink); }
    .bg-current {
        display: flex;
        align-items: center;
        gap: .75rem;
        margin-bottom: .75rem;
        padding: .65rem .75rem;
        border: 1px solid var(--border);
        border-radius: 10px;
        background: #fff;
    }
    .bg-current img {
        width: 96px;
        height: 68px;
        object-fit: cover;
        border-radius: 6px;
        border: 1px solid var(--border);
        flex-shrink: 0;
    }
    .cert-preview-wrap {
        background: linear-gradient(160deg, #EEF2FF, #F8FAFC 55%);
        border: 1px solid var(--border);
        border-radius: 14px;
        padding: 1rem;
        overflow: auto;
    }
    .cert-preview {
        width: 100%;
        aspect-ratio: 297 / 210;
        background: #fff;
        border-radius: 6px;
        box-shadow: 0 10px 30px rgba(23, 26, 36, .08);
        position: relative;
        overflow: hidden;
        box-sizing: border-box;
    }
    .cert-preview:not(.has-bg)::after {
        content: "";
        position: absolute;
        inset: 3.5%;
        border: 1.5px solid #8C7BFF;
        pointer-events: none;
        border-radius: 2px;
        z-index: 2;
    }
    .cert-preview:not(.has-bg) {
        border: 2px solid #171A24;
    }
    .cert-preview.has-bg::after { display: none; }
    .pv-bg {
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
        object-position: center;
        display: none;
        z-index: 0;
    }
    .cert-preview.has-bg .pv-bg { display: block; }
    .pv-content {
        position: relative;
        z-index: 2;
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-start;
        text-align: center;
        padding: 18% 14% 12%;
    }
    .cert-preview.has-bg .pv-content {
        padding: 18% 14% 12%;
        display: flex;
    }
    .cert-preview.has-bg .pv-title,
    .cert-preview.has-bg .pv-lead,
    .cert-preview.has-bg .pv-name,
    .cert-preview.has-bg .pv-ic,
    .cert-preview.has-bg .pv-body,
    .cert-preview.has-bg .pv-connector,
    .cert-preview.has-bg .pv-event-name,
    .cert-preview.has-bg .pv-date {
        text-shadow: 0 1px 2px rgba(255,255,255,.55);
    }
    .cert-preview .pv-title {
        font-size: clamp(1rem, 2.5vw, 1.45rem);
        font-weight: 800;
        letter-spacing: .06em;
        text-transform: uppercase;
        margin: 0 0 .35rem;
        color: #1A237E;
        line-height: 1.1;
    }
    .cert-preview .pv-lead {
        font-size: clamp(.55rem, 1.15vw, .72rem);
        font-weight: 600;
        letter-spacing: .1em;
        text-transform: uppercase;
        color: #1A237E;
        margin: .45rem 0 .35rem;
    }
    .cert-preview .pv-name {
        font-size: clamp(1.05rem, 2.8vw, 1.7rem);
        font-weight: 700;
        font-family: Georgia, "Times New Roman", serif;
        font-style: italic;
        line-height: 1.15;
        margin: .35rem 0 .25rem;
        color: #171A24;
    }
    .cert-preview .pv-rule {
        width: 42%;
        max-width: 160px;
        height: 0;
        border-top: 1.5px solid #C9A227;
        margin: .35rem auto .45rem;
        position: relative;
    }
    .cert-preview .pv-ic {
        font-size: clamp(.58rem, 1.2vw, .75rem);
        font-weight: 600;
        color: #1A237E;
        margin: .2rem 0;
    }
    .cert-preview .pv-connector {
        font-size: clamp(.5rem, 1vw, .65rem);
        font-style: italic;
        color: #5A6A9A;
        margin: .3rem 0 .15rem;
    }
    .cert-preview .pv-event-name {
        font-size: clamp(.7rem, 1.45vw, .9rem);
        font-weight: 700;
        color: #171A24;
        line-height: 1.3;
        margin: 0 0 .15rem;
    }
    .cert-preview .pv-date {
        font-size: clamp(.65rem, 1.3vw, .82rem);
        font-weight: 700;
        color: #1A237E;
        margin: 0;
    }
    .cert-preview .pv-footer {
        position: absolute;
        left: 6%;
        right: 6%;
        bottom: 5%;
        z-index: 3;
        width: auto;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: flex-end;
        gap: .2rem;
        margin: 0;
        padding: 0;
        font-family: "JetBrains Mono", ui-monospace, monospace;
        font-size: clamp(.45rem, .95vw, .58rem);
        color: #6B7280;
    }
    .cert-preview .pv-code {
        font-weight: 700;
        color: #374151;
        text-align: left;
    }
    @media (max-width: 992px) {
        .cert-edit-grid { grid-template-columns: 1fr; }
        .form-grid-2 { grid-template-columns: 1fr; }
    }
</style>
@endpush

@section('content')
@php
    $selectedRoles = old('roles', $template['roles']);
    $bgUrl = $template['background_url'] ?? null;
    $previewBody = strtr(old('body', $template['body']), [
        '{eventName}' => $event->fullName(),
        '{date}' => now()->format('j F Y'),
        '{role}' => strtolower($selectedRoles[0] ?? 'visitor'),
        '{sessions}' => '3',
        '{sessionLabel}' => 'sessions',
        '{stamps}' => '5',
        '{boothCount}' => '8',
    ]);
@endphp

<div class="pg-head">
    <div>
        <a href="{{ route('mexco.admin.certificates', ['tab' => 'templates']) }}" class="cell-sub d-inline-block mb-2" style="text-decoration:none">&larr; Back to certificates</a>
        <h1>Edit template</h1>
        <p>Customise how this certificate looks for {{ $event->name }}.</p>
    </div>
</div>

<form method="POST"
      action="{{ route('mexco.admin.certificates.update', $template['key']) }}"
      id="certTemplateForm"
      enctype="multipart/form-data">
    @csrf @method('PUT')

    <div class="cert-edit-grid">
        <div class="card cert-edit-card">
            <h2>Template details</h2>

            <div class="form-row">
                <label class="form-label">Certificate background image</label>
                @if($bgUrl)
                    <div class="bg-current" id="bgCurrent">
                        <img src="{{ $bgUrl }}" alt="Current background">
                        <div>
                            <div class="cell-name" style="font-size:.875rem">Current background</div>
                            <input type="hidden" name="remove_background" id="fldRemoveBg" value="0">
                            <button type="button" class="btn btn-outline-danger btn-sm mt-2" id="btnRemoveBg">
                                Remove template
                            </button>
                            <p class="placeholder-hint mt-1 mb-0">Removes only the uploaded certificate background image (not this certificate template). Click Save to apply.</p>
                        </div>
                    </div>
                @endif
                <label class="upload-zone" for="fldBackground" id="bgZone">
                    <div id="bgZoneLabel">{{ $bgUrl ? 'Replace image (PNG, JPG, WEBP · max 5MB)' : 'Upload A4 landscape image (PNG, JPG, WEBP · max 5MB)' }}</div>
                    <div class="mt-1" style="font-size:.75rem">Design tip: leave the centre clear for name and text</div>
                </label>
                <input type="file" name="background" id="fldBackground" class="d-none" accept="image/png,image/jpeg,image/jpg,image/webp">
                @error('background') <div class="text-danger mt-1" style="font-size:.8rem">{{ $message }}</div> @enderror
            </div>

            <div class="form-row">
                <label class="form-label req">Template name</label>
                <input type="text" name="name" id="fldName" class="form-input" value="{{ old('name', $template['name']) }}" required maxlength="255">
                @error('name') <div class="text-danger mt-1" style="font-size:.8rem">{{ $message }}</div> @enderror
            </div>

            <div class="form-row">
                <label class="form-label">Description</label>
                <input type="text" name="description" id="fldDescription" class="form-input" value="{{ old('description', $template['description']) }}" maxlength="500">
            </div>

            <div class="form-row">
                <label class="form-label req">Applies to roles</label>
                <div class="role-checks">
                    @forelse($roleNames as $role)
                        <label>
                            <input type="checkbox" name="roles[]" value="{{ $role }}" @checked(in_array($role, $selectedRoles, true))>
                            {{ $role }}
                        </label>
                    @empty
                        <span class="cell-sub">No roles configured yet. Add roles under Roles &amp; Access.</span>
                    @endforelse
                </div>
                <p class="placeholder-hint mt-1 mb-0">Note: each role checkbox can be used on only one template. Certificate names must also be unique.</p>
                @error('roles') <div class="text-danger mt-1" style="font-size:.8rem">{{ $message }}</div> @enderror
            </div>

            <div class="form-row">
                <label class="form-label req">Certificate title</label>
                <input type="text" name="title" id="fldTitle" class="form-input" value="{{ old('title', $template['title']) }}" required maxlength="255">
            </div>

            <div class="form-row">
                <label class="form-label req">Lead line</label>
                <input type="text" name="lead" id="fldLead" class="form-input" value="{{ old('lead', $template['lead']) }}" required maxlength="255">
            </div>

            <div class="form-row">
                <label class="form-label req">Body text</label>
                <input type="text" name="body" id="fldBody" class="form-input" value="{{ old('body', $template['body']) }}" required maxlength="255" placeholder="in attendance of">
                <p class="placeholder-hint">
                    Shown above the event name (e.g. <code>in attendance of</code>).
                    Optional placeholders: <code>{eventName}</code> <code>{date}</code> <code>{role}</code>
                </p>
            </div>

            <div class="d-flex justify-content-end gap-2 mt-3">
                <a href="{{ route('mexco.admin.certificates', ['tab' => 'templates']) }}" class="btn btn-outline-secondary">Cancel</a>
                <button type="submit" class="btn-purple">Save template</button>
            </div>
        </div>

        <div class="card cert-edit-card">
            <h2>Live preview</h2>
            <p class="cell-sub mb-2">Background image fills the certificate; all form text overlays on top. Issued date and cert code stack in the footer.</p>
            <div class="cert-preview-wrap">
                <div class="cert-preview {{ $bgUrl ? 'has-bg' : '' }}" id="certPreview">
                    <img class="pv-bg" id="pvBg" src="{{ $bgUrl }}" alt="" @if(!$bgUrl) style="display:none" @endif>
                    <div class="pv-content">
                        <div class="pv-static pv-title" id="pvTitle">{{ old('title', $template['title']) }}</div>
                        <div class="pv-static pv-lead" id="pvLead">{{ old('lead', $template['lead']) }}</div>
                        <div class="pv-name">Sample Participant</div>
                        <div class="pv-static pv-rule"></div>
                        <div class="pv-ic">IC NO. 900101015555</div>
                        <div class="pv-connector pv-body" id="pvBody">{{ old('body', $template['body']) }}</div>
                        <div class="pv-event-name" id="pvEventName">{{ $event->fullName() }}</div>
                        <div class="pv-static pv-connector">on</div>
                        <div class="pv-date" id="pvDate">{{ now()->format('j F Y') }}</div>
                        <div class="pv-footer">
                            <div class="pv-issued">Issued {{ now()->format('j F Y') }}</div>
                            <div class="pv-code">CERT-SAMPLE-0001</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
@endsection

@push('scripts')
<script>
(function () {
    const eventName = @json($event->fullName());
    const savedBg = @json($bgUrl);
    const title = document.getElementById('fldTitle');
    const lead = document.getElementById('fldLead');
    const body = document.getElementById('fldBody');
    const bgInput = document.getElementById('fldBackground');
    const removeBg = document.getElementById('fldRemoveBg');
    const btnRemoveBg = document.getElementById('btnRemoveBg');
    const bgCurrent = document.getElementById('bgCurrent');
    const preview = document.getElementById('certPreview');
    const pvBg = document.getElementById('pvBg');
    const pvTitle = document.getElementById('pvTitle');
    const pvLead = document.getElementById('pvLead');
    const pvBody = document.getElementById('pvBody');
    const bgZoneLabel = document.getElementById('bgZoneLabel');
    let objectUrl = null;
    let markedForRemoval = false;

    function applyBackground(url) {
        if (url) {
            preview.classList.add('has-bg');
            pvBg.src = url;
            pvBg.style.display = 'block';
        } else {
            preview.classList.remove('has-bg');
            pvBg.removeAttribute('src');
            pvBg.style.display = 'none';
        }
    }

    function syncBackground() {
        if (markedForRemoval) {
            applyBackground(null);
            return;
        }
        if (bgInput.files && bgInput.files[0]) {
            if (objectUrl) URL.revokeObjectURL(objectUrl);
            objectUrl = URL.createObjectURL(bgInput.files[0]);
            applyBackground(objectUrl);
            return;
        }
        applyBackground(savedBg || null);
    }

    function sync() {
        pvTitle.textContent = title.value || 'Certificate of Participation';
        pvLead.textContent = lead.value || 'This certificate is awarded to';
        pvBody.textContent = (body.value || '').trim() || 'in attendance of';
    }

    bgInput.addEventListener('change', function () {
        if (this.files[0]) {
            bgZoneLabel.textContent = this.files[0].name;
            markedForRemoval = false;
            if (removeBg) removeBg.value = '0';
            if (bgCurrent) bgCurrent.style.display = '';
            if (btnRemoveBg) btnRemoveBg.textContent = 'Remove template';
        }
        syncBackground();
    });

    if (btnRemoveBg && removeBg) {
        btnRemoveBg.addEventListener('click', function () {
            markedForRemoval = true;
            removeBg.value = '1';
            bgInput.value = '';
            bgZoneLabel.textContent = 'Upload A4 landscape image (PNG, JPG, WEBP · max 5MB)';
            if (bgCurrent) bgCurrent.style.opacity = '0.45';
            btnRemoveBg.textContent = 'Marked for removal';
            syncBackground();
        });
    }

    ['input', 'change'].forEach(function (evt) {
        [title, lead, body].forEach(function (el) {
            el.addEventListener(evt, sync);
        });
    });
})();
</script>
@endpush
