@extends('layouts.admin')
@section('title', 'Forecasting & Prediksi Stok - SI Apotek')

@section('content')
<div class="flex flex-col xl:flex-row justify-between items-start xl:items-center mb-6 gap-4">
    <div>
        <h2 class="text-2xl font-bold text-gray-800">Forecasting (SMA - {{ $period }} Bulan)</h2>
        <p class="text-sm text-gray-500 mt-1">
            @if($isBacktest)
                Mode Uji Akurasi (Backtest) dari {{ \Carbon\Carbon::createFromFormat('Y-m', $startMonthInput)->translatedFormat('F Y') }} hingga {{ \Carbon\Carbon::createFromFormat('Y-m', $endMonthInput)->translatedFormat('F Y') }}.
            @else
                Memprediksi permintaan obat berdasarkan penjualan {{ $period }} bulan terakhir.
            @endif
        </p>
    </div>
    
    <div class="flex flex-col items-end gap-2 w-full xl:w-auto">
        <form action="{{ route('forecasting.index') }}" method="GET" class="flex flex-wrap items-center justify-end gap-3 w-full">
            <div class="flex items-center gap-2 bg-white p-1 rounded-lg border shadow-sm">
                <label class="text-xs font-semibold text-gray-500 uppercase px-2">Periode</label>
                <select name="period" class="px-2 py-1 text-sm border-0 focus:ring-0 bg-transparent font-bold text-emerald-700">
                    @for($i = 1; $i <= 12; $i++)
                        <option value="{{ $i }}" {{ $period == $i ? 'selected' : '' }}>{{ $i }} Bulan</option>
                    @endfor
                </select>
            </div>
            
            <div class="flex items-center gap-2 bg-white p-1 rounded-lg border shadow-sm">
                <label class="text-xs font-semibold text-gray-500 uppercase px-2">Kategori</label>
                <select name="category_id" class="px-2 py-1 text-sm border-0 focus:ring-0 bg-transparent font-bold text-emerald-700 max-w-[150px]">
                    <option value="">Semua</option>
                    @foreach($categories as $category)
                        <option value="{{ $category->id }}" {{ $selectedCategory == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
                    @endforeach
                </select>
            </div>

            <!-- Backtest Range -->
            <div class="flex items-center gap-2 bg-white p-1 rounded-lg border shadow-sm border-blue-200">
                <label class="text-xs font-semibold text-blue-500 uppercase px-2">Uji Akurasi</label>
                <input type="month" name="start_month" value="{{ $startMonthInput }}" class="px-2 py-1 text-sm border-0 focus:ring-0 bg-transparent font-bold text-blue-700" title="Bulan Awal Uji">
                <span class="text-gray-400">-</span>
                <input type="month" name="end_month" value="{{ $endMonthInput }}" class="px-2 py-1 text-sm border-0 focus:ring-0 bg-transparent font-bold text-blue-700" title="Bulan Akhir Uji">
            </div>

            <div class="flex gap-2">
                <button type="submit" class="px-4 py-2 text-sm font-bold text-white bg-emerald-600 rounded-lg hover:bg-emerald-700 transition shadow-sm">
                    Terapkan
                </button>
                @if($isBacktest || $selectedCategory || $period != 3)
                    <a href="{{ route('forecasting.index') }}" class="px-4 py-2 text-sm font-bold text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 transition shadow-sm">
                        Reset
                    </a>
                @endif
            </div>
        </form>
    </div>
</div>

<!-- START CHARTS -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
    <!-- Chart 1: Trend Keseluruhan -->
    <div class="bg-white p-5 rounded-xl border border-gray-200 shadow-sm">
        <h3 class="font-bold text-gray-800 mb-4">
            @if($isBacktest)
                Perbandingan Aktual vs Prediksi Total
            @else
                Tren Penjualan & Prediksi Total
            @endif
        </h3>
        <div class="h-64">
            <canvas id="trendChart"></canvas>
        </div>
    </div>
    
    <!-- Chart 2: Top 5 -->
    <div class="bg-white p-5 rounded-xl border border-gray-200 shadow-sm">
        <h3 class="font-bold text-gray-800 mb-4">
            @if($isBacktest)
                Data Tidak Tersedia (Mode Uji)
            @else
                Top 5 Prediksi Permintaan Bulan Depan
            @endif
        </h3>
        <div class="h-64 flex items-center justify-center">
            @if($isBacktest)
                <p class="text-gray-400 font-medium">Chart Top 5 dinonaktifkan pada Mode Uji Akurasi.</p>
            @else
                <canvas id="top5Chart"></canvas>
            @endif
        </div>
    </div>
</div>
<!-- END CHARTS -->

<div class="w-full mb-8 overflow-hidden rounded-xl shadow-sm border border-gray-200">
    <div class="w-full overflow-x-auto" style="overflow-x: auto; max-width: 100vw;">
        <table class="w-full whitespace-nowrap min-w-max">
            <thead>
                @if($isBacktest)
                <tr class="text-xs font-bold tracking-wide text-left text-gray-600 uppercase border-b bg-gray-50">
                    <th class="px-4 py-4" rowspan="2">Obat & Kode</th>
                    <th class="px-4 py-4 text-center border-l border-gray-200" colspan="{{ count($months) }}">Aktual Penjualan (Qty) Saat Uji</th>
                    <th class="px-4 py-4 text-center border-l border-gray-200" rowspan="2">Rata-rata Aktual</th>
                    <th class="px-4 py-4 text-center border-l border-gray-200 bg-blue-50" rowspan="2">Rata-rata Prediksi</th>
                    <th class="px-4 py-4 text-center border-l border-gray-200" rowspan="2">Akurasi (MAPE)</th>
                </tr>
                <tr class="text-xs font-bold tracking-wide text-center text-gray-500 border-b bg-gray-50">
                    @foreach($months as $month)
                    <th class="px-2 py-2 border-l border-t border-gray-200">{{ $month->translatedFormat('F Y') }}</th>
                    @endforeach
                </tr>
                @else
                <tr class="text-xs font-bold tracking-wide text-left text-gray-600 uppercase border-b bg-gray-50">
                    <th class="px-4 py-4" rowspan="2">Obat & Kode</th>
                    <th class="px-4 py-4 text-center border-l border-gray-200" colspan="{{ $period }}">Data Historis Penjualan (Qty)</th>
                    <th class="px-4 py-4 text-center border-l border-gray-200 bg-emerald-50" rowspan="2">
                        Prediksi<br>
                        <span class="text-emerald-600">{{ $forecasts[0]->next_month ?? 'Bulan Depan' }}</span>
                    </th>
                    <th class="px-4 py-4 text-center" rowspan="2">Stok Saat Ini</th>
                    <th class="px-4 py-4 text-center" rowspan="2">Status Rekomendasi</th>
                </tr>
                <tr class="text-xs font-bold tracking-wide text-center text-gray-500 border-b bg-gray-50">
                    @foreach($months as $month)
                    <th class="px-2 py-2 border-l border-t border-gray-200">{{ $month->translatedFormat('F Y') }}</th>
                    @endforeach
                </tr>
                @endif
            </thead>
            <tbody class="bg-white divide-y divide-gray-100">
                @forelse($forecasts as $data)
                <tr class="text-gray-700 hover:bg-gray-50 transition-colors">
                    <td class="px-4 py-3">
                        <div class="font-bold text-gray-800">{{ $data->medicine->name }}</div>
                        <div class="text-xs text-gray-500">{{ $data->medicine->code }} | {{ $data->medicine->category->name ?? '-' }}</div>
                    </td>
                    
                    @if($isBacktest)
                    @foreach($data->details as $hist)
                    <td class="px-4 py-3 text-center border-l border-gray-100 font-medium text-gray-600">{{ $hist['actual'] }}</td>
                    @endforeach
                    <td class="px-4 py-3 text-center border-l border-gray-100 font-medium text-gray-600">
                        {{ $data->avg_actual }}
                    </td>
                    <td class="px-4 py-3 text-center border-l border-gray-100 font-bold text-blue-700 bg-blue-50/50 text-lg">
                        {{ $data->avg_forecast }}
                    </td>
                    <td class="px-4 py-3 text-center border-l border-gray-100">
                        @if($data->accuracy >= 80)
                            <span class="px-3 py-1 font-bold leading-tight text-emerald-700 bg-emerald-100 rounded-full text-sm inline-block">
                                {{ $data->accuracy }}%
                            </span>
                        @elseif($data->accuracy >= 50)
                            <span class="px-3 py-1 font-bold leading-tight text-orange-700 bg-orange-100 rounded-full text-sm inline-block">
                                {{ $data->accuracy }}%
                            </span>
                        @else
                            <span class="px-3 py-1 font-bold leading-tight text-red-700 bg-red-100 rounded-full text-sm inline-block">
                                {{ $data->accuracy }}%
                            </span>
                        @endif
                    </td>
                    @else
                        @foreach($data->history as $hist)
                        <td class="px-4 py-3 text-center border-l border-gray-100 font-medium text-gray-600">{{ $hist['qty'] }}</td>
                        @endforeach
                        <td class="px-4 py-3 text-center border-l border-gray-100 font-bold text-emerald-700 bg-emerald-50/50 text-lg">
                            {{ $data->forecast }}
                        </td>
                        <td class="px-4 py-3 text-center font-bold text-gray-700">
                            {{ $data->medicine->current_stock }}
                        </td>
                        <td class="px-4 py-3 text-center">
                            <span class="px-3 py-1 font-semibold leading-tight text-{{ $data->status_color }}-700 bg-{{ $data->status_color }}-100 rounded-full text-xs inline-block w-full max-w-[140px]">
                                {{ $data->status }}
                            </span>
                        </td>
                    @endif
                </tr>
                @empty
                <tr>
                    <td colspan="{{ $isBacktest ? (4 + count($months)) : (4 + $period) }}" class="px-4 py-10 text-center text-gray-500">
                        <svg class="w-12 h-12 mx-auto text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
                        Belum ada data obat untuk di-forecast.
                    </td>
                </tr>
                @endforelse
            </tbody>
        </table>
    </div>
</div>

@if(!$isBacktest)
<!-- Info Panel -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
    <div class="bg-white p-5 rounded-xl border border-gray-200 shadow-sm">
        <h4 class="font-bold text-gray-800 flex items-center gap-2 mb-2">
            <span class="w-3 h-3 rounded-full bg-emerald-500"></span> Aman / Normal
        </h4>
        <p class="text-sm text-gray-600">Stok obat saat ini mencukupi untuk memenuhi prediksi permintaan bulan depan.</p>
    </div>
    <div class="bg-white p-5 rounded-xl border border-gray-200 shadow-sm">
        <h4 class="font-bold text-gray-800 flex items-center gap-2 mb-2">
            <span class="w-3 h-3 rounded-full bg-red-500"></span> Potensi Stockout
        </h4>
        <p class="text-sm text-gray-600">Stok saat ini kurang dari prediksi bulan depan. Segera lakukan <b>Restock</b>!</p>
    </div>
    <div class="bg-white p-5 rounded-xl border border-gray-200 shadow-sm">
        <h4 class="font-bold text-gray-800 flex items-center gap-2 mb-2">
            <span class="w-3 h-3 rounded-full bg-orange-500"></span> Potensi Overstock
        </h4>
        <p class="text-sm text-gray-600">Stok saat ini jauh melebihi rata-rata prediksi permintaan. Tunda restock untuk menghindari obat expired sebelum terjual.</p>
    </div>
</div>
@endif
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Data from Controller
        const chartData = @json($chartData);
        
        // Render Trend Chart
        const ctxTrend = document.getElementById('trendChart').getContext('2d');
        
        let datasets = [];
        
        if (chartData.is_backtest) {
            datasets = [
                {
                    label: 'Aktual Penjualan (Qty)',
                    data: chartData.actual,
                    backgroundColor: 'rgba(59, 130, 246, 0.2)', // Blue
                    borderColor: 'rgba(59, 130, 246, 1)',
                    borderWidth: 2,
                    fill: false,
                    tension: 0.3,
                    pointBackgroundColor: 'rgba(59, 130, 246, 1)',
                },
                {
                    label: 'Prediksi (Qty)',
                    data: chartData.forecast,
                    backgroundColor: 'rgba(16, 185, 129, 0.2)', // Emerald
                    borderColor: 'rgba(16, 185, 129, 1)',
                    borderWidth: 2,
                    borderDash: [5, 5], // Dashed line for forecast
                    fill: false,
                    tension: 0.3,
                    pointBackgroundColor: 'rgba(16, 185, 129, 1)',
                }
            ];
        } else {
            datasets = [{
                label: 'Total Penjualan (Qty)',
                data: chartData.trend,
                backgroundColor: 'rgba(16, 185, 129, 0.2)', // Emerald
                borderColor: 'rgba(16, 185, 129, 1)',
                borderWidth: 2,
                fill: true,
                tension: 0.3,
                pointBackgroundColor: 'rgba(16, 185, 129, 1)',
            }];
        }

        new Chart(ctxTrend, {
            type: 'line',
            data: {
                labels: chartData.labels,
                datasets: datasets
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });

        // Render Top 5 Bar Chart (Only if not backtest)
        if (!chartData.is_backtest) {
            const top5Data = @json($top5Forecasts ?? []);
            const ctxTop5 = document.getElementById('top5Chart').getContext('2d');
            const top5Labels = top5Data.map(item => item.name);
            const top5Values = top5Data.map(item => item.forecast);
            
            new Chart(ctxTop5, {
                type: 'bar',
                data: {
                    labels: top5Labels,
                    datasets: [{
                        label: 'Prediksi Permintaan (Qty)',
                        data: top5Values,
                        backgroundColor: 'rgba(59, 130, 246, 0.6)', // Blue
                        borderColor: 'rgba(59, 130, 246, 1)',
                        borderWidth: 1,
                        borderRadius: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: { beginAtZero: true }
                    }
                }
            });
        }
    });
</script>
@endpush
