@extends('admin.layout.main')

@section('title', 'PeGas - Halaman Utama Admin')

@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">Halaman Utama Admin</h1>
        <button onclick="location.reload()" class="btn btn-sm btn-light shadow-sm border text-dark">
            <i class="fas fa-sync fa-sm mr-1"></i> Perbarui Data
        </button>
    </div>

    <div class="row">
        <div class="col-xl col-md-6 mb-4">
            <div class="card shadow h-100 py-2" style="border-left: 4px solid #7bb31a;">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1" style="color: #7bb31a;">Total Pengguna</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $totalUser }}</div>
                        </div>
                        <div class="col-auto"><i class="fas fa-users fa-2x text-gray-300"></i></div>
                    </div>
                </div>
            </div>
        </div>

        @php
            $cards = [
                ['title' => 'Rerata Penjualan', 'val' => $rerataPenjualan . ' Tbg', 'color' => 'success', 'icon' => 'chart-area'],
                ['title' => 'Bantuan', 'val' => $pendingBantuan, 'color' => 'danger', 'icon' => 'comments'],
                ['title' => 'Artikel', 'val' => $totalArtikel, 'color' => 'info', 'icon' => 'newspaper'],
                ['title' => 'Pertanyaan Umum', 'val' => $totalFaq, 'color' => 'warning', 'icon' => 'question-circle'],
            ];
        @endphp
        @foreach($cards as $card)
        <div class="col-xl col-md-6 mb-4">
            <div class="card border-left-{{ $card['color'] }} shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-{{ $card['color'] }} text-uppercase mb-1">{{ $card['title'] }}</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $card['val'] }}</div>
                        </div>
                        <div class="col-auto"><i class="fas fa-{{ $card['icon'] }} fa-2x text-gray-300"></i></div>
                    </div>
                </div>
            </div>
        </div>
        @endforeach
    </div>

    <div class="row">
        <div class="col-xl-8 col-lg-7">
            <div class="card shadow mb-4">
                <div class="card-header bg-white py-3 d-flex flex-row align-items-center justify-content-between border-0">
                    <h6 class="m-0 font-weight-bold align-self-center" style="color: #7bb31a;">Tren Penjualan (Data Asli)</h6>
                    <div style="min-width: 280px;">
                        <form action="{{ request()->url() }}" method="GET" id="filterPangkalanForm">
                            <select name="pangkalan_id" class="form-control form-control-sm text-dark font-weight-bold shadow-sm" onchange="document.getElementById('filterPangkalanForm').submit();">
                                <option value="" {{ $selectedPangkalanId === null ? 'selected' : '' }}>-- Akumulasi Gabungan (Semua Pangkalan) --</option>
                                @foreach($pangkalanList as $p)
                                    <option value="{{ $p->id }}" {{ $selectedPangkalanId === $p->id ? 'selected' : '' }}>
                                        {{ $p->name }}
                                    </option>
                                @endforeach
                            </select>
                        </form>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-area d-flex align-items-center justify-content-center" style="position: relative; min-height: 320px;">
                        @if($chartDates->isEmpty() || $totalDataAsliTersedia == 0)
                            <div class="text-muted small font-italic text-center">Data belum tersedia</div>
                        @else
                            <canvas id="multiLineChart" 
                                    data-labels="{{ json_encode($chartLabels) }}"
                                    data-datasets="{{ json_encode($lineChartData) }}"></canvas>
                        @endif
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-4 col-lg-5">
            <div class="card shadow mb-4">
                <div class="card-header bg-white py-3 border-0">
                    <h6 class="m-0 font-weight-bold" style="color: #7bb31a;">Dominasi Volume Jual</h6>
                </div>
                <div class="card-body">
                    <div class="chart-pie pt-4 pb-2">
                        <canvas id="dominasiPieChart"
                                data-rendah="{{ $pieData['rendah'] }}"
                                data-sedang="{{ $pieData['sedang'] }}"
                                data-tinggi="{{ $pieData['tinggi'] }}"></canvas>
                    </div>
                    <div class="mt-4 text-center small">
                        <span class="mr-2 text-info"><i class="fas fa-circle"></i> Kurang dari 10</span>
                        <span class="mr-2 text-warning"><i class="fas fa-circle"></i> 10 Sampai 15</span>
                        <span class="mr-2" style="color: #7bb31a;"><i class="fas fa-circle"></i> Lebih dari 15</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card shadow mb-4">
                <div class="card-header bg-white py-3 d-flex flex-row align-items-center justify-content-between border-0">
                    <h6 class="m-0 font-weight-bold text-success">Estimasi Hasil Prediksi Seluruh Pangkalan</h6>
                    <span class="badge badge-{{ $selectedPangkalanId !== null ? 'success' : 'secondary' }} text-xs px-2 py-1 shadow-sm">
                        {{ $selectedPangkalanId !== null ? 'Penyaringan Aktif' : 'Akumulasi Menyeluruh' }}
                    </span>
                </div>
                <div class="card-body">
                    <div class="chart-area d-flex align-items-center justify-content-center" style="position: relative; height: 320px;">
                        @if($predictionDates->isEmpty() || $totalPrediksiTersedia == 0)
                            <div class="text-muted small font-italic text-center">Data belum tersedia</div>
                        @else
                            <canvas id="predictionLineChart"
                                    data-labels="{{ json_encode($predictionLabels) }}"
                                    data-datasets="{{ json_encode($predictionChartData) }}"
                                    data-filtered="{{ $selectedPangkalanId !== null ? 'true' : 'false' }}"></canvas>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-6 mb-4">
            <div class="card shadow mb-4" style="min-height: 420px;">
                <div class="card-header bg-white py-3 border-0">
                    <h6 class="m-0 font-weight-bold" style="color: #7bb31a;">Aktivitas Pangkalan Terbaru</h6>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush">
                        @forelse($aktivitasPrediksi as $ap)
                            <div class="list-group-item py-3 border-bottom">
                                <div class="d-flex w-100 justify-content-between align-items-center mb-1">
                                    <h6 class="mb-0 font-weight-bold text-gray-800">{{ $ap['name'] }}</h6>
                                    <small class="font-weight-normal bg-light px-2 py-1 rounded border" style="color: #7bb31a;">
                                        <i class="far fa-clock mr-1"></i>{{ $ap['waktu']->locale('id')->diffForHumans() }}
                                    </small>
                                </div>
                                <p class="mb-0 text-muted small">
                                    <i class="fas fa-history text-xs mr-1" style="color: #7bb31a;"></i>
                                    {{ $ap['aksi'] }} pada tanggal <span class="font-weight-bold text-gray-700">{{ $ap['waktu']->locale('id')->translatedFormat('d F Y') }}</span>
                                </p>
                            </div>
                        @empty
                            <div class="text-muted small font-italic text-center py-5">Belum ada aktivitas pangkalan terbaru</div>
                        @endforelse
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-6 mb-4">
            <div class="card shadow mb-4" style="min-height: 420px;">
                <div class="card-header bg-white py-3 border-0"><h6 class="m-0 font-weight-bold text-primary">Tiket Bantuan</h6></div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm table-hover">
                            <thead><tr><th>Pangkalan</th><th>Status</th><th>Aksi</th></tr></thead>
                            <tbody>
                                @forelse($recentBantuan as $rb)
                                <tr>
                                    <td>{{ $rb->user->name }}</td>
                                    <td><span class="badge badge-{{ $rb->status == 'pending' ? 'danger' : 'success' }}">{{ $rb->status == 'pending' ? 'TERTUNDA' : 'SELESAI' }}</span></td>
                                    <td><a href="{{ route('admin.management-bantuan.index') }}" class="btn btn-xs btn-primary shadow-sm" style="background-color: #7bb31a; border-color: #7bb31a;">Balas</a></td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="3" class="text-center text-muted small font-italic py-4">Tidak ada tiket bantuan</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    const salesCanvas = document.getElementById("multiLineChart");
    if (salesCanvas) {
        const labelsData = JSON.parse(salesCanvas.dataset.labels);
        const datasetsRaw = JSON.parse(salesCanvas.dataset.datasets);

        const configuredDatasets = datasetsRaw.map(function(ds) {
            return {
                label: ds.label,
                data: ds.data,
                borderColor: '#7bb31a',
                backgroundColor: 'rgba(123, 179, 26, 0.05)',
                fill: true,
                tension: 0.3,
                pointRadius: 4
            };
        });

        new Chart(salesCanvas.getContext('2d'), {
            type: 'line',
            data: {
                labels: labelsData,
                datasets: configuredDatasets
            },
            options: {
                maintainAspectRatio: false,
                scales: {
                    y: { beginAtZero: true, ticks: { precision: 0 } }
                }
            }
        });
    }

    const pieCanvas = document.getElementById("dominasiPieChart");
    if (pieCanvas) {
        const nilaiRendah = parseInt(pieCanvas.dataset.rendah);
        const nilaiSedang = parseInt(pieCanvas.dataset.sedang);
        const nilaiTinggi = parseInt(pieCanvas.dataset.tinggi);

        new Chart(pieCanvas, {
            type: 'doughnut',
            data: {
                labels: ["Kurang dari 10", "10 Sampai 15", "Lebih dari 15"],
                datasets: [{
                    data: [nilaiRendah, nilaiSedang, nilaiTinggi],
                    backgroundColor: ['#36b9cc', '#f6c23e', '#7bb31a'],
                }]
            },
            options: { maintainAspectRatio: false }
        });
    }

    const predCanvas = document.getElementById("predictionLineChart");
    if (predCanvas) {
        const predLabels = JSON.parse(predCanvas.dataset.labels);
        const predDatasetsRaw = JSON.parse(predCanvas.dataset.datasets);
        const isPredFiltered = predCanvas.dataset.filtered === 'true';

        const configuredPredDatasets = predDatasetsRaw.map(function(ds) {
            return {
                label: ds.label,
                data: ds.data,
                borderColor: isPredFiltered ? '#36b9cc' : '#4e73df',
                backgroundColor: "transparent",
                borderDash: isPredFiltered ? [] : [5, 5],
                tension: 0.3,
                pointRadius: 4
            };
        });

        new Chart(predCanvas.getContext('2d'), {
            type: 'line',
            data: {
                labels: predLabels,
                datasets: configuredPredDatasets
            },
            options: {
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'bottom' }
                },
                scales: {
                    y: { beginAtZero: true, ticks: { precision: 0 } }
                }
            }
        });
    }
</script>
@endpush
@endsection