@extends('admin.layouts.app')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3>Template Builder - {{ $template->name }}</h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <h6>Template Canvas</h6>
                                </div>
                                <div class="card-body text-center">
                                    <div id="canvasContainer" class="border rounded d-inline-block">
                                        <canvas id="templateCanvas" width="800" height="600"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h6>Add Fields</h6>
                                </div>
                                <div class="card-body">
                                    <div class="form-group">
                                        <label>Field Type</label>
                                        <select id="fieldType" class="form-control">
                                            <option value="text">Text Field</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Field Label</label>
                                        <input type="text" id="fieldLabel" class="form-control" placeholder="e.g., Student Name">
                                    </div>
                                    <div class="form-group">
                                        <label>Field Value</label>
                                        <input type="text" id="fieldValue" class="form-control" placeholder="e.g., @{{student_name}}">
                                    </div>
                                    <div class="form-group">
                                        <label>X Position</label>
                                        <input type="number" id="fieldX" class="form-control" value="100">
                                    </div>
                                    <div class="form-group">
                                        <label>Y Position</label>
                                        <input type="number" id="fieldY" class="form-control" value="100">
                                    </div>
                                    <div class="form-group">
                                        <label>Font Size</label>
                                        <input type="number" id="fieldFontSize" class="form-control" value="24">
                                    </div>
                                    <div class="form-group">
                                        <label>Font Family</label>
                                        <select id="fieldFontFamily" class="form-control">
                                            <option value="Arial">Arial</option>
                                            <option value="Times New Roman">Times New Roman</option>
                                            <option value="Courier New">Courier New</option>
                                        </select>
                                    </div>
                                    <button type="button" class="btn btn-primary" id="addField">Add Field</button>
                                </div>
                            </div>

                            <div class="card mt-3">
                                <div class="card-header">
                                    <h6>Template Fields</h6>
                                </div>
                                <div class="card-body">
                                    <div id="fieldsList">
                                        <!-- Fields will be listed here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-12">
                            <button type="button" class="btn btn-success" id="saveTemplate">Save Template</button>
                            <button type="button" class="btn btn-info" id="previewTemplate">Preview</button>
                            <a href="{{ route('admin.template-builder.index') }}" class="btn btn-secondary">Back</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const canvas = document.getElementById('templateCanvas');
    const ctx = canvas.getContext('2d');
    let fields = [];

    // Load existing template data
    @if($template->template_data)
        fields = @json($template->template_data['fields'] ?? []);
    @endif

    // Initialize canvas
    function initCanvas() {
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        renderFields();
    }

    // Render all fields
    function renderFields() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        fields.forEach(field => {
            if (field.type === 'text') {
                ctx.font = `${field.fontSize}px ${field.fontFamily}`;
                ctx.fillStyle = '#000000';
                ctx.fillText(field.value, field.x, field.y);
            }
        });

        updateFieldsList();
    }

    // Update fields list display
    function updateFieldsList() {
        const container = document.getElementById('fieldsList');
        container.innerHTML = '';

        fields.forEach((field, index) => {
            const fieldDiv = document.createElement('div');
            fieldDiv.className = 'border rounded p-2 mb-2';
            fieldDiv.innerHTML = `
                <strong>${field.label}</strong> (${field.value})
                <button type="button" class="btn btn-sm btn-danger float-right" onclick="deleteField(${index})">Delete</button>
            `;
            container.appendChild(fieldDiv);
        });
    }

    // Add new field
    document.getElementById('addField').addEventListener('click', function() {
        const newField = {
            type: document.getElementById('fieldType').value,
            label: document.getElementById('fieldLabel').value,
            value: document.getElementById('fieldValue').value,
            x: parseInt(document.getElementById('fieldX').value),
            y: parseInt(document.getElementById('fieldY').value),
            fontSize: parseInt(document.getElementById('fieldFontSize').value),
            fontFamily: document.getElementById('fieldFontFamily').value
        };

        if (newField.label && newField.value) {
            fields.push(newField);
            renderFields();

            // Clear form
            document.getElementById('fieldLabel').value = '';
            document.getElementById('fieldValue').value = '';
        }
    });

    // Delete field
    window.deleteField = function(index) {
        fields.splice(index, 1);
        renderFields();
    };

    // Save template
    document.getElementById('saveTemplate').addEventListener('click', function() {
        const templateData = {
            fields: fields,
            settings: {
                width: canvas.width,
                height: canvas.height
            }
        };

        fetch('{{ route("admin.template-builder.update", $template) }}', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                template_data: templateData
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Template saved successfully!');
            } else {
                alert('Error saving template');
            }
        });
    });

    // Preview template
    document.getElementById('previewTemplate').addEventListener('click', function() {
        const previewCanvas = document.createElement('canvas');
        previewCanvas.width = canvas.width;
        previewCanvas.height = canvas.height;
        const previewCtx = previewCanvas.getContext('2d');

        // Draw background
        previewCtx.fillStyle = '#ffffff';
        previewCtx.fillRect(0, 0, previewCanvas.width, previewCanvas.height);

        // Draw fields with sample data
        fields.forEach(field => {
            if (field.type === 'text') {
                const sampleValue = field.value
                    .replace(/\{\{student_name\}\}/g, 'John Doe')
                    .replace(/\{\{course_name\}\}/g, 'Web Development')
                    .replace(/\{\{graduation_date\}\}/g, '2024-01-15');

                previewCtx.font = `${field.fontSize}px ${field.fontFamily}`;
                previewCtx.fillStyle = '#000000';
                previewCtx.fillText(sampleValue, field.x, field.y);
            }
        });

        const previewWindow = window.open('', '_blank');
        previewWindow.document.write(`
            <html>
                <head><title>Template Preview</title></head>
                <body style="margin: 20px; text-align: center;">
                    <h2>Template Preview</h2>
                    <img src="${previewCanvas.toDataURL()}" style="max-width: 100%; border: 1px solid #ddd;">
                </body>
            </html>
        `);
    });

    // Initialize
    initCanvas();
});
</script>
@endsection
