{{-- Excel Upload Modal Component --}}
{{-- Usage: @include('layouts.partials.excel_upload_modal', ['module' => 'stores', 'title' => 'Stores', 'uploadRoute' => route('stores.upload_excel'), 'downloadRoute' => route('stores.download_template')]) --}}

<!-- Upload Excel Modal -->
<div class="modal fade" id="uploadExcelModal-{{ $module }}" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">
                    <i class="fas fa-file-upload"></i> Upload Excel - {{ $title }}
                </h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form id="uploadExcelForm-{{ $module }}">
                @csrf
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle"></i>
                        <strong>Petunjuk:</strong>
                        <ul class="mb-0 mt-2">
                            <li>Download template Excel terlebih dahulu</li>
                            <li>Isi data sesuai format template</li>
                            <li>Upload file Excel (.xlsx atau .xls)</li>
                            <li>Sistem akan insert data baru atau update data yang sudah ada berdasarkan Code</li>
                        </ul>
                    </div>
                    
                    <div class="form-group">
                        <label>File Excel <span class="text-danger">*</span></label>
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" id="excel_file_{{ $module }}" name="excel_file" accept=".xlsx,.xls" required>
                            <label class="custom-file-label" for="excel_file_{{ $module }}">Pilih file...</label>
                        </div>
                        <small class="text-muted">Format: .xlsx atau .xls (Max: 10MB)</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-warning" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-warning" id="uploadExcelSubmit-{{ $module }}">
                        <i class="fas fa-upload"></i> Upload
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(function() {
    // Upload Excel button
    $('#upload-excel-btn-{{ $module }}').click(function() {
        $('#uploadExcelModal-{{ $module }}').modal('show');
    });

    // Download Template button
    $('#download-template-btn-{{ $module }}').click(function() {
        window.location.href = '{{ $downloadRoute }}';
    });

    // Update file input label
    $('#excel_file_{{ $module }}').on('change', function() {
        const fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').html(fileName);
    });

    // Handle Excel upload
    $('#uploadExcelForm-{{ $module }}').submit(function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const btn = $('#uploadExcelSubmit-{{ $module }}');
        const originalText = btn.html();
        
        btn.html('<i class="fa fa-spinner fa-spin"></i> Uploading...').prop('disabled', true);
        
        $.ajax({
            url: '{{ $uploadRoute }}',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    let errorHtml = '';
                    if (response.errors && response.errors.length > 0) {
                        errorHtml = '<br><br><div class="text-left"><strong>Errors:</strong><ul class="mb-0">';
                        response.errors.forEach(e => {
                            errorHtml += `<li>Row ${e.row}: ${e.error}</li>`;
                        });
                        errorHtml += '</ul></div>';
                    }
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        html: response.message + errorHtml,
                        confirmButtonText: 'OK',
                        width: '600px'
                    }).then(() => {
                        $('#uploadExcelModal-{{ $module }}').modal('hide');
                        $('#uploadExcelForm-{{ $module }}')[0].reset();
                        $('#excel_file_{{ $module }}').next('.custom-file-label').html('Pilih file...');
                        
                        // Reload DataTable if exists
                        if ($.fn.DataTable.isDataTable('#id_data_table')) {
                            $('#id_data_table').DataTable().ajax.reload();
                        } else if ($.fn.DataTable.isDataTable('#dataTable')) {
                            $('#dataTable').DataTable().ajax.reload();
                        } else if ($.fn.DataTable.isDataTable('#holidaysTable')) {
                            $('#holidaysTable').DataTable().ajax.reload();
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal!',
                        text: response.message,
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function(xhr) {
                const response = xhr.responseJSON || {};
                let errorMessage = response.message || 'Upload gagal';
                
                if (response.errors) {
                    errorMessage += '<br><br><ul class="text-left mb-0">';
                    for (const key in response.errors) {
                        errorMessage += `<li>${response.errors[key].join(', ')}</li>`;
                    }
                    errorMessage += '</ul>';
                }
                
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    html: errorMessage,
                    confirmButtonText: 'OK'
                });
            },
            complete: function() {
                btn.html(originalText).prop('disabled', false);
            }
        });
    });
});
</script>
