@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</h3>
                        <a href="{{ route('admin.modern-certificates.index') }}" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to Certificates
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    @if($errors->any())
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <form action="{{ route('admin.modern-certificates.store') }}" method="POST">
                        @csrf

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="template_id">Select Template *</label>
                                    <select name="template_id" id="template_id" class="form-control" required>
                                        <option value="">Choose a template...</option>
                                        @foreach($templates as $template)
                                            <option value="{{ $template->id }}"
                                                    {{ old('template_id') == $template->id ? 'selected' : '' }}
                                                    data-category="{{ $template->category }}">
                                                {{ $template->name }} ({{ $template->category }})
                                            </option>
                                        @endforeach
                                    </select>
                                    <small class="form-text text-muted">
                                        Choose a template to use for this certificate
                                    </small>
                                </div>

                                                                <div class="form-group">
                                    <label for="student_search">Search Student</label>
                                    <div class="input-group">
                                        <input type="text" id="student_search" class="form-control"
                                               placeholder="Search by name, email, or ID...">
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary" id="searchStudent">
                                                <i class="fas fa-search"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div id="searchResults" class="mt-2" style="display: none;">
                                        <!-- Search results will appear here -->
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="student_name">Student Name *</label>
                                    <input type="text" name="student_name" id="student_name" class="form-control"
                                           value="{{ old('student_name') }}" required placeholder="Enter student's full name">
                                </div>

                                <div class="form-group">
                                    <label for="student_email">Student Email</label>
                                    <input type="email" name="student_email" id="student_email" class="form-control"
                                           value="{{ old('student_email') }}" placeholder="Enter student's email">
                                </div>

                                <div class="form-group">
                                    <label for="student_id">Student ID</label>
                                    <input type="text" name="student_id" id="student_id" class="form-control"
                                           value="{{ old('student_id') }}" placeholder="Enter student ID">
                                </div>

                                <div class="form-group">
                                    <label for="course_name">Course Name</label>
                                    <input type="text" name="course_name" id="course_name" class="form-control"
                                           value="{{ old('course_name') }}" placeholder="Enter course name">
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="graduation_date">Graduation Date *</label>
                                    <input type="date" name="graduation_date" id="graduation_date" class="form-control"
                                           value="{{ old('graduation_date') }}" required>
                                </div>

                                <div class="form-group">
                                    <label for="instructor_name">Instructor Name</label>
                                    <input type="text" name="instructor_name" id="instructor_name" class="form-control"
                                           value="{{ old('instructor_name') }}" placeholder="Enter instructor name">
                                </div>

                                <div class="form-group">
                                    <label for="organization_name">Organization Name</label>
                                    <input type="text" name="organization_name" id="organization_name" class="form-control"
                                           value="{{ old('organization_name') }}" placeholder="Enter organization name">
                                </div>

                                <div class="form-group">
                                    <label>Custom Fields</label>
                                    <div id="custom_fields_container">
                                        <div class="input-group mb-2">
                                            <input type="text" name="custom_data[field_name]" class="form-control" placeholder="Field name">
                                            <input type="text" name="custom_data[field_value]" class="form-control" placeholder="Field value">
                                            <div class="input-group-append">
                                                <button type="button" class="btn btn-outline-secondary remove-field" type="button">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <button type="button" class="btn btn-sm btn-outline-primary" id="add_custom_field">
                                        <i class="fas fa-plus"></i> Add Custom Field
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="form-group">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-magic"></i> Generate Certificate
                                    </button>
                                    <a href="{{ route('admin.modern-certificates.index') }}" class="btn btn-secondary ml-2">
                                        Cancel
                                    </a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    // Auto-select template if passed via URL
    const urlParams = new URLSearchParams(window.location.search);
    const templateId = urlParams.get('template');
    if (templateId) {
        $('#template_id').val(templateId);
    }

    // Add custom field
    $('#add_custom_field').click(function() {
        const fieldHtml = `
            <div class="input-group mb-2">
                <input type="text" name="custom_data[field_name]" class="form-control" placeholder="Field name">
                <input type="text" name="custom_data[field_value]" class="form-control" placeholder="Field value">
                <div class="input-group-append">
                    <button type="button" class="btn btn-outline-secondary remove-field" type="button">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        `;
        $('#custom_fields_container').append(fieldHtml);
    });

    // Remove custom field
    $(document).on('click', '.remove-field', function() {
        $(this).closest('.input-group').remove();
    });

    // Template selection change
    $('#template_id').change(function() {
        const selectedTemplate = $(this).find('option:selected');
        if (selectedTemplate.val()) {
            // You can add template-specific logic here
            console.log('Template selected:', selectedTemplate.text());
        }
    });

    // Student search functionality
    $('#searchStudent').click(function() {
        const query = $('#student_search').val();
        if (query.length < 2) {
            alert('Please enter at least 2 characters to search');
            return;
        }

        $.get('{{ route("admin.modern-certificates.search-students") }}', { q: query })
            .done(function(students) {
                if (students.length > 0) {
                    let resultsHtml = '<div class="list-group">';
                    students.forEach(function(student) {
                        resultsHtml += `
                            <a href="#" class="list-group-item list-group-item-action student-result"
                               data-student-id="${student.id}">
                                <strong>${student.name}</strong><br>
                                <small class="text-muted">
                                    ${student.email} | ID: ${student.student_id || 'N/A'}
                                    ${student.course_name ? ' | Course: ' + student.course_name : ''}
                                </small>
                            </a>
                        `;
                    });
                    resultsHtml += '</div>';
                    $('#searchResults').html(resultsHtml).show();
                } else {
                    $('#searchResults').html('<div class="alert alert-info">No students found</div>').show();
                }
            })
            .fail(function() {
                $('#searchResults').html('<div class="alert alert-danger">Error searching students</div>').show();
            });
    });

    // Handle student selection
    $(document).on('click', '.student-result', function(e) {
        e.preventDefault();
        const studentId = $(this).data('student-id');

        $.get('{{ route("admin.modern-certificates.student-data", ":id") }}'.replace(':id', studentId))
            .done(function(student) {
                $('#student_name').val(student.student_name);
                $('#student_email').val(student.student_email);
                $('#student_id').val(student.student_id);
                $('#course_name').val(student.course_name);

                // Hide search results
                $('#searchResults').hide();
                $('#student_search').val('');
            })
            .fail(function() {
                alert('Error loading student data');
            });
    });
});
</script>
@endpush
