@extends('admin.layouts.app')

@section('title', 'Generate Certificate')

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

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="user_search">Search Student *</label>
                                    <input type="text" class="form-control @error('user_id') is-invalid @enderror"
                                           id="user_search" placeholder="Start typing student name or email..." required>
                                    <input type="hidden" id="user_id" name="user_id" value="{{ old('user_id') }}" required>
                                    @error('user_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror

                                    <div id="user_results" class="list-group mt-2" style="display: none;"></div>
                                </div>

                                <div class="form-group">
                                    <label for="template_id">Certificate Template *</label>
                                    <select class="form-control @error('template_id') is-invalid @enderror"
                                            id="template_id" name="template_id" required>
                                        <option value="">Select a template</option>
                                        @foreach($templates as $template)
                                            <option value="{{ $template->id }}"
                                                    data-name-x="{{ $template->name_x }}"
                                                    data-name-y="{{ $template->name_y }}"
                                                    data-date-x="{{ $template->date_x }}"
                                                    data-date-y="{{ $template->date_y }}"
                                                    data-serial-x="{{ $template->serial_x }}"
                                                    data-serial-y="{{ $template->serial_y }}">
                                                {{ $template->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('template_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>

                                <div class="form-group">
                                    <label for="graduation_date">Graduation Date *</label>
                                    <input type="date" class="form-control @error('graduation_date') is-invalid @enderror"
                                           id="graduation_date" name="graduation_date" value="{{ old('graduation_date') }}" required>
                                    @error('graduation_date')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>

                                <button type="submit" class="btn btn-primary">Generate Certificate</button>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Certificate Preview</label>
                                    <div class="border rounded p-2" style="background: #f8f9fa;">
                                        <div id="previewContainer" style="text-align: center; padding: 20px;">
                                            <p class="text-muted">Select a template and student to see preview</p>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label>Student Information</label>
                                    <div id="studentInfo" class="border rounded p-3" style="background: #f8f9fa; display: none;">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <strong>Name:</strong><br>
                                                <span id="studentName">-</span>
                                            </div>
                                            <div class="col-md-6">
                                                <strong>Email:</strong><br>
                                                <span id="studentEmail">-</span>
                                            </div>
                                        </div>
                                        <div class="row mt-2">
                                            <div class="col-md-6">
                                                <strong>Serial Number:</strong><br>
                                                <span id="studentSerial">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const userSearch = document.getElementById('user_search');
    const userResults = document.getElementById('user_results');
    const userId = document.getElementById('user_id');
    const templateSelect = document.getElementById('template_id');
    const studentInfo = document.getElementById('studentInfo');
    const previewContainer = document.getElementById('previewContainer');

    let selectedUser = null;
    let selectedTemplate = null;

    // User search functionality
    userSearch.addEventListener('input', function() {
        const query = this.value.trim();
        if (query.length < 2) {
            userResults.style.display = 'none';
            return;
        }

        console.log('Searching for users with query:', query);
        console.log('Search URL:', `{{ route('admin.graduation-certificates.search-users') }}?q=${encodeURIComponent(query)}`);
        
        fetch(`{{ route('admin.graduation-certificates.search-users') }}?q=${encodeURIComponent(query)}`)
            .then(response => {
                console.log('Response status:', response.status);
                console.log('Response headers:', response.headers);
                return response.json();
            })
            .then(users => {
                console.log('Users response:', users);
                userResults.innerHTML = '';
                if (users.length > 0) {
                    users.forEach(user => {
                        const item = document.createElement('a');
                        item.href = '#';
                        item.className = 'list-group-item list-group-item-action';
                        item.textContent = `${user.name} (${user.email})`;
                        item.addEventListener('click', function(e) {
                            e.preventDefault();
                            selectUser(user);
                        });
                        userResults.appendChild(item);
                    });
                    userResults.style.display = 'block';
                } else {
                    userResults.innerHTML = '<div class="list-group-item text-muted">No users found</div>';
                    userResults.style.display = 'block';
                }
            })
            .catch(error => {
                console.error('Error searching users:', error);
                userResults.innerHTML = '<div class="list-group-item text-danger">Error searching users</div>';
                userResults.style.display = 'block';
            });
    });

    // Hide results when clicking outside
    document.addEventListener('click', function(e) {
        if (!userSearch.contains(e.target) && !userResults.contains(e.target)) {
            userResults.style.display = 'none';
        }
    });

    function selectUser(user) {
        selectedUser = user;
        userSearch.value = user.name;
        userId.value = user.id;
        userResults.style.display = 'none';

        // Update student info
        document.getElementById('studentName').textContent = user.name;
        document.getElementById('studentEmail').textContent = user.email;
        document.getElementById('studentSerial').textContent = `CERT-${String(user.id).padStart(6, '0')}-${new Date().getFullYear()}`;
        studentInfo.style.display = 'block';

        updatePreview();
    }

    // Template selection
    templateSelect.addEventListener('change', function() {
        const templateId = this.value;
        if (templateId) {
            const option = this.options[this.selectedIndex];
            selectedTemplate = {
                id: templateId,
                name: option.text,
                name_x: parseInt(option.dataset.nameX),
                name_y: parseInt(option.dataset.nameY),
                date_x: parseInt(option.dataset.dateX),
                date_y: parseInt(option.dataset.dateY),
                serial_x: parseInt(option.dataset.serialX),
                serial_y: parseInt(option.dataset.serialY)
            };
        } else {
            selectedTemplate = null;
        }
        updatePreview();
    });

    function updatePreview() {
        if (selectedUser && selectedTemplate) {
            previewContainer.innerHTML = `
                <div style="border: 2px solid #ddd; padding: 20px; background: #fff; max-width: 300px; margin: 0 auto;">
                    <h5 style="margin-bottom: 20px;">Certificate Preview</h5>
                    <div style="margin-bottom: 15px;">
                        <strong>Student:</strong> ${selectedUser.name}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>Date:</strong> ${document.getElementById('graduation_date').value || 'Graduation Date'}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>Serial:</strong> CERT-${String(selectedUser.id).padStart(6, '0')}-${new Date().getFullYear()}
                    </div>
                    <small class="text-muted">Template: ${selectedTemplate.name}</small>
                </div>
            `;
        } else {
            previewContainer.innerHTML = '<p class="text-muted">Select a template and student to see preview</p>';
        }
    }

    // Update preview when graduation date changes
    document.getElementById('graduation_date').addEventListener('change', updatePreview);
});
</script>
@endpush
