@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">
                    <div class="card-header">
                        <h3 class="card-title">{!! $variables['judul'] !!}</h3>
                        <div class="card-tools">
                            <a href="{{ route('forecasts.index') }}" class="btn btn-sm btn-warning">
                                <i class="fas fa-arrow-left"></i> Kembali ke Daftar
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- Forecast Header Info -->
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="30%"><strong>Nomor Forecast</strong></td>
                                        <td>: {{ $forecast->forecast_number }}</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Store</strong></td>
                                        <td>: {{ $forecast->store->name ?? '' }}</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Periode</strong></td>
                                        <td>: {{ $forecast->month_name }} {{ $forecast->year }}</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Tanggal Upload</strong></td>
                                        <td>: {{ $forecast->upload_date->format('d M Y') }}</td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <td width="30%"><strong>Status</strong></td>
                                        <td>: <span class="badge badge-{{ $forecast->status_badge_class }}">{{ $forecast->status }}</span></td>
                                    </tr>
                                    <tr>
                                        <td><strong>Dibuat Oleh</strong></td>
                                        <td>: {{ $forecast->creator->fullname ?? 'System' }} ({{ $forecast->created_at->format('d M Y, H:i') }})</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Diubah Oleh</strong></td>
                                        <td>: {{ $forecast->modificator->fullname ?? '-' }} ({{ $forecast->updated_at ? $forecast->updated_at->format('d M Y, H:i') : '-' }})</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Total Item</strong></td>
                                        <td>: {{ $forecast->activeDetails->groupBy('raw_material_id')->count() }} material</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Rentang Tanggal</strong></td>
                                        <td>: 
                                            @if(count($forecastData['dates']) > 0)
                                            {{ $forecastData['dates']->first()->format('d M Y') }} - {{ $forecastData['dates']->last()->format('d M Y') }}
                                            @else
                                            Tidak ada tanggal
                                            @endif
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="row mb-3">
                            <div class="col-12">
                                <div class="btn-group">
                                    @if($forecast->status == 'Draft')
                                    <button type="button" class="btn btn-sm btn-warning button-cek-permission" data-permission="forecasts.confirm" id="approve-btn">
                                        <i class="fas fa-check"></i> Konfirmasi Forecast
                                    </button>                                    
                                    <button type="button" class="btn btn-sm btn-warning button-cek-permission" data-permission="forecasts.replace_data" id="replace-data-btn">
                                        <i class="fas fa-upload"></i> Ganti Data
                                    </button>
                                    @endif
                                    <button type="button" class="btn btn-sm btn-warning button-cek-permission" data-permission="forecasts.export_horizontal" id="export-data-btn">
                                        <i class="fas fa-download"></i> Ekspor Data
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Replace Progress -->
                        <div id="replaceProgress" 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">Mengganti data...</p>
                        </div>

                        <!-- Replace Results -->
                        <div id="replaceResults" class="mt-4" style="display: none;">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title">Hasil Penggantian</h5>
                                </div>
                                <div class="card-body">
                                    <div id="replaceResultsContent"></div>
                                </div>
                            </div>
                        </div>

                        <!-- Forecast Details -->
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">Detail Forecast</h5>
                            </div>
                            <div class="card-body">
                                @if(count($forecastData['materials']) > 0)
                                <div class="table-responsive">
                                    <table id="details_table" class="table table-hover table-sm">
                                        <thead class="bg-light">
                                            <tr>
                                                <th style="min-width: 120px;">Kode Item</th>
                                                <th style="min-width: 200px;">Nama Item</th>
                                                <th style="min-width: 60px;">UOM</th>
                                                @foreach($forecastData['dates'] as $date)
                                                <th class="text-center" style="min-width: 80px;">
                                                    <div>{{ $date->format('d') }}</div>
                                                    <small class="text-muted text-sm">{{ $date->format('M') }}</small>
                                                </th>
                                                @endforeach
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($forecastData['materials'] as $material)
                                            <tr>
                                                <td><strong>{{ $material['raw_material_code'] }}</strong></td>
                                                <td>{{ $material['raw_material_name'] }}</td>
                                                <td class="text-center">{{ $material['uom'] }}</td>
                                                @foreach($forecastData['dates'] as $date)
                                                @php
                                                $dateKey = $date->format('Y-m-d');
                                                $qty = $material['dates'][$dateKey]['qty'] ?? 0;
                                                @endphp
                                                <td class="text-right">
                                                    @if($qty > 0)
                                                    <span class="badge badge-info">{{ number_format($qty, 2) }}</span>
                                                    @else
                                                    <span class="text-muted text-sm">-</span>
                                                    @endif
                                                </td>
                                                @endforeach
                                            </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                                @else
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle"></i> Tidak ada detail forecast ditemukan.
                                </div>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Replace Data Modal -->
<div class="modal fade" id="replaceDataModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Ganti Data Forecast</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form id="replaceDataForm" enctype="multipart/form-data">
                @csrf
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-exclamation-triangle"></i>
                        <strong>Peringatan:</strong> Ini akan mengganti semua data forecast yang ada untuk periode ini. Tindakan ini tidak dapat dibatalkan.
                    </div>

                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        <strong>Persyaratan Upload:</strong>
                        <ul class="mb-0 mt-2">
                            <li><strong>Maksimal 31 kolom tanggal</strong> per upload</li>
                            <li><strong>Tidak boleh backdate:</strong> Forecast hanya bisa diganti untuk bulan berjalan atau bulan mendatang</li> 
                            <li>Format yang didukung: <strong>.xlsx, .xls, .csv</strong> (Maks: <strong>10MB</strong>)</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" name="excel_file" id="replace_excel_file" accept=".xlsx,.xls,.csv" required>
                            <label class="custom-file-label" for="replace_excel_file">Pilih file...</label>
                        </div>
                        <small class="form-text text-muted text-sm">
                            Format yang didukung: .xlsx, .xls, .csv (Maks: 10MB)
                        </small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-warning" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-sm btn-info button-cek-permission" data-permission="forecasts.replace_data" id="replaceBtn">
                        <i class="fas fa-upload"></i> Ganti Data
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
    $(document).ready(function() {
        // Initialize DataTable for details
        $('#details_table').DataTable({
            "responsive": false, // Disable responsive to maintain horizontal scroll
            "lengthChange": true,
            "autoWidth": false,
            "pageLength": 25,
            "scrollX": true, // Enable horizontal scrolling for many date columns
            "scrollCollapse": true,
            "order": [
                [0, "asc"]
            ], // Sort by raw material code
            "columnDefs": [{
                    "targets": [0, 1, 2], // Raw material code, name, UOM columns
                    "className": "text-left"
                },
                {
                    "targets": [0, 1, 2], // Fixed columns
                    "width": "auto"
                }
            ],
            "fixedColumns": {
                "leftColumns": 3 // Fix first 3 columns (code, name, UOM) when scrolling horizontally
            },
            "language": {
                "emptyTable": "Tidak ada data forecast tersedia",
                "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ material",
                "infoEmpty": "Menampilkan 0 sampai 0 dari 0 material",
                "lengthMenu": "Tampilkan _MENU_ data",
                "search": "Cari:",
                "paginate": {
                    "first": "Pertama",
                    "last": "Terakhir",
                    "next": "Selanjutnya",
                    "previous": "Sebelumnya"
                }
            }
        });

        // Replace data button
        $('#replace-data-btn').click(function() {
            $('#replaceDataModal').modal('show');
        });

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

        // Replace data form submission
        $('#replaceDataForm').submit(function(e) {
            e.preventDefault();

            const formData = new FormData(this);

            // Show progress
            $('#replaceProgress').show();
            $('#loaderkdnknz').show();
            $('#replaceResults').hide();
            $('#replaceBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Mengganti...');
            $('#replaceDataModal').modal('hide');

            // 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.replace_data", $forecast->id) }}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    clearInterval(progressInterval);
                    $('.progress-bar').css('width', '100%');

                    setTimeout(function() {
                        $('#replaceProgress').hide();
                        $('#loaderkdnknz').hide();
                        $('#replaceResults').show();

                        let resultsHtml = '';
                        if (response.success) {
                            resultsHtml = `
                            <div class="alert alert-success">
                                <h5><i class="icon fas fa-check"></i> Penggantian Berhasil!</h5>
                                <p><strong>Total Berhasil:</strong> ${response.success_count} records</p>
                                <p><strong>Diupdate:</strong> ${response.update_count} records</p>
                                <p><strong>Ditambahkan:</strong> ${response.insert_count} records</p>
                                ${response.delete_count > 0 ? `<p><strong>Dihapus:</strong> ${response.delete_count} records</p>` : ''}
                                <p><strong>Gagal:</strong> ${response.error_count} records</p>
                            </div>
                        `;

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

                            // Reload page after successful replacement
                            setTimeout(function() {
                                location.reload();
                            }, 3000);
                        } else {
                            resultsHtml = `
                            <div class="alert alert-danger">
                                <h5><i class="icon fas fa-ban"></i> Penggantian Gagal!</h5>
                                <p>${response.message}</p>
                            </div>
                        `;
                        }

                        $('#replaceResultsContent').html(resultsHtml);
                    }, 500);
                },
                error: function(xhr) {
                    clearInterval(progressInterval);
                    $('#replaceProgress').hide();
                    $('#replaceResults').show();
                    $('#loaderkdnknz').hide();

                    let errorMessage = 'Terjadi kesalahan saat penggantian data.';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    }

                    $('#replaceResultsContent').html(`
                    <div class="alert alert-danger">
                        <h5><i class="icon fas fa-ban"></i> Penggantian Gagal!</h5>
                        <p>${errorMessage}</p>
                    </div>
                `);
                },
                complete: function() {
                    $('#replaceBtn').prop('disabled', false).html('<i class="fas fa-upload"></i> Ganti Data');
                }
            });
        });

        // Confirm forecast
        $('#approve-btn').click(function() {
            Swal.fire({
                title: 'Konfirmasi Forecast?',
                text: 'Apakah Anda yakin ingin mengkonfirmasi forecast ini?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Konfirmasi!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '{{ route("forecasts.confirm") }}',
                        type: 'POST',
                        data: {
                            _token: '{{ csrf_token() }}',
                            forecast_id: {{$forecast->id}}
                        },
                        success: function(response) {
                            if (response.success) {
                                Swal.fire('Terkonfirmasi!', response.message, 'success').then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire('Error', response.message, 'error');
                            }
                        },
                        error: function(xhr) {
                            const message = xhr.responseJSON?.message || 'Terjadi kesalahan';
                            Swal.fire('Error', message, 'error');
                        }
                    });
                }
            });
        });

        // Export data
        $('#export-data-btn').click(function() {
            const form = $('<form>', {
                'method': 'POST',
                'action': '{{ route("forecasts.export_horizontal") }}',
                'target': '_blank'
            });

            form.append($('<input>', {
                'type': 'hidden',
                'name': '_token',
                'value': '{{ csrf_token() }}'
            }));

            form.append($('<input>', {
                'type': 'hidden',
                'name': 'forecast_id',
                'value': '{{ $forecast->id }}'
            }));

            $('body').append(form);
            form.submit();
            form.remove();
        });
    });
</script>
@endsection