@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">Generate Certificate for {{ $user->full_name ?? $user->name }}</h3>
                        <a href="{{ route('admin.certificate-generator.index') }}" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to List
                        </a>
                    </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

                    <!-- User Information -->
                    <div class="row mb-4">
                        <div class="col-md-12">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h5>User Information</h5>
                                    <div class="row">
                                        <div class="col-md-3">
                                            <strong>Name:</strong> {{ $user->full_name ?? $user->name ?? 'N/A' }}
                                        </div>
                                        <div class="col-md-3">
                                            <strong>Email:</strong> {{ $user->email }}
                                        </div>
                                        <div class="col-md-3">
                                            <strong>Serial Number:</strong> {{ $userData['serial_number'] }}
                                        </div>
                                        <div class="col-md-3">
                                            <strong>User ID:</strong> {{ $user->id }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Debug Information (Remove in production) -->
                    @if(config('app.debug'))
                    <div class="row mb-4">
                        <div class="col-md-12">
                            <div class="alert alert-info">
                                <h6>Debug Information:</h6>
                                <p><strong>Templates Count:</strong> {{ count($templates) }}</p>
                                <p><strong>User Data:</strong> {{ json_encode($userData) }}</p>
                                <p><strong>Templates:</strong> {{ json_encode($templates) }}</p>
                            </div>
                        </div>
                    </div>
                    @endif


                    <!-- Certificate Generation Form -->
                    <form id="certificate-form" method="POST" action="{{ route('admin.certificate-generator.store', $user->id) }}" enctype="multipart/form-data">
                        @csrf

                        <!-- Template Selection -->
                        <div class="row mb-4">
                            <div class="col-md-12">
                                <h6>Select Template</h6>
                        <div class="row">
                                    @foreach($templates as $key => $template)
                                    <div class="col-md-4 mb-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="template_name" id="template_{{ $key }}" value="{{ $key }}" {{ $loop->first ? 'checked' : '' }}>
                                            <label class="form-check-label" for="template_{{ $key }}">
                                                <div class="card">
                                                    <div class="card-body text-center">
                                                        <i class="fas fa-certificate fa-3x text-primary mb-2"></i>
                                                        <h6>{{ $template['name'] }}</h6>
                                                        <p class="text-muted small">{{ $template['description'] }}</p>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>

                        <!-- Certificate Preview -->
                        <div class="row mb-4">
                            <div class="col-md-12 text-center">
                                <h6>Certificate Preview</h6>
                                <canvas id="certificate-canvas" width="800" height="600" style="border: 1px solid #ddd; max-width: 100%;"></canvas>
                            </div>
                        </div>

                        <!-- Position Controls -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Student Name Position</label>
                                    <div class="row">
                                        <div class="col-6">
                                            <input type="number" name="name_x" id="name-x" class="form-control" placeholder="X Position" value="400">
                                        </div>
                                        <div class="col-6">
                                            <input type="number" name="name_y" id="name-y" class="form-control" placeholder="Y Position" value="300">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Serial Number Position</label>
                                    <div class="row">
                                        <div class="col-6">
                                            <input type="number" name="serial_x" id="serial-x" class="form-control" placeholder="X Position" value="400">
                                </div>
                                        <div class="col-6">
                                            <input type="number" name="serial_y" id="serial-y" class="form-control" placeholder="Y Position" value="350">
                                        </div>
                                    </div>
                                </div>
                            </div>
                                </div>

                        <!-- Font Settings -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Font Size</label>
                                    <input type="number" name="font_size" id="font-size" class="form-control" value="24" min="12" max="48">
                                </div>
                                    </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Font Color</label>
                                    <input type="color" name="font_color" id="font-color" class="form-control" value="#000000">
                                </div>
                            </div>
                            </div>

                        <!-- Additional Fields -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Certificate Title</label>
                                    <input type="text" name="certificate_title" class="form-control" value="Certificate of Completion" placeholder="Enter certificate title">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Course/Program Name</label>
                                    <input type="text" name="course_name" class="form-control" value="Web Development Course" placeholder="Enter course name">
                                </div>
                                    </div>
                                </div>

                        <!-- Image Upload (Optional) -->
                        <div class="row mb-4">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label>Background Image (Optional)</label>
                                    <input type="file" name="background_image" class="form-control" accept="image/*">
                                    <small class="form-text text-muted">Upload a custom background image for the certificate</small>
                                </div>
                            </div>
                        </div>

                        <!-- Hidden fields for canvas data -->
                        <input type="hidden" name="certificate_data" id="certificate_data">
                        <input type="hidden" name="image_data" id="image_data">

                        <!-- Action Buttons -->
                        <div class="text-center">
                            <button type="button" id="preview-btn" class="btn btn-info mr-2">
                                <i class="fas fa-eye"></i> Preview
                            </button>
                            <button type="submit" id="generate-btn" class="btn btn-success">
                                <i class="fas fa-certificate"></i> Generate Certificate
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    #certificate-generator-container {
        min-height: 600px;
        border: 2px dashed #dee2e6;
        border-radius: 8px;
        padding: 20px;
    }

    .certificate-preview {
        max-width: 100%;
        height: auto;
        border: 1px solid #ddd;
        border-radius: 4px;
    }

    .template-selector {
        margin-bottom: 20px;
    }

    .template-option {
        cursor: pointer;
        border: 2px solid transparent;
        border-radius: 8px;
        padding: 10px;
        margin: 5px;
        transition: all 0.3s ease;
    }

    .template-option:hover {
        border-color: #007bff;
        background-color: #f8f9fa;
    }

    .template-option.selected {
        border-color: #007bff;
        background-color: #e3f2fd;
    }
</style>
@endpush

@push('scripts')
<!-- Certificate Generator Package -->
<script src="https://cdn.jsdelivr.net/npm/certificate-generator@latest/dist/certificate-generator.min.js"></script>
<script>
$(document).ready(function() {
    // User data for certificate generation
    const userData = @json($userData);
    const templates = @json($templates);

    console.log('User Data:', userData);
    console.log('Templates:', templates);

    // Draw initial certificate
    drawCertificate();

    // Template selection handler
    $('input[name="template_name"]').change(function() {
        drawCertificate();
    });

    // Event handlers
    $('#preview-btn').click(function() {
        drawCertificate();
    });

    $('#generate-btn').click(generateCertificate);

    // Auto-preview on input change
    $('#name-x, #name-y, #serial-x, #serial-y, #font-size, #font-color').on('input', function() {
        drawCertificate();
    });


    function drawCertificate() {
        console.log('Drawing certificate...');
        const canvas = document.getElementById('certificate-canvas');
        if (!canvas) {
            console.error('Canvas element not found');
            return;
        }
        const ctx = canvas.getContext('2d');

        // Clear canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // Draw background image if available
        if (window.backgroundImage) {
            ctx.drawImage(window.backgroundImage, 0, 0, canvas.width, canvas.height);
        } else {
            // Draw default background
            ctx.fillStyle = '#f8f9fa';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // Draw border
            ctx.strokeStyle = '#007bff';
            ctx.lineWidth = 4;
            ctx.strokeRect(20, 20, canvas.width - 40, canvas.height - 40);
        }

        // Draw title
        ctx.fillStyle = '#007bff';
        ctx.font = 'bold 36px Arial';
        ctx.textAlign = 'center';
        const title = $('input[name="certificate_title"]').val() || 'CERTIFICATE OF COMPLETION';
        ctx.fillText(title, canvas.width / 2, 100);

        // Draw course name
        ctx.fillStyle = '#666666';
        ctx.font = 'bold 24px Arial';
        ctx.textAlign = 'center';
        const courseName = $('input[name="course_name"]').val() || 'Web Development Course';
        ctx.fillText(courseName, canvas.width / 2, 150);

        // Draw student name
        ctx.fillStyle = $('#font-color').val() || '#000000';
        ctx.font = `bold ${$('#font-size').val() || 24}px Arial`;
        ctx.textAlign = 'center';
        const name = userData ? userData.name : 'Student Name';
        const nameX = parseInt($('#name-x').val()) || 400;
        const nameY = parseInt($('#name-y').val()) || 300;
        ctx.fillText(name, nameX, nameY);

        // Draw "This is to certify that" text
        ctx.fillStyle = '#333333';
        ctx.font = '20px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('This is to certify that', canvas.width / 2, 250);

        // Draw serial number
        ctx.fillStyle = '#666666';
        ctx.font = '16px Arial';
        ctx.textAlign = 'left';
        const serialNumber = userData ? userData.serial_number : 'SN-001';
        const serialX = parseInt($('#serial-x').val()) || 400;
        const serialY = parseInt($('#serial-y').val()) || 350;
        ctx.fillText(`Serial Number: ${serialNumber}`, serialX, serialY);

        // Draw date
        ctx.fillStyle = '#333333';
        ctx.font = '18px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(`Date: ${new Date().toLocaleDateString()}`, canvas.width / 2, 500);

        // Draw signature line
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(canvas.width - 200, canvas.height - 100);
        ctx.lineTo(canvas.width - 50, canvas.height - 100);
        ctx.stroke();

        ctx.fillStyle = '#333333';
        ctx.font = '16px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('Authorized Signature', canvas.width - 125, canvas.height - 80);
    }


    // Form submission handler
    $('#certificate-form').on('submit', function(e) {
        e.preventDefault();

        const canvas = document.getElementById('certificate-canvas');
        const imageData = canvas.toDataURL('image/png');

        // Set form data
        $('#certificate_data').val(JSON.stringify({
            name: userData.name,
            serial_number: userData.serial_number,
            email: userData.email,
            user_id: userData.user_id,
            positions: {
                name: { x: parseInt($('#name-x').val()), y: parseInt($('#name-y').val()) },
                serial: { x: parseInt($('#serial-x').val()), y: parseInt($('#serial-y').val()) }
            },
            font_size: parseInt($('#font-size').val()),
            font_color: $('#font-color').val()
        }));
        $('#image_data').val(imageData);

        // Submit form
        const formData = new FormData(this);

        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    alert('Certificate generated successfully!');
                    window.location.href = '{{ route("admin.certificate-generator.index") }}';
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function(xhr) {
                const response = JSON.parse(xhr.responseText);
                alert('Error: ' + (response.message || 'An error occurred'));
            }
        });
    });

    // Auto-preview on input change
    $('#name-x, #name-y, #serial-x, #serial-y, #font-size, #font-color, input[name="certificate_title"], input[name="course_name"]').on('input', function() {
        drawCertificate();
    });

    // Handle background image upload
    $('input[name="background_image"]').on('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const img = new Image();
                img.onload = function() {
                    // Store the background image for drawing
                    window.backgroundImage = img;
                    drawCertificate();
                };
                img.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
});
</script>
@endpush
