<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('header', null, []); ?> 
        <div class="flex items-center justify-between w-full flex-wrap gap-3">
            <div>
                <h1 class="text-lg font-semibold text-gray-800">Import Invoices</h1>
                <p class="text-xs text-gray-400 mt-0.5">Bulk import invoices for multiple customers via CSV</p>
            </div>
            <a href="<?php echo e(route('invoices.index')); ?>"
                class="text-sm text-gray-500 hover:text-gray-700 font-medium inline-flex items-center gap-1">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                </svg>
                Back to Invoices
            </a>
        </div>
     <?php $__env->endSlot(); ?>

    <div x-data="invoiceImporter()" class="max-w-7xl mx-auto space-y-6">
        <!-- Main upload panel -->
        <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
            <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 pb-6 border-b border-gray-100">
                <div>
                    <h3 class="text-sm font-semibold text-gray-800">CSV Import Instructions</h3>
                    <p class="text-xs text-gray-500 mt-1 max-w-2xl leading-relaxed">
                        To successfully import, please download and use our pre-formatted CSV template.
                        You can specify multiple line items for a single invoice by repeating the same
                        <code class="px-1.5 py-0.5 rounded bg-gray-100 font-mono text-[11px] text-indigo-600 font-bold">invoice_group_id</code> (e.g. <code class="font-bold">INV-001</code>) on consecutive rows.
                    </p>
                </div>
                <a href="<?php echo e(route('invoices.import.template')); ?>"
                    class="shrink-0 inline-flex items-center gap-1.5 px-4 py-2.5 rounded-xl border border-gray-200 hover:bg-gray-50 text-gray-700 text-xs font-semibold transition shadow-sm">
                    <svg class="w-4 h-4 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                    </svg>
                    Download CSV Template
                </a>
            </div>

            <!-- Upload drag drop -->
            <div class="mt-6">
                <div class="relative border-2 border-dashed border-gray-200 hover:border-indigo-500 rounded-2xl p-8 transition text-center"
                     :class="{ 'border-indigo-500 bg-indigo-50/20': dragging }"
                     @dragover.prevent="dragging = true"
                     @dragleave.prevent="dragging = false"
                     @drop.prevent="dragging = false; if ($event.dataTransfer.files.length > 0) { uploadFile($event.dataTransfer.files[0]); }">
                    
                    <input type="file" id="csv_file" class="hidden" accept=".csv" @change="if ($event.target.files.length > 0) { uploadFile($event.target.files[0]); }">
                    
                    <label for="csv_file" class="cursor-pointer">
                        <div class="w-12 h-12 rounded-full bg-indigo-50 text-indigo-600 flex items-center justify-center mx-auto mb-3">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                            </svg>
                        </div>
                        <span class="text-sm font-semibold text-gray-700 block">Click to upload or drag & drop</span>
                        <span class="text-xs text-gray-400 mt-1 block">Only CSV files up to 4MB are supported</span>
                    </label>
                </div>
            </div>
        </div>

        <!-- Processing Loader / Progress Bar -->
        <div x-show="loading" class="bg-white rounded-2xl border border-gray-100 shadow-sm p-8 space-y-4">
            <div class="flex items-center justify-between text-xs font-semibold text-gray-500">
                <span class="inline-flex items-center gap-2">
                    <svg class="w-4 h-4 animate-spin text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                    </svg>
                    Uploading and validating invoices...
                </span>
                <span class="font-bold text-indigo-600" x-text="progress + '%'"></span>
            </div>
            <div class="w-full bg-gray-100 h-2.5 rounded-full overflow-hidden">
                <div class="bg-indigo-600 h-full rounded-full transition-all duration-300 ease-out" :style="'width: ' + progress + '%'"></div>
            </div>
        </div>

        <!-- Parsed Invoices Preview -->
        <div x-show="!loading && invoices.length > 0" class="space-y-6">
            <div class="flex items-center justify-between">
                <h2 class="text-sm font-bold text-gray-800 uppercase tracking-wide" x-text="`Previewing ${invoices.length} Invoices`"></h2>
                
                <div class="flex items-center gap-3">
                    <button @click="resetImporter()" class="text-xs font-semibold text-gray-500 hover:text-gray-700 transition">
                        Clear File
                    </button>
                    <button @click="confirmImport()" :disabled="hasCriticalErrors || importing"
                            class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 disabled:bg-gray-200 disabled:cursor-not-allowed text-white text-xs font-semibold rounded-xl transition shadow-sm inline-flex items-center gap-1.5">
                        <svg class="w-4 h-4" x-show="!importing" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                        </svg>
                        <svg class="w-4 h-4 animate-spin" x-show="importing" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                        </svg>
                        <span x-text="importing ? 'Importing...' : 'Confirm & Save Invoices'"></span>
                    </button>
                </div>
            </div>

            <!-- Danger Alert if errors exist -->
            <div x-show="hasCriticalErrors" class="p-4 rounded-xl bg-rose-50 border border-rose-100 flex items-start gap-3">
                <svg class="w-5 h-5 text-rose-500 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
                <div>
                    <h4 class="text-xs font-bold text-rose-800 uppercase">Critical Errors Detected</h4>
                    <p class="text-xs text-rose-600 mt-1">Please fix the highlighted rows in your CSV file and upload again. Invoices with errors cannot be imported.</p>
                </div>
            </div>

            <!-- Invoices List -->
            <div class="space-y-4">
                <template x-for="inv in invoices" :key="inv.group_id">
                    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                        <!-- Invoice Header -->
                        <div class="px-5 py-4 bg-gray-50/50 border-b border-gray-100 flex items-center justify-between flex-wrap gap-3">
                            <div class="flex items-center gap-3">
                                <span class="text-[10px] font-bold px-2 py-0.5 rounded bg-indigo-50 text-indigo-600 uppercase font-mono" x-text="inv.group_id"></span>
                                <span class="text-xs font-bold text-gray-800" x-text="inv.customer_name"></span>
                                <span class="text-[11px] text-gray-400" x-text="`NTN: ${inv.customer_ntn || 'Unregistered'}`"></span>
                                <span class="text-[11px] px-2 py-0.5 rounded bg-gray-200/60 text-gray-600" x-text="inv.customer_province"></span>
                            </div>
                            <div class="flex items-center gap-4">
                                <div class="text-right">
                                    <span class="text-[10px] text-gray-400 block uppercase font-medium">Invoice Date</span>
                                    <span class="text-xs font-bold text-gray-700" x-text="inv.invoice_date"></span>
                                </div>
                                <div class="text-right">
                                    <span class="text-[10px] text-gray-400 block uppercase font-medium">Net Amount</span>
                                    <span class="text-xs font-bold text-indigo-600" x-text="formatCurrency(inv.total_amount)"></span>
                                </div>
                            </div>
                        </div>

                        <!-- Errors Box -->
                        <div x-show="inv.errors.length > 0" class="px-5 py-3 bg-rose-50/30 border-b border-gray-100">
                            <ul class="list-disc pl-5 text-xs text-rose-600 space-y-1">
                                <template x-for="err in inv.errors">
                                    <li x-text="err"></li>
                                </template>
                            </ul>
                        </div>

                        <!-- Line Items Table -->
                        <div class="overflow-x-auto">
                            <table class="w-full text-left border-collapse">
                                <thead>
                                    <tr class="bg-white border-b border-gray-100 text-[10px] font-bold text-gray-400 uppercase tracking-wider">
                                        <th class="px-5 py-3">Description</th>
                                        <th class="px-5 py-3">HS Code</th>
                                        <th class="px-5 py-3 text-right">Quantity</th>
                                        <th class="px-5 py-3">UOM</th>
                                        <th class="px-5 py-3 text-right">Rate</th>
                                        <th class="px-5 py-3 text-right">Excl. Tax</th>
                                        <th class="px-5 py-3 text-right">Sales Tax</th>
                                        <th class="px-5 py-3 text-right">Total</th>
                                    </tr>
                                </thead>
                                <tbody class="text-xs text-gray-600 divide-y divide-gray-50">
                                    <template x-for="item in inv.items">
                                        <tr>
                                            <td class="px-5 py-3.5 font-medium text-gray-800" x-text="item.product_description"></td>
                                            <td class="px-5 py-3.5 font-mono text-gray-400" x-text="item.hs_code || '—'"></td>
                                            <td class="px-5 py-3.5 text-right font-semibold" x-text="item.quantity"></td>
                                            <td class="px-5 py-3.5 text-gray-500" x-text="item.uom"></td>
                                            <td class="px-5 py-3.5 text-right font-semibold" x-text="formatCurrency(item.rate)"></td>
                                            <td class="px-5 py-3.5 text-right text-gray-500" x-text="formatCurrency(item.value_sales_excluding_st)"></td>
                                            <td class="px-5 py-3.5 text-right text-emerald-600 font-semibold" x-text="`${formatCurrency(item.sales_tax_applicable)} (${item.sales_tax_rate}%)`"></td>
                                            <td class="px-5 py-3.5 text-right font-bold text-gray-800" x-text="formatCurrency(item.total_values)"></td>
                                        </tr>
                                    </template>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <script>
         function invoiceImporter() {
            return {
                dragging: false,
                loading: false,
                importing: false,
                progress: 0,
                invoices: [],

                init() {
                    // component loaded
                },

                uploadFile(file) {
                    this.loading = true;
                    this.progress = 0;
                    this.invoices = [];
                    
                    const formData = new FormData();
                    formData.append('file', file);

                    axios.post('<?php echo e(route("invoices.import.preview")); ?>', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        },
                        onUploadProgress: (progressEvent) => {
                            if (progressEvent.total) {
                                const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                                this.progress = Math.min(percentCompleted, 90);
                            } else {
                                this.progress = 50;
                            }
                        }
                    })
                    .then(response => {
                        this.progress = 100;
                        setTimeout(() => {
                            this.loading = false;
                            if (response.data.success) {
                                this.invoices = response.data.invoices;
                            } else {
                                alert(response.data.error || 'Failed to parse file.');
                            }
                        }, 400);
                    })
                    .catch(error => {
                        this.loading = false;
                        alert(error.response?.data?.message || 'Error uploading file.');
                    });
                },

                confirmImport() {
                    this.importing = true;
                    axios.post('<?php echo e(route("invoices.import.store")); ?>', {
                        invoices: this.invoices
                    })
                    .then(response => {
                        this.importing = false;
                        if (response.data.success) {
                            alert(response.data.message);
                            window.location.href = '<?php echo e(route("invoices.index")); ?>';
                        } else {
                            alert(response.data.error || 'Failed to import records.');
                        }
                    })
                    .catch(error => {
                        this.importing = false;
                        alert(error.response?.data?.message || 'Error occurred during import.');
                    });
                },

                get hasCriticalErrors() {
                    return this.invoices.some(inv => inv.errors.length > 0);
                },

                resetImporter() {
                    this.invoices = [];
                    document.getElementById('csv_file').value = '';
                },

                formatCurrency(val) {
                    return 'Rs. ' + parseFloat(val).toLocaleString(undefined, {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }
            }
        }
    </script>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php /**PATH /www/wwwroot/fbrdiv2.shiningerp.com/resources/views/invoices/import.blade.php ENDPATH**/ ?>