@extends('layouts.admin')

@section('title', 'Document Templates')

@section('page-title', 'Document Templates')

@section('content')
<div class="max-w-7xl mx-auto">
    <!-- Header -->
    <div class="mb-6">
        <h2 class="text-2xl font-bold text-gray-900">Document Templates</h2>
        <p class="text-sm text-gray-500 mt-1">Choose default templates for invoices, quotations, and receipts</p>
    </div>

    @if(session('success'))
        <div class="mb-6 p-4 bg-green-100 border border-green-200 text-green-800 rounded-lg flex items-center gap-2">
            <span class="material-symbols-outlined">check_circle</span>
            <span>{{ session('success') }}</span>
        </div>
    @endif

    @if(session('error'))
        <div class="mb-6 p-4 bg-red-100 border border-red-200 text-red-800 rounded-lg flex items-center gap-2">
            <span class="material-symbols-outlined">error</span>
            <span>{{ session('error') }}</span>
        </div>
    @endif

    <!-- Section A: Invoice Templates -->
    <div class="bg-white rounded-xl border border-gray-200 shadow-sm mb-6">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-bold text-gray-900 flex items-center gap-2">
                <span class="material-symbols-outlined text-primary">description</span>
                Invoice Templates
            </h3>
            <p class="text-sm text-gray-500 mt-1">Select the default template for invoice documents</p>
        </div>
        <div class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                @foreach($invoiceTemplates as $key => $template)
                    <div class="template-card group relative bg-white border-2 rounded-lg overflow-hidden transition-all {{ $defaultInvoiceTemplate === $key ? 'border-primary shadow-lg ring-2 ring-primary/20' : 'border-gray-200 hover:border-gray-300 hover:shadow-md' }}" data-template-type="invoice" data-template-key="{{ $key }}">
                        <!-- Template Preview -->
                        <div class="h-48 bg-gradient-to-br {{ $key === 'modern' ? 'from-blue-50 to-blue-100' : ($key === 'classic' ? 'from-gray-50 to-gray-100' : ($key === 'minimal' ? 'from-purple-50 to-purple-100' : 'from-indigo-50 to-indigo-100')) }} flex items-center justify-center border-b border-gray-200 relative overflow-hidden">
                            @if($key === 'modern')
                                <!-- Modern Corporate Preview -->
                                <img src="{{ asset('template/mod corporate.png') }}" alt="Modern Corporate Template Preview" class="w-full h-full object-cover">
                            @elseif($key === 'minimal')
                                <!-- Business Professional Preview -->
                                <img src="{{ asset('template/Inv Bus proff.png') }}" alt="Business Professional Template Preview" class="w-full h-full object-cover">
                            @elseif($key === 'classic')
                                <!-- Minimal Clean Preview -->
                                <img src="{{ asset('template/minal prev.png') }}" alt="Minimal Clean Template Preview" class="w-full h-full object-cover">
                            @else
                                <!-- Premium Branding Preview -->
                                <img src="{{ asset('template/premium brand.png') }}" alt="Premium Branding Template Preview" class="w-full h-full object-cover">
                            @endif
                            @if($defaultInvoiceTemplate === $key)
                                <div class="absolute top-2 right-2">
                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-semibold bg-primary text-white shadow-sm">
                                        <span class="material-symbols-outlined text-xs mr-1">check_circle</span>
                                        Default
                                    </span>
                                </div>
                            @endif
                        </div>
                        
                        <!-- Template Info -->
                        <div class="p-4">
                            <h4 class="text-sm font-semibold text-gray-900 mb-1">{{ $template['name'] }}</h4>
                            <p class="text-xs text-gray-500 mb-4 line-clamp-2">{{ $template['description'] }}</p>
                            
                            <button 
                                type="button"
                                onclick="setDefaultTemplate(this, 'invoice', '{{ $key }}')" 
                                class="w-full px-4 py-2 text-sm font-medium rounded-lg transition-colors {{ $defaultInvoiceTemplate === $key ? 'bg-gray-100 text-gray-500 cursor-not-allowed' : 'bg-primary text-white hover:bg-blue-600' }}"
                                {{ $defaultInvoiceTemplate === $key ? 'disabled' : '' }}
                            >
                                {{ $defaultInvoiceTemplate === $key ? 'Currently Active' : 'Set as Default' }}
                            </button>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
    </div>

    <!-- Section B: Quotation Templates -->
    <div class="bg-white rounded-xl border border-gray-200 shadow-sm mb-6">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-bold text-gray-900 flex items-center gap-2">
                <span class="material-symbols-outlined text-primary">receipt_long</span>
                Quotation Templates
            </h3>
            <p class="text-sm text-gray-500 mt-1">Select the default template for quotation documents</p>
        </div>
        <div class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                @foreach($quotationTemplates as $key => $template)
                    <div class="template-card group relative bg-white border-2 rounded-lg overflow-hidden transition-all {{ $defaultQuotationTemplate === $key ? 'border-primary shadow-lg ring-2 ring-primary/20' : 'border-gray-200 hover:border-gray-300 hover:shadow-md' }}" data-template-type="quotation" data-template-key="{{ $key }}">
                        <!-- Template Preview -->
                        @php
                            $quotationPreviewFile = match ($key) {
                                'modern' => 'Q-Corporate Quote.png',
                                'classic' => 'Q-sales proposal.png',
                                'minimal' => 'Q-clean estimate.png',
                                default => 'Q-premium-proposal.png',
                            };
                        @endphp
                        <div class="h-48 bg-gray-50 flex items-center justify-center border-b border-gray-200 relative overflow-hidden p-2">
                            <img
                                src="{{ asset('template/'.rawurlencode($quotationPreviewFile)) }}"
                                alt="{{ $template['name'] ?? 'Quotation' }} template preview"
                                class="h-full w-full object-contain object-top rounded-sm shadow-sm ring-1 ring-gray-200/80"
                                loading="lazy"
                            />
                            @if($defaultQuotationTemplate === $key)
                                <div class="absolute top-2 right-2">
                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-semibold bg-primary text-white shadow-sm">
                                        <span class="material-symbols-outlined text-xs mr-1">check_circle</span>
                                        Default
                                    </span>
                                </div>
                            @endif
                        </div>
                
                <!-- Template Info -->
                        <div class="p-4">
                            <h4 class="text-sm font-semibold text-gray-900 mb-1">{{ $template['name'] }}</h4>
                            <p class="text-xs text-gray-500 mb-4 line-clamp-2">{{ $template['description'] }}</p>
                            
                            <button
                                type="button"
                                onclick="setDefaultTemplate(this, 'quotation', '{{ $key }}')"
                                class="w-full px-4 py-2 text-sm font-medium rounded-lg transition-colors {{ $defaultQuotationTemplate === $key ? 'bg-gray-100 text-gray-500 cursor-not-allowed' : 'bg-primary text-white hover:bg-blue-600' }}"
                                {{ $defaultQuotationTemplate === $key ? 'disabled' : '' }}
                            >
                                {{ $defaultQuotationTemplate === $key ? 'Currently Active' : 'Set as Default' }}
                            </button>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
    </div>

    <!-- Section C: Receipt Templates -->
    <div class="bg-white rounded-xl border border-gray-200 shadow-sm mb-6">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-bold text-gray-900 flex items-center gap-2">
                <span class="material-symbols-outlined text-primary">receipt</span>
                Receipt Templates
            </h3>
            <p class="text-sm text-gray-500 mt-1">Select the default template for receipt documents</p>
        </div>
                <div class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                @foreach($receiptTemplates as $key => $template)
                    <div class="template-card group relative bg-white border-2 rounded-lg overflow-hidden transition-all {{ $defaultReceiptTemplate === $key ? 'border-primary shadow-lg ring-2 ring-primary/20' : 'border-gray-200 hover:border-gray-300 hover:shadow-md' }}" data-template-type="receipt" data-template-key="{{ $key }}">
                        <!-- Template Preview -->
                        <div class="h-48 bg-gradient-to-br {{ $key === 'modern' ? 'from-green-50 to-green-100' : ($key === 'classic' ? 'from-gray-50 to-gray-100' : ($key === 'minimal' ? 'from-blue-50 to-blue-100' : 'from-emerald-50 to-emerald-100')) }} flex items-center justify-center border-b border-gray-200 relative overflow-hidden">
                            @if($key === 'modern')
                                <!-- Standard Payment Receipt Preview -->
                                <img src="{{ asset('template/Standard Payment reciept.png') }}" alt="Standard Payment Receipt Template Preview" class="w-full h-full object-cover">
                            @elseif($key === 'classic')
                                <!-- POS Style Receipt Preview -->
                                <img src="{{ asset('template/POS Style Receipt.png') }}" alt="POS Style Receipt Template Preview" class="w-full h-full object-cover">
                            @elseif($key === 'minimal')
                                <!-- Business Receipt Preview -->
                                <img src="{{ asset('template/Business Receipt.png') }}" alt="Business Receipt Template Preview" class="w-full h-full object-cover">
                            @else
                                <!-- Modern Branded Receipt Preview -->
                                <img src="{{ asset('template/Modern Branded Receipt.png') }}" alt="Modern Branded Receipt Template Preview" class="w-full h-full object-cover">
                            @endif
                            @if($defaultReceiptTemplate === $key)
                                <div class="absolute top-2 right-2">
                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-semibold bg-primary text-white shadow-sm">
                                        <span class="material-symbols-outlined text-xs mr-1">check_circle</span>
                                        Default
                                    </span>
                                </div>
                            @endif
                        </div>
                        
                        <!-- Template Info -->
                        <div class="p-4">
                            <h4 class="text-sm font-semibold text-gray-900 mb-1">{{ $template['name'] }}</h4>
                            <p class="text-xs text-gray-500 mb-4 line-clamp-2">{{ $template['description'] }}</p>
                            
                            <button 
                                type="button"
                                onclick="setDefaultTemplate(this, 'receipt', '{{ $key }}')" 
                                class="w-full px-4 py-2 text-sm font-medium rounded-lg transition-colors {{ $defaultReceiptTemplate === $key ? 'bg-gray-100 text-gray-500 cursor-not-allowed' : 'bg-primary text-white hover:bg-blue-600' }}"
                                {{ $defaultReceiptTemplate === $key ? 'disabled' : '' }}
                            >
                                {{ $defaultReceiptTemplate === $key ? 'Currently Active' : 'Set as Default' }}
                            </button>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
    </div>
</div>

<script>
async function setDefaultTemplate(buttonEl, type, templateKey) {
    const button = buttonEl?.closest?.('button') ?? buttonEl;
    if (!button || button.disabled) {
        return;
    }

    const originalHtml = button.innerHTML;
    button.disabled = true;
    button.innerHTML = '<span class="material-symbols-outlined animate-spin text-sm">sync</span>';

    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
    if (!csrfToken) {
        alert('CSRF token not found. Please refresh the page and try again.');
        button.disabled = false;
        button.innerHTML = originalHtml;
        return;
    }

    try {
        const response = await fetch('{{ route("admin.invoice-templates.set-default") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                type: type,
                template: templateKey
            })
        });

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: 'Server error occurred' }));
            throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        if (data.success) {
            location.reload();
        } else {
            alert(data.message || 'Failed to set default template');
            button.disabled = false;
            button.innerHTML = originalHtml;
        }
    } catch (error) {
        console.error('Error:', error);

        if (error.message && error.message.includes('CSRF')) {
            alert('Session expired. Please refresh the page and try again.');
            location.reload();
        } else {
            alert('An error occurred while setting the default template: ' + error.message);
            button.disabled = false;
            button.innerHTML = originalHtml;
        }
    }
}
</script>
@endsection
