@extends('admin.layouts.app')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h3 class="card-title">Template Builder</h3>
                        <div>
                            <a href="{{ route('admin.template-builder.create') }}" class="btn btn-primary">
                                <i class="fas fa-plus"></i> Create New Template
                            </a>
                            <button type="button" class="btn btn-outline-primary" data-toggle="modal" data-target="#importModal">
                                <i class="fas fa-download"></i> Import Template
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    @if(session('success'))
                        <div class="alert alert-success alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            {{ session('success') }}
                        </div>
                    @endif

                    @if(session('error'))
                        <div class="alert alert-danger alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            {{ session('error') }}
                        </div>
                    @endif

                    <!-- Template Categories -->
                    <div class="mb-4">
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-secondary active" data-category="all">All</button>
                            <button type="button" class="btn btn-outline-secondary" data-category="general">General</button>
                            <button type="button" class="btn btn-outline-secondary" data-category="academic">Academic</button>
                            <button type="button" class="btn btn-outline-secondary" data-category="professional">Professional</button>
                            <button type="button" class="btn btn-outline-secondary" data-category="training">Training</button>
                        </div>
                    </div>

                    <!-- Templates Grid -->
                    <div class="row" id="templates-grid">
                        @forelse($templates as $template)
                            <div class="col-lg-4 col-md-6 mb-4 template-item" data-category="{{ $template->category }}">
                                <div class="card h-100 template-card">
                                    <div class="template-preview">
                                        @if($template->background_image)
                                            <img src="{{ $template->background_url }}" class="card-img-top" alt="{{ $template->name }}" style="height: 200px; object-fit: cover;">
                                        @else
                                            <div class="card-img-top bg-light d-flex align-items-center justify-content-center" style="height: 200px;">
                                                <i class="fas fa-image fa-3x text-muted"></i>
                                            </div>
                                        @endif
                                        <div class="template-overlay">
                                            <div class="btn-group-vertical">
                                                <a href="{{ route('admin.template-builder.show', $template) }}" class="btn btn-sm btn-info">
                                                    <i class="fas fa-eye"></i> Preview
                                                </a>
                                                <a href="{{ route('admin.template-builder.edit', $template) }}" class="btn btn-sm btn-primary">
                                                    <i class="fas fa-edit"></i> Edit
                                                </a>
                                                <button type="button" class="btn btn-sm btn-success preview-btn"
                                                        data-template-id="{{ $template->id }}"
                                                        data-template-name="{{ $template->name }}">
                                                    <i class="fas fa-magic"></i> Test
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <h5 class="card-title">{{ $template->name }}</h5>
                                        @if($template->description)
                                            <p class="card-text text-muted">{{ Str::limit($template->description, 100) }}</p>
                                        @endif
                                        <div class="template-meta">
                                            <span class="badge badge-{{ $template->is_active ? 'success' : 'secondary' }} mr-2">
                                                {{ $template->is_active ? 'Active' : 'Inactive' }}
                                            </span>
                                            <span class="badge badge-info mr-2">{{ $template->category }}</span>
                                            <span class="badge badge-light">{{ $template->width }}×{{ $template->height }}</span>
                                        </div>
                                        <div class="template-stats mt-2">
                                            <small class="text-muted">
                                                <i class="fas fa-fields"></i> {{ count($template->template_fields) }} fields
                                                @if($template->certificates_count)
                                                    • <i class="fas fa-certificate"></i> {{ $template->certificates_count }} generated
                                                @endif
                                            </small>
                                        </div>
                                    </div>
                                    <div class="card-footer">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <small class="text-muted">
                                                Created {{ $template->created_at->diffForHumans() }}
                                                @if($template->creator)
                                                    by {{ $template->creator->full_name }}
                                                @endif
                                            </small>
                                            <div class="btn-group">
                                                <a href="{{ route('admin.template-builder.duplicate', $template) }}"
                                                   class="btn btn-sm btn-outline-secondary"
                                                   title="Duplicate">
                                                    <i class="fas fa-copy"></i>
                                                </a>
                                                <a href="{{ route('admin.template-builder.export', $template) }}"
                                                   class="btn btn-sm btn-outline-info"
                                                   title="Export">
                                                    <i class="fas fa-download"></i>
                                                </a>
                                                <form action="{{ route('admin.template-builder.destroy', $template) }}"
                                                      method="POST"
                                                      class="d-inline"
                                                      onsubmit="return confirm('Are you sure you want to delete this template?')">
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @empty
                            <div class="col-12">
                                <div class="text-center py-5">
                                    <i class="fas fa-paint-brush fa-3x text-muted mb-3"></i>
                                    <h5>No Templates Found</h5>
                                    <p class="text-muted">Create your first certificate template to get started.</p>
                                    <a href="{{ route('admin.template-builder.create') }}" class="btn btn-primary">
                                        <i class="fas fa-plus"></i> Create Template
                                    </a>
                                </div>
                            </div>
                        @endforelse
                    </div>

                    <!-- Pagination -->
                    @if($templates->hasPages())
                        <div class="d-flex justify-content-center">
                            {{ $templates->links() }}
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Import Modal -->
<div class="modal fade" id="importModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Import Template</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form action="{{ route('admin.template-builder.import') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-body">
                    <div class="form-group">
                        <label for="template_file">Template File (JSON)</label>
                        <input type="file" name="template_file" id="template_file" class="form-control-file" accept=".json" required>
                        <small class="form-text text-muted">
                            Upload a previously exported template file (.json format)
                        </small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Import Template</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Test Template Modal -->
<div class="modal fade" id="testTemplateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Test Template: <span id="testTemplateName"></span></h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="testTemplateForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="test_student_name">Student Name *</label>
                                <input type="text" name="student_name" id="test_student_name" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label for="test_course_name">Course Name</label>
                                <input type="text" name="course_name" id="test_course_name" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="test_graduation_date">Graduation Date</label>
                                <input type="date" name="graduation_date" id="test_graduation_date" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="test_instructor_name">Instructor Name</label>
                                <input type="text" name="instructor_name" id="test_instructor_name" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="test_organization_name">Organization Name</label>
                                <input type="text" name="organization_name" id="test_organization_name" class="form-control">
                            </div>
                            <div class="form-group">
                                <button type="button" class="btn btn-primary btn-block" id="generateTestBtn">
                                    <i class="fas fa-magic"></i> Generate Test Certificate
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
                <div id="testResult" class="mt-3" style="display: none;">
                    <div class="text-center">
                        <img id="testCertificateImage" class="img-fluid border rounded" alt="Test Certificate">
                        <div class="mt-2">
                            <a href="#" id="testDownloadBtn" class="btn btn-success">
                                <i class="fas fa-download"></i> Download
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
.template-card {
    transition: transform 0.2s, box-shadow 0.2s;
}

.template-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.template-preview {
    position: relative;
    overflow: hidden;
}

.template-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
}

.template-card:hover .template-overlay {
    opacity: 1;
}

.template-overlay .btn-group-vertical {
    gap: 10px;
}

.template-overlay .btn {
    min-width: 120px;
}

.template-meta .badge {
    font-size: 0.75rem;
}

.template-stats {
    font-size: 0.875rem;
}
</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    // Category filtering
    $('[data-category]').click(function() {
        const category = $(this).data('category');

        $('[data-category]').removeClass('active');
        $(this).addClass('active');

        if (category === 'all') {
            $('.template-item').show();
        } else {
            $('.template-item').hide();
            $(`.template-item[data-category="${category}"]`).show();
        }
    });

    // Test template functionality
    $('.preview-btn').click(function() {
        const templateId = $(this).data('template-id');
        const templateName = $(this).data('template-name');

        $('#testTemplateName').text(templateName);
        $('#testTemplateForm').attr('data-template-id', templateId);
        $('#testResult').hide();
        $('#testTemplateModal').modal('show');
    });

    // Generate test certificate
    $('#generateTestBtn').click(function() {
        const templateId = $('#testTemplateForm').data('template-id');
        const formData = new FormData($('#testTemplateForm')[0]);

        // Show loading state
        $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Generating...');

        $.ajax({
            url: `/admin/template-builder/${templateId}/preview`,
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    $('#testCertificateImage').attr('src', response.preview_url);
                    $('#testDownloadBtn').attr('href', response.download_url);
                    $('#testResult').show();
                } else {
                    alert('Error: ' + response.error);
                }
            },
            error: function() {
                alert('Error generating test certificate');
            },
            complete: function() {
                $('#generateTestBtn').prop('disabled', false).html('<i class="fas fa-magic"></i> Generate Test Certificate');
            }
        });
    });

    // Auto-hide alerts
    setTimeout(function() {
        $('.alert').fadeOut('slow');
    }, 5000);
});
</script>
@endpush
