@extends('user.layout.main')

@section('title', 'Sistem Prediksi PeGas')

@section('content')
    <div class="container-fluid">
        <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">
                Prediksi Jumlah Stok LPG Selama 180 Hari Kedepan
                <span id="serverStatusBadge" class="badge badge-secondary ml-2"
                    style="font-size: 0.8rem; vertical-align: middle;">
                    <i class="fas fa-spinner fa-spin mr-1"></i> Memeriksa Server...
                </span>
            </h1>
            <button id="btnPredictAction" class="btn btn-primary shadow-sm" onclick="runFullPrediction()" disabled>
                <i class="fas fa-sync fa-sm text-white-50 mr-2"></i> Lakukan Prediksi Baru
            </button>
        </div>

        <div class="row">
            <div class="col-12">
                <div class="alert alert-info border-left-info shadow-sm py-3" role="alert">
                    <div class="row no-gutters align-items-center">
                        <div class="col-auto mr-3">
                            <i class="fas fa-info-circle fa-2x text-info"></i>
                        </div>
                        <div class="col">
                            <h6 class="m-0 font-weight-bold text-info">Catatan Informasi</h6>
                            <p class="mb-0 text-dark" style="font-size: 0.9rem;">
                                Hasil peramalan ini merupakan alat bantu estimasi jumlah stok lpg dengan mempertimbangkan
                                pola penjualan. Ketersediaan stok secara nyata tetap dipengaruhi oleh jadwal pengiriman dan
                                regulasi dari agen. gunakan batas bawah sebagai minimal stok dan batas atas sebagai maksimal
                                stok yang diperlukan
                                <br><strong>Penting:</strong> Prediksi hari Minggu bernilai <strong>0</strong> (Libur agen).
                                Untuk mengunduh (Excel) atau <span class="text-danger font-weight-bold">menghapus hasil
                                    prediksi</span>, silakan kunjungi menu <strong>Riwayat</strong>.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between bg-white">
                <h6 class="m-0 font-weight-bold text-primary">Grafik Estimasi Permintaan</h6>

                <div id="chartControls" class="{{ count($hasilPrediksi) > 0 ? '' : 'd-none' }}">
                    <div class="d-flex align-items-center">
                        <span class="text-xs mr-3 text-gray-600 d-none d-md-inline">
                            <i class="fas fa-hand-point-right mr-1 text-primary"></i>
                            Pilih rentang waktu hasil prediksi untuk ditampilkan pada chart:
                        </span>
                        <select id="rangeSelector" class="form-control form-control-sm shadow-sm" style="width: 250px;"
                            onchange="updateChartDisplay()">
                            <option value="30">Tampilkan 1 Bulan (Harian)</option>
                            <option value="60">Tampilkan 2 Bulan (Harian)</option>
                            <option value="90">Tampilkan 3 Bulan (Harian)</option>
                            <option value="120">Tampilkan 4 Bulan (Mingguan)</option>
                            <option value="150">Tampilkan 5 Bulan (Mingguan)</option>
                            <option value="180">Tampilkan 6 Bulan (Mingguan)</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div id="noDataState" class="text-center py-5 {{ count($hasilPrediksi) > 0 ? 'd-none' : '' }}">
                    <i class="fas fa-chart-area fa-4x text-gray-300 mb-3"></i>
                    <h5 class="text-gray-500">Belum ada data hasil prediksi. Silahkan klik tombol <strong>Lakukan Prediksi
                            Baru</strong>.</h5>
                </div>
                <div id="chartWrapper" class="{{ count($hasilPrediksi) > 0 ? '' : 'd-none' }}">
                    <div class="chart-area" style="height: 400px;">
                        <canvas id="predictionChart"></canvas>
                    </div>
                    <div class="text-center mt-2">
                        <small class="text-muted"><i class="fas fa-search-plus mr-1"></i> Gunakan scroll mouse untuk Zoom
                            In/Out pada grafik</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="card shadow mb-4">
            <div class="card-header py-3 bg-white">
                <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-table mr-1"></i> Rincian Angka Prediksi
                    (Harian)</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="dataTable-Prediction" width="100%"
                        cellspacing="0">
                        <thead class="bg-gray-100 text-primary">
                            <tr>
                                <th>No</th>
                                <th>Hari & Tanggal</th>
                                <th>Estimasi (Tabung)</th>
                                <th>Batas Bawah</th>
                                <th>Batas Atas</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($hasilPrediksi as $index => $row)
                                <tr>
                                    <td>{{ $index + 1 }}</td>
                                    <td>{{ \Carbon\Carbon::parse($row->tanggal)->locale('id')->translatedFormat('l, d F Y') }}
                                    </td>
                                    <td><span class="badge badge-primary px-3">{{ $row->estimasi }}</span></td>
                                    <td class="text-danger font-weight-bold">{{ $row->batas_bawah }}</td>
                                    <td class="text-success font-weight-bold">{{ $row->batas_atas }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom"></script>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

        <script>
            let myChart = null;
            let rawData = @json($hasilPrediksi);
            let dataTable = null;

            $(document).ready(function() {
                // Cek status server Flask saat halaman dibuka
                checkServerConnection();

                if ($.fn.DataTable.isDataTable('#dataTable-Prediction')) {
                    $('#dataTable-Prediction').DataTable().destroy();
                }

                dataTable = $('#dataTable-Prediction').DataTable({
                    "pageLength": 10,
                    "lengthMenu": [
                        [10, 50, 100, -1],
                        [10, 50, 100, "Semua"]
                    ],
                    "language": {
                        "search": "Cari data:",
                        "lengthMenu": "Tampilkan _MENU_ data",
                        "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
                        "zeroRecords": "Data tidak ditemukan",
                        "paginate": {
                            "next": "Berikutnya",
                            "previous": "Sebelumnya"
                        }
                    },
                    "order": [
                        [0, "asc"]
                    ]
                });

                if (rawData.length > 0) {
                    updateChartDisplay();
                }
            });

            // FUNGSI BARU: AJAX Cek Status Server Finis
            function checkServerConnection() {
                const badge = document.getElementById('serverStatusBadge');
                const btnPredict = document.getElementById('btnPredictAction');

                fetch("{{ url('user/prediksi/check-status') }}")
                    .then(res => res.json())
                    .then(data => {
                        badge.className = ""; // Reset class

                        if (data.status === 'connected') {
                            badge.classList.add('badge', 'badge-info', 'px-2', 'py-1'); // Biru muda (Bootstrap info)
                            badge.innerHTML = `<i class="fas fa-check-circle mr-1"></i> ${data.message}`;
                            btnPredict.removeAttribute('disabled'); // Aktifkan tombol prediksi
                        } else if (data.status === 'error_response') {
                            badge.classList.add('badge', 'badge-danger', 'px-2', 'py-1'); // Merah
                            badge.innerHTML = `<i class="fas fa-exclamation-triangle mr-1"></i> ${data.message}`;
                        } else {
                            badge.classList.add('badge', 'badge-danger', 'px-2', 'py-1'); // Merah
                            badge.innerHTML = `<i class="fas fa-times-circle mr-1"></i> ${data.message}`;
                        }
                    })
                    .catch(() => {
                        badge.className = "badge badge-danger px-2 py-1";
                        badge.innerHTML = `<i class="fas fa-times-circle mr-1"></i> Server Prediksi Tidak Ditemukan`;
                    });
            }

            function runFullPrediction() {
                Swal.fire({
                    title: 'Mulai Prediksi?',
                    text: "Sistem akan menghitung estimasi jumlah stok untuk 6 bulan ke depan.",
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Ya, Hitung!',
                    confirmButtonColor: '#4e73df'
                }).then((result) => {
                    if (result.isConfirmed) {
                        Swal.fire({
                            title: 'Memproses Perhitungan...',
                            text: 'Mohon tunggu, proses ini memakan waktu beberapa saat.',
                            allowOutsideClick: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });

                        fetch("{{ url('user/prediksi/forecast') }}", {
                                method: 'POST',
                                headers: {
                                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                                    'Content-Type': 'application/json',
                                    'Accept': 'application/json'
                                }
                            })
                            .then(res => res.json())
                            .then(data => {
                                if (data.success) {
                                    Swal.fire({
                                        icon: 'success',
                                        title: 'Berhasil',
                                        text: 'Data 6 bulan telah tersimpan!',
                                        timer: 2000,
                                        showConfirmButton: false
                                    });
                                    setTimeout(() => location.reload(), 2000);
                                } else {
                                    Swal.fire('Error', data.error, 'error');
                                }
                            })
                            .catch(() => Swal.fire('Error', 'Koneksi ke server flask terputus.', 'error'));
                    }
                });
            }

            function updateChartDisplay() {
                const days = parseInt(document.getElementById('rangeSelector').value);
                if (isNaN(days)) return;

                let filtered = rawData.slice(0, days);
                let labels, values, upper, lower;

                if (days <= 90) {
                    labels = filtered.map(d => d.tanggal);
                    values = filtered.map(d => d.estimasi);
                    upper = filtered.map(d => d.batas_atas);
                    lower = filtered.map(d => d.batas_bawah);
                } else {
                    labels = [];
                    values = [];
                    upper = [];
                    lower = [];
                    for (let i = 0; i < filtered.length; i += 7) {
                        let chunk = filtered.slice(i, i + 7);
                        labels.push("Minggu " + (Math.floor(i / 7) + 1));
                        values.push(chunk.reduce((s, x) => s + x.estimasi, 0));
                        upper.push(chunk.reduce((s, x) => s + x.batas_atas, 0));
                        lower.push(chunk.reduce((s, x) => s + x.batas_bawah, 0));
                    }
                }
                renderChart(labels, values, upper, lower, days <= 90 ? 'Harian' : 'Mingguan');
            }

            function renderChart(labels, values, upper, lower, mode) {
                const ctx = document.getElementById('predictionChart').getContext('2d');
                if (myChart) myChart.destroy();

                myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [{
                                label: 'Estimasi Utama',
                                data: values,
                                borderColor: '#4e73df',
                                backgroundColor: 'rgba(78, 115, 223, 0.1)',
                                fill: false,
                                tension: 0.3,
                                zIndex: 10
                            },
                            {
                                label: 'Batas Atas',
                                data: upper,
                                borderColor: 'rgba(28, 200, 138, 0.4)',
                                borderDash: [5, 5],
                                pointRadius: 0,
                                fill: false
                            },
                            {
                                label: 'Batas Bawah',
                                data: lower,
                                borderColor: 'rgba(231, 74, 59, 0.4)',
                                borderDash: [5, 5],
                                pointRadius: 0,
                                fill: false
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            tooltip: {
                                mode: 'index',
                                intersect: false
                            },
                            zoom: {
                                pan: {
                                    enabled: true,
                                    mode: 'x'
                                },
                                zoom: {
                                    wheel: {
                                        enabled: true
                                    },
                                    pinch: {
                                        enabled: true
                                    },
                                    mode: 'x',
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: 'Total Tabung (' + mode + ')'
                                }
                            }
                        }
                    }
                });
            }
        </script>
    @endpush
@endsection
