@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">Bulk Certificate Generation</h3>
                        <a href="{{ route('admin.certificate-generator.index') }}" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to Generator
                        </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('errors'))
                        <div class="alert alert-warning alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            <h6>Some errors occurred during processing:</h6>
                            <ul class="mb-0">
                                @foreach(session('errors') as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    @if($errors->any())
                        <div class="alert alert-danger alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            <ul class="mb-0">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <div class="row">
                        <div class="col-md-8">
                            <form action="{{ route('admin.certificate-generator.process-bulk-upload') }}" method="POST" enctype="multipart/form-data" id="bulkUploadForm">
                                @csrf
                                <div class="form-group">
                                    <label for="template_id">Certificate Template <span class="text-danger">*</span></label>
                                    <select name="template_id" id="template_id" class="form-control" required>
                                        <option value="">Select Template</option>
                                        @foreach($templates as $template)
                                            <option value="{{ $template->id }}"
                                                data-fields="{{ json_encode($template->fields) }}"
                                                data-default-fields="{{ json_encode($template->default_fields) }}">
                                                {{ $template->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label for="graduation_date">Graduation Date <span class="text-danger">*</span></label>
                                    <input type="date" name="graduation_date" id="graduation_date" class="form-control" required>
                                </div>

                                <div class="form-group">
                                    <label for="csv_file">CSV File <span class="text-danger">*</span></label>
                                    <input type="file" name="csv_file" id="csv_file" class="form-control-file" accept=".csv,.txt" required>
                                    <small class="form-text text-muted">
                                        Upload a CSV file with student information. The file should contain columns for student identification (email, full_name, or name).
                                    </small>
                                </div>

                                <div class="form-group">
                                    <label>CSV Format Example</label>
                                    <div class="table-responsive">
                                        <table class="table table-sm table-bordered">
                                            <thead class="thead-light">
                                                <tr>
                                                    <th>email</th>
                                                    <th>full_name</th>
                                                    <th>course_name</th>
                                                    <th>instructor_name</th>
                                                    <th>custom_field1</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>john@example.com</td>
                                                    <td>John Doe</td>
                                                    <td>Advanced Mathematics</td>
                                                    <td>Dr. Smith</td>
                                                    <td>Custom Value</td>
                                                </tr>
                                                <tr>
                                                    <td>jane@example.com</td>
                                                    <td>Jane Smith</td>
                                                    <td>Physics 101</td>
                                                    <td>Prof. Johnson</td>
                                                    <td>Another Value</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label>Template Fields</label>
                                    <div id="template_fields_preview" class="border rounded p-3">
                                        <i class="fas fa-info-circle text-muted"></i> Select a template to see available fields
                                    </div>
                                </div>

                                <button type="submit" class="btn btn-primary" id="processBtn">
                                    <i class="fas fa-upload"></i> Process CSV & Generate Certificates
                                </button>
                            </form>
                        </div>

                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">Instructions</h6>
                                </div>
                                <div class="card-body">
                                    <ol class="mb-0">
                                        <li><strong>Select Template:</strong> Choose the certificate template to use</li>
                                        <li><strong>Set Date:</strong> Set the graduation/completion date</li>
                                        <li><strong>Prepare CSV:</strong> Create a CSV file with student data</li>
                                        <li><strong>Upload & Process:</strong> Upload the file and generate certificates</li>
                                    </ol>

                                    <hr>

                                    <h6>CSV Requirements:</h6>
                                    <ul class="mb-0">
                                        <li>Must have at least one identifier column (email, full_name, or name)</li>
                                        <li>Additional columns can be used for custom fields</li>
                                        <li>First row should contain column headers</li>
                                        <li>File size should be reasonable (max 5MB)</li>
                                    </ul>

                                    <hr>

                                    <h6>Supported Formats:</h6>
                                    <ul class="mb-0">
                                        <li>CSV (.csv)</li>
                                        <li>Text files (.txt) with comma separation</li>
                                    </ul>
                                </div>
                            </div>

                            <div class="card mt-3">
                                <div class="card-header">
                                    <h6 class="mb-0">Download Sample CSV</h6>
                                </div>
                                <div class="card-body">
                                    <p class="mb-2">Download a sample CSV file to see the required format:</p>
                                    <button type="button" class="btn btn-outline-primary btn-sm" id="downloadSampleBtn">
                                        <i class="fas fa-download"></i> Download Sample CSV
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    // Template selection change
    $('#template_id').change(function() {
        const templateId = $(this).val();
        if (templateId) {
            loadTemplateFields(templateId);
        } else {
            $('#template_fields_preview').html('<i class="fas fa-info-circle text-muted"></i> Select a template to see available fields');
        }
    });

    function loadTemplateFields(templateId) {
        const option = $(`#template_id option[value="${templateId}"]`);
        const fields = option.data('fields') || option.data('default-fields');

        if (fields) {
            let html = '<h6>Available Fields:</h6><div class="row">';
            Object.keys(fields).forEach(function(key) {
                const field = fields[key];
                html += `
                    <div class="col-md-6 mb-2">
                        <div class="border rounded p-2">
                            <strong>${field.label}</strong><br>
                            <small class="text-muted">
                                Position: ${field.x}%, ${field.y}%<br>
                                Font: ${field.font_family} ${field.font_size}px<br>
                                Color: <span class="badge badge-secondary">${field.color}</span>
                            </small>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            $('#template_fields_preview').html(html);
        }
    }

    // Download sample CSV
    $('#downloadSampleBtn').click(function() {
        const csvContent = `email,full_name,course_name,instructor_name,organization_name,custom_field1
john.doe@example.com,John Doe,Advanced Mathematics,Dr. Sarah Smith,University of Science,Mathematics Excellence
jane.smith@example.com,Jane Smith,Physics 101,Prof. Michael Johnson,Institute of Technology,Physics Achievement
mike.wilson@example.com,Mike Wilson,Computer Science,Dr. Emily Brown,Tech University,Programming Skills
sarah.davis@example.com,Sarah Davis,Chemistry Lab,Prof. David Wilson,Science College,Lab Excellence
alex.taylor@example.com,Alex Taylor,Engineering Design,Dr. Lisa Anderson,Engineering Institute,Design Innovation`;

        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'sample_certificate_data.csv';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    });

    // Form validation
    $('#bulkUploadForm').submit(function(e) {
        const fileInput = $('#csv_file')[0];
        const file = fileInput.files[0];

        if (file) {
            const fileSize = file.size / 1024 / 1024; // Convert to MB
            if (fileSize > 5) {
                e.preventDefault();
                alert('File size must be less than 5MB');
                return false;
            }
        }

        // Show loading state
        $('#processBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Processing...');
    });

    // Auto-hide alerts
    setTimeout(function() {
        $('.alert').fadeOut('slow');
    }, 8000);
});
</script>
@endpush
