@extends('admin.layouts.app')

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

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Create Certificate Template</h3>
                    <div class="card-tools">
                        <a href="{{ route('admin.graduation-certificates.templates.index') }}" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to Templates
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form action="{{ route('admin.graduation-certificates.templates.store') }}" method="POST" enctype="multipart/form-data" id="templateForm">
                        @csrf

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="name">Template Name *</label>
                                    <input type="text" class="form-control @error('name') is-invalid @enderror"
                                           id="name" name="name" value="{{ old('name') }}" required>
                                    @error('name')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="background_image">Background Image *</label>
                                    <input type="file" class="form-control @error('background_image') is-invalid @enderror"
                                           id="background_image" name="background_image"
                                           accept="image/jpeg,image/jpg,image/png" required>
                                    <small class="form-text text-muted">Upload a JPG or PNG image (max 2MB)</small>
                                    @error('background_image')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label>Text Positioning</label>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <label>Student Name Position</label>
                                            <div class="input-group">
                                                <input type="number" class="form-control" id="name_x" name="name_x"
                                                       value="{{ old('name_x', 100) }}" placeholder="X" required>
                                                <input type="number" class="form-control" id="name_y" name="name_y"
                                                       value="{{ old('name_y', 200) }}" placeholder="Y" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <label>Graduation Date Position</label>
                                            <div class="input-group">
                                                <input type="number" class="form-control" id="date_x" name="date_x"
                                                       value="{{ old('date_x', 100) }}" placeholder="X" required>
                                                <input type="number" class="form-control" id="date_y" name="date_y"
                                                       value="{{ old('date_y', 300) }}" placeholder="Y" required>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row mt-2">
                                        <div class="col-md-6">
                                            <label>Serial Number Position</label>
                                            <div class="input-group">
                                                <input type="number" class="form-control" id="serial_x" name="serial_x"
                                                       value="{{ old('serial_x', 100) }}" placeholder="X" required>
                                                <input type="number" class="form-control" id="serial_y" name="serial_y"
                                                       value="{{ old('serial_y', 400) }}" placeholder="Y" required>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <button type="submit" class="btn btn-primary">Create Template</button>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Preview & Positioning</label>
                                    <div class="border rounded p-2" style="background: #f8f9fa;">
                                        <canvas id="previewCanvas" width="400" height="300"
                                                style="border: 1px solid #ddd; max-width: 100%; height: auto;"></canvas>
                                    </div>
                                    <small class="form-text text-muted">
                                        Drag the text elements to position them on the image.
                                        The coordinates will be automatically updated in the form fields.
                                    </small>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const canvas = document.getElementById('previewCanvas');
    const ctx = canvas.getContext('2d');
    const fileInput = document.getElementById('background_image');

    let image = null;
    let isDragging = false;
    let dragTarget = null;
    let dragOffset = { x: 0, y: 0 };

    // Text elements
    const textElements = [
        { id: 'name', text: 'Student Name', x: 100, y: 200, color: '#000000', size: 20 },
        { id: 'date', text: 'Graduation Date', x: 100, y: 300, color: '#000000', size: 16 },
        { id: 'serial', text: 'Serial Number', x: 100, y: 400, color: '#666666', size: 14 }
    ];

    // Load image when file is selected
    fileInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(event) {
                image = new Image();
                image.onload = function() {
                    // Resize canvas to fit image
                    const maxWidth = 400;
                    const maxHeight = 300;
                    let { width, height } = image;

                    if (width > maxWidth) {
                        height = (height * maxWidth) / width;
                        width = maxWidth;
                    }
                    if (height > maxHeight) {
                        width = (width * maxHeight) / height;
                        height = maxHeight;
                    }

                    canvas.width = width;
                    canvas.height = height;

                    // Scale text positions
                    const scaleX = width / image.naturalWidth;
                    const scaleY = height / image.naturalHeight;

                    textElements.forEach(element => {
                        element.x = element.x * scaleX;
                        element.y = element.y * scaleY;
                    });

                    drawCanvas();
                };
                image.src = event.target.result;
            };
            reader.readAsDataURL(file);
        }
    });

    // Mouse events for dragging
    canvas.addEventListener('mousedown', startDrag);
    canvas.addEventListener('mousemove', drag);
    canvas.addEventListener('mouseup', stopDrag);

    function startDrag(e) {
        const rect = canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;

        // Check if clicking on text
        for (let i = textElements.length - 1; i >= 0; i--) {
            const element = textElements[i];
            if (x >= element.x - 50 && x <= element.x + 50 &&
                y >= element.y - 20 && y <= element.y + 20) {
                isDragging = true;
                dragTarget = element;
                dragOffset.x = x - element.x;
                dragOffset.y = y - element.y;
                break;
            }
        }
    }

    function drag(e) {
        if (!isDragging || !dragTarget) return;

        const rect = canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;

        dragTarget.x = x - dragOffset.x;
        dragTarget.y = y - dragOffset.y;

        // Update form fields
        updateFormFields();
        drawCanvas();
    }

    function stopDrag() {
        isDragging = false;
        dragTarget = null;
    }

    function updateFormFields() {
        // Scale back to original image dimensions
        const scaleX = image ? image.naturalWidth / canvas.width : 1;
        const scaleY = image ? image.naturalHeight / canvas.height : 1;

        document.getElementById('name_x').value = Math.round(textElements[0].x * scaleX);
        document.getElementById('name_y').value = Math.round(textElements[0].y * scaleY);
        document.getElementById('date_x').value = Math.round(textElements[1].x * scaleX);
        document.getElementById('date_y').value = Math.round(textElements[1].y * scaleY);
        document.getElementById('serial_x').value = Math.round(textElements[2].x * scaleX);
        document.getElementById('serial_y').value = Math.round(textElements[2].y * scaleY);
    }

    function drawCanvas() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // Draw background image if available
        if (image) {
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        } else {
            // Draw placeholder
            ctx.fillStyle = '#f0f0f0';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = '#999';
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('Upload an image to preview', canvas.width / 2, canvas.height / 2);
        }

        // Draw text elements
        textElements.forEach(element => {
            ctx.fillStyle = element.color;
            ctx.font = `${element.size}px Arial`;
            ctx.textAlign = 'center';
            ctx.fillText(element.text, element.x, element.y);

            // Draw selection box if dragging
            if (dragTarget === element) {
                ctx.strokeStyle = '#007bff';
                ctx.lineWidth = 2;
                ctx.strokeRect(element.x - 50, element.y - 20, 100, 40);
            }
        });
    }

    // Initial draw
    drawCanvas();

    // Debug: Log canvas dimensions
    console.log('Canvas initialized:', canvas.width, 'x', canvas.height);
    console.log('Canvas element:', canvas);

    // Test canvas context
    if (ctx) {
        console.log('Canvas context working');
        // Draw a test rectangle
        ctx.fillStyle = '#e0e0e0';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#333';
        ctx.font = '16px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('Upload an image to preview', canvas.width / 2, canvas.height / 2);
    } else {
        console.error('Canvas context not working');
    }
});
</script>
@endpush
