@extends('layouts/base_view')
@section('title')
{!! $variables['header_routes'] !!}
@endsection
@section('content')
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card card-outline card-warning">
                    <div class="card-header">
                        <h3 class="card-title">{!! $variables['judul'] !!}</h3>
                    </div>
                    <div class="card-body">
                        <!-- Upload Progress -->
                        <div id="uploadProgress" class="mt-4" style="display: none;">
                            <div class="progress">
                                <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                            </div>
                            <p class="mt-2 mb-0">Mengupload dan memproses file...</p>
                        </div>

                        <!-- Upload Results -->
                        <div id="uploadResults" class="mt-4" style="display: none;">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title">Hasil Upload</h5>
                                </div>
                                <div class="card-body">
                                    <div id="resultsContent"></div>
                                </div>
                            </div>
                        </div>

                        <form id="uploadForm" enctype="multipart/form-data">
                            @csrf
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="form-group select2-purple">
                                                <label>Tahun <span class="text-danger">*</span></label>
                                                <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" style="width:100%" name="year" id="year" required>
                                                    @for($year = date('Y'); $year <= date('Y') + 2; $year++)
                                                        <option value="{{ $year }}" {{ $year == date('Y') ? 'selected' : '' }}>{{ $year }}</option>
                                                        @endfor
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label>Bulan <span class="text-danger">*</span></label>
                                                <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" style="width:100%" name="month" id="month" required>
                                                    @for($month = 1; $month <= 12; $month++)
                                                        <option value="{{ $month }}" {{ $month == date('n') ? 'selected' : '' }}>
                                                        {{ date('F', mktime(0, 0, 0, $month, 1)) }}
                                                        </option>
                                                        @endfor
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label>File Excel <span class="text-danger">*</span>&nbsp;<span class="text-info" id="downloadTemplateBtn" style="cursor: pointer;"> Unduh Template <i class="fas fa-download"></i> </span></label>
                                                <div class="input-group">
                                                    <div class="custom-file">
                                                        <input type="file" class="custom-file-input input-sm" name="excel_file" id="excel_file" accept=".xlsx,.xls,.csv" required>
                                                        <label class="custom-file-label text-sm" for="excel_file">Pilih file...</label>
                                                    </div>
                                                    <div class="input-group-append">
                                                        <button type="submit" class="btn btn-sm btn-outline-info button-cek-permission" data-permission="forecasts.upload_excel" id="uploadBtn">
                                                            <i class="fas fa-upload"></i> Unggah Forecast
                                                        </button>
                                                    </div>
                                                </div>
                                                <small class="form-text text-muted text-sm">
                                                    Format yang didukung: .xlsx, .xls, .csv (Maks: 10MB)
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <!-- Upload Instructions -->
                                    <div class="alert alert-info mt-4 text-sm">
                                        <h5><i class="icon fas fa-info"></i> Instruksi Upload</h5>
                                        <ul class="mb-0">
                                            <li>Unduh template terlebih dahulu untuk melihat format yang diperlukan</li>
                                            <li>Struktur kolom: <strong>store_code | raw_material_code | raw_material_name | uom | 2026-01-01 | 2026-01-02 | ...</strong></li>
                                            <li>Kolom pertama: <strong>store_code</strong> (harus ada di sistem dan user harus punya akses)</li>
                                            <li>Kolom kedua: <strong>raw_material_code</strong> (harus ada di sistem)</li>
                                            <li>Kolom ketiga: <strong>raw_material_name</strong> (hanya untuk referensi)</li>
                                            <li>Kolom keempat: <strong>uom</strong> (satuan, hanya untuk referensi)</li>
                                            <li>Kolom tanggal: <strong>2026-01-01, 2026-01-02, 2026-01-03, ...</strong> (semua tanggal di bulan yang dipilih)</li>
                                            <li><strong>Dukungan multi-store:</strong> Satu file bisa berisi data untuk beberapa store</li>
                                            <li><strong>Pengelompokan otomatis:</strong> Sistem akan otomatis mengelompokkan data per store dan membuat header forecast terpisah</li>
                                            <li><strong>Maksimal 31 kolom tanggal</strong> per upload</li>
                                            <li><strong>Tidak boleh backdate:</strong> Forecast hanya bisa diupload untuk bulan berjalan atau bulan mendatang</li>
                                            <li><strong>Validasi akses:</strong> User harus punya akses ke semua store yang ada di file upload</li>
                                            <li><strong>Upsert otomatis:</strong> Jika forecast sudah ada untuk suatu store, data akan di-upsert (insert baru atau update yang sudah ada)</li>
                                            <li>Setiap baris mewakili satu raw material untuk satu store dengan quantity untuk setiap tanggal</li>
                                            <li>Kosongkan sel atau isi 0 untuk tanggal yang tidak ada forecast</li>
                                            <li>Hanya store_code dan raw_material_code yang digunakan untuk validasi, kolom lain hanya referensi</li>
                                            <li>Ukuran file maksimal: <strong>10MB</strong></li>
                                            <li>Format yang didukung: <strong>.xlsx, .xls, .csv</strong></li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <a href="{{ route('stores.index') }}" class="btn btn-outline-warning btn-sm" data='back' onclick="return notificationBeforeBack(event, this);"><i class="fas fa-arrow-left"></i> Kembali</a>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
    $(document).ready(function() {
        // File input change event
        $('#excel_file').on('change', function() {
            const fileName = $(this).val().split('\\').pop();
            $(this).next('.custom-file-label').html(fileName);
        });

        // Download template with selected year/month
        $('#downloadTemplateBtn').click(function() {
            const year = $('#year').val();
            const month = $('#month').val();

            if (!year || !month) {
                Swal.fire('Peringatan', 'Silakan pilih tahun dan bulan terlebih dahulu', 'warning');
                return;
            }

            const url = '{{ route("forecasts.download_template") }}?year=' + year + '&month=' + month;
            window.location.href = url;
        });

        // Form submission
        $('#uploadForm').submit(function(e) {
            e.preventDefault();

            const formData = new FormData(this);

            // Show progress
            $('#uploadProgress').show();
            $('#loaderkdnknz').show();
            $('#uploadResults').hide();
            $('#uploadBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Mengupload...');

            // Simulate progress
            let progress = 0;
            const progressInterval = setInterval(function() {
                progress += Math.random() * 15;
                if (progress > 90) progress = 90;
                $('.progress-bar').css('width', progress + '%');
            }, 200);

            $.ajax({
                url: '{{ route("forecasts.upload_excel") }}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    clearInterval(progressInterval);
                    $('.progress-bar').css('width', '100%');

                    setTimeout(function() {
                        $('#uploadProgress').hide();
                        $('#loaderkdnknz').hide();
                        $('#uploadResults').show();

                        let resultsHtml = '';
                        if (response.success) {
                            resultsHtml = `
                            <div class="alert alert-success">
                                <h5><i class="icon fas fa-check"></i> Unggah Berhasil!</h5>
                                <p><strong>Total Berhasil:</strong> ${response.total_success} records</p>
                                <p><strong>Total Ditambahkan:</strong> ${response.total_inserted} records</p>
                                <p><strong>Total Gagal:</strong> ${response.total_errors} records</p>
                            </div>
                        `;

                            // Show per-store results
                            if (response.stores) {
                                resultsHtml += `<div class="alert alert-info"><h6>Hasil Per-Store:</h6><ul class="mb-0">`;
                                Object.keys(response.stores).forEach(function(storeCode) {
                                    const storeResult = response.stores[storeCode];
                                    resultsHtml += `<li><strong>${storeCode}:</strong> ${storeResult.success_count} berhasil, ${storeResult.error_count} gagal</li>`;
                                });
                                resultsHtml += `</ul></div>`;
                            }

                            if (response.errors && response.errors.length > 0) {
                                resultsHtml += `
                                <div class="alert alert-danger">
                                    <h6>Detail Error:</h6>
                                    <ul class="mb-0">
                            `;
                                response.errors.slice(0, 20).forEach(function(error) {
                                    resultsHtml += `<li>${error}</li>`;
                                });
                                if (response.errors.length > 20) {
                                    resultsHtml += `<li>... dan ${response.errors.length - 20} error lainnya</li>`;
                                }
                                resultsHtml += `</ul></div>`;
                            }

                            // Reset form if successful
                            if (response.total_errors === 0) {
                                $('#uploadForm')[0].reset();
                                $('.custom-file-label').html('Pilih file...');
                            }
                        } else {
                            resultsHtml = `
                            <div class="alert alert-danger">
                                <h5><i class="icon fas fa-ban"></i> Unggah Gagal!</h5>
                                <p>${response.message}</p>
                            </div>
                        `;
                        }

                        $('#resultsContent').html(resultsHtml);
                    }, 500);
                },
                error: function(xhr) {
                    clearInterval(progressInterval);
                    $('#uploadProgress').hide();
                    $('#loaderkdnknz').hide();
                    $('#uploadResults').show();

                    let errorMessage = 'Terjadi kesalahan saat upload.';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    } else if (xhr.responseJSON && xhr.responseJSON.errors) {
                        const errors = xhr.responseJSON.errors;
                        errorMessage = Object.values(errors).flat().join('<br>');
                    }

                    $('#resultsContent').html(`
                    <div class="alert alert-danger">
                        <h5><i class="icon fas fa-ban"></i> Unggah Gagal!</h5>
                        <p>${errorMessage}</p>
                    </div>
                `);
                },
                complete: function() {
                    $('#uploadBtn').prop('disabled', false).html('<i class="fas fa-upload"></i> Unggah Forecast');
                }
            });
        });
    });
</script>
@endsection