@extends('layouts.app')
@section('title', 'Dashboard - ISPA Prediction')

@section('content')
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesom
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"/>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-doughnutlabel"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster/dist/MarkerCluster.css" />
<script src="https://unpkg.com/leaflet.markercluster/dist/leaflet.markercluster.js"></script>

<style>
  .gradient-orange {
    background: linear-gradient(135deg, #ff9800, #ff5722);
}

.gradient-blue {
    background: linear-gradient(135deg, #2196f3, #3f51b5);
}

.gradient-green {
    background: linear-gradient(135deg, #4caf50, #009688);
}

.gradient-purple {
    background: linear-gradient(135deg, #9c27b0, #673ab7);
}

  .card-gradient {
    color: white;
    border-radius: 1rem;
    padding: 1rem 1.25rem;
    box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15);
    min-height: 220px; /* naikkan supaya semua card sama tinggi */
    display: flex;
    flex-direction: column;
    justify-content: space-between; /* supaya isi terbagi rata */
    position: relative;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;

    transition: transform 0.3s ease, box-shadow 0.3s ease;
    transform-style: preserve-3d;
    perspective: 1000px;
    transform: translateZ(0);
}


.card-gradient:hover {
    /* Angkat card ke depan dan tambahkan shadow lebih dalam */
    transform: translateY(-10px) translateZ(30px) scale(1.05);
    box-shadow:
        0 1rem 2rem rgba(0,0,0,0.3),
        0 0 15px rgba(255,255,255,0.2);
    cursor: pointer;
}

.card-gradient i {
    opacity: 0.85;
    /* Bisa juga beri efek 3D ikon */
    transform-style: preserve-3d;
    transition: transform 0.3s ease;
}

.card-gradient:hover i {
    transform: translateZ(20px) rotateY(10deg);
}

.card-gradient h5 {
    font-size: 1rem;
    margin-bottom: 0.5rem;
}

.card-gradient p,
.card-gradient h3 {
    font-size: 0.9rem;
    margin: 0;
}
/* Style progress bar container */
  .progress-bar-container {
    width: 100%;
    background-color: rgba(255, 255, 255, 0.25);
    border-radius: 1rem;
    height: 18px;
    margin-top: 0.5rem;
    overflow: hidden;
  }

  /* Progress bar fill yang diisi persentase */
  .progress-bar-fill {
    height: 100%;
    border-radius: 1rem;
    transition: width 0.6s ease;
  }

  /* Warna khusus untuk masing-masing card */
  .progress-orange {
    background: linear-gradient(90deg, #ffb74d, #ff9800);
  }

  .progress-blue {
    background: linear-gradient(90deg, #64b5f6, #2196f3);
  }

  .progress-green {
    background: linear-gradient(90deg, #81c784, #4caf50);
  }
  .card-jumlah-kasus {
    min-height: 180px; /* Sesuaikan dengan tinggi card Merokok */
    padding-bottom: 1.5rem; /* Atau sesuai kebutuhan */
}
   .card-map {
        height: 400px;
        width: 100%;
    }
</style>
@if(session('login_success'))
    <div class="alert alert-success alert-dismissible fade show position-fixed" style="top: 60px; right: 30px; z-index: 1050; min-width: 300px; max-width: 400px;" role="alert">
        <strong>🎉 {{ session('login_success') }}</strong>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>

    <script>
        setTimeout(function () {
            const alert = document.querySelector('.alert');
            if (alert) {
                alert.classList.remove('show');
                alert.classList.add('fade');
                setTimeout(() => alert.remove(), 500);
            }
        }, 3000);
    </script>
@endif

<style>
    .card-custom {
        margin-bottom: 1rem;
    }
    .card-map {
        height: 400px;
        width: 100%;
    }
</style>
<div class="container">
    <h2 class="mb-4">Dashboard Admin</h2>
    <div class="row">
        <div class="row mb-4 d-flex justify-content-center align-items-center">
   <div class="row mb-4 d-flex justify-content-center align-items-center">
   <!-- Dalam setiap card, tambahkan progress bar di bawah teks persen -->
<!-- PHBS -->
<div class="col-md-6 col-xl-3 mb-4">
    <div class="card-gradient gradient-orange h-100">
        <div class="mb-3">
            <i class="fas fa-hand-holding-heart fa-2x"></i>
        </div>
        <h5 class="card-title">Perilaku Hidup Bersih dan Sehat</h5>
        <p>Baik: {{ $stats->persen_phbs_baik }}% | Tidak Baik: {{ $stats->persen_phbs_tidak_baik }}%</p>
        <div class="progress-bar-container d-flex" style="height: 18px; border-radius: 1rem; overflow: hidden;">
            <div style="width: {{ $stats->persen_phbs_baik }}%; background: linear-gradient(90deg, #ffb74d, #ff9800);"></div>
            <div style="width: {{ $stats->persen_phbs_tidak_baik }}%; background: linear-gradient(90deg, #d84315, #bf360c);"></div>
        </div>
    </div>
</div>
<!-- Imunisasi -->
<div class="col-md-6 col-xl-3 mb-4">
    <div class="card-gradient gradient-blue h-100">
        <div class="mb-3">
            <i class="fas fa-syringe fa-2x"></i>
        </div>
        <h5 class="card-title">Imunisasi PCV (Pneumococcal Conjugate Vaccine)</h5>
        <p>Imunisasi: {{ $stats->persen_imunisasi }}% | Tidak Imunisasi: {{ $stats->persen_tidak_imunisasi }}%</p>
        <div class="progress-bar-container d-flex" style="height: 18px; border-radius: 1rem; overflow: hidden;">
            <div style="width: {{ $stats->persen_imunisasi }}%; background: linear-gradient(90deg, #64b5f6, #2196f3);"></div>
            <div style="width: {{ $stats->persen_tidak_imunisasi }}%; background: linear-gradient(90deg, #1565c0, #0d47a1);"></div>
        </div>
    </div>
</div>

<!-- Merokok -->
<div class="col-md-6 col-xl-3 mb-4">
    <div class="card-gradient gradient-green h-100">
        <div class="mb-3">
            <i class="fas fa-smoking fa-2x"></i>
        </div>
        <h5 class="card-title">Perilaku Merokok</h5>
        <p>Merokok: {{ $stats->persen_merokok }}% | Tidak Merokok: {{ $stats->persen_tidak_merokok }}%</p>
        <div class="progress-bar-container d-flex" style="height: 18px; border-radius: 1rem; overflow: hidden;">
            <div style="width: {{ $stats->persen_merokok }}%; background: linear-gradient(90deg, #81c784, #4caf50);"></div>
            <div style="width: {{ $stats->persen_tidak_merokok }}%; background: linear-gradient(90deg, #2e7d32, #1b5e20);"></div>
        </div>
    </div>
</div>
<!-- Jumlah Kasus -->
<div class="col-md-6 col-xl-3 mb-4 position-relative">
    <div class="card-gradient gradient-purple h-100 d-flex flex-column justify-content-center p-3 position-relative">

        {{-- Dropdown Tahun di Pojok Kanan Atas --}}
        @if($tahunTersedia->count() > 1)
        <div style="position: absolute; top: 0.75rem; right: 0.75rem;">
            <form method="GET" action="{{ route('admin.dashboard') }}">
                <select name="tahun" id="tahun" class="form-select form-select-sm w-auto" style="font-size: 0.75rem;" onchange="this.form.submit()">
                    @foreach($tahunTersedia as $tahun)
                        <option value="{{ $tahun }}" {{ $tahun == $selectedYear ? 'selected' : '' }}>
                            {{ $tahun }}
                        </option>
                    @endforeach
                </select>
            </form>
        </div>
        @endif

        <div class="mb-3">
            <i class="fas fa-notes-medical fa-2x"></i>
        </div>

        <h5 class="card-title">Jumlah Kasus</h5>
        <h3>{{ $jumlahKasusDataLatih }}</h3>
        <p>Total kasus Infeksi Saluran Pernapasan Akut pada balita di tahun {{ $selectedYear }}</p>

    </div>
</div>

    <div class="row">
        <div class="col-md-6 col-lg-4 mb-4">
            <div class="card shadow-sm border-0 card-custom">
                <div class="card-body">
                    <h5 class="card-title">Top 5 Kasus di Situbondo</h5>
                    <canvas id="kasusChart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-6 col-lg-8 mb-4">
    <div class="card shadow-sm border-0 card-custom">
        <div class="card-body">
            <h5 class="card-title d-flex justify-content-between align-items-center">
                Jumlah Kasus per Bulan

                <!-- Form Filter Tahun -->
                <form method="GET" action="{{ route('dashboard') }}">
                    <select name="year" id="filterYear" class="form-select form-select-sm w-auto" style="font-size:0.9rem;" onchange="this.form.submit()">
                        @foreach($availableYears as $year)
                            <option value="{{ $year }}" {{ $year == $selectedYear ? 'selected' : '' }}>{{ $year }}</option>
                        @endforeach
                    </select>
                </form>
            </h5>
            <canvas id="kasusLineChart" height="150"></canvas>
        </div>
    </div>
</div>

    <!-- Peta Situbondo -->
<div class="row">
    <div class="col-12">
        <div class="card shadow-sm border-0 card-custom">
            <div class="card-body">
                <h5 class="card-title">Peta Persebaran ISPA Situbondo</h5>
                <div id="situbondo-map" class="card-map"></div>
            </div>
        </div>
    </div>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    // Pie/Donut Chart - Top 5 Kasus
    const ctxPie = document.getElementById('kasusChart').getContext('2d');
    const kasusChart = new Chart(ctxPie, {
        type: 'doughnut',
        data: {
            labels: @json($topKasus->pluck('nama')),
            datasets: [{
                label: 'Jumlah Kasus',
                data: @json($topKasus->pluck('kasus_2023')),
                backgroundColor: [
                    'rgba(255, 99, 132, 0.8)',   // Merah
                    'rgba(54, 162, 235, 0.8)',   // Biru
                    'rgba(255, 206, 86, 0.8)',   // Kuning
                    'rgba(75, 192, 192, 0.8)',   // Hijau toska
                    'rgba(153, 102, 255, 0.8)'   // Ungu
                ],
                hoverOffset: 4
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { position: 'top' },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return context.label + ': ' + context.raw + ' Kasus';
                        }
                    }
                }
            },
            cutout: '50%'
        }
    });

    // Line Chart - Kasus per Bulan
    const ctxLine = document.getElementById('kasusLineChart').getContext('2d');
    const lineChart = new Chart(ctxLine, {
        type: 'line',
        data: {
            labels: @json($bulanLabels),
            datasets: [{
                label: 'Jumlah Kasus',
                data: @json($totalKasus),
                borderColor: 'rgba(255,99,132,1)',
                backgroundColor: 'rgba(255,99,132,0.2)',
                fill: false,
                tension: 0.3,
                pointBackgroundColor: 'rgba(255,99,132,1)',
                pointBorderColor: '#fff',
                pointHoverBackgroundColor: '#fff',
                pointHoverBorderColor: 'rgba(255,99,132,1)',
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { display: true, position: 'top' },
                title: { display: true, text: 'Jumlah Kasus per Bulan' }
            }
        }
    });
</script>
<!-- Load CSS & JS Leaflet + Cluster -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster/dist/MarkerCluster.css" />
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet.markercluster/dist/leaflet.markercluster.js"></script>
<script>
    var map = L.map('situbondo-map').setView([-7.716, 114.016], 10);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);

    var dataLatih = @json($data_latih);

    var iconRawan = L.icon({
        iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png',
        iconSize: [25, 41],
        iconAnchor: [12, 41],
        popupAnchor: [1, -34],
        shadowUrl: 'https://unpkg.com/leaflet@1.9.3/dist/images/marker-shadow.png',
        shadowSize: [41, 41]
    });

    var iconWaspada = L.icon({
        iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png',
        iconSize: [25, 41],
        iconAnchor: [12, 41],
        popupAnchor: [1, -34],
        shadowUrl: 'https://unpkg.com/leaflet@1.9.3/dist/images/marker-shadow.png',
        shadowSize: [41, 41]
    });

    var markers = L.layerGroup().addTo(map);

    dataLatih.forEach(function(item, index) {
        var lat = parseFloat(item.latitude);
        var lng = parseFloat(item.longitude);

        if (isNaN(lat) || isNaN(lng)) {
            console.warn(`Koordinat tidak valid pada index ${index}:`, item);
            return;
        }

        console.log(`Menambahkan marker index ${index}:`, {
            lat: lat,
            lng: lng,
            status: item.hipotesis,
            kecamatan: item.kecamatan
        });

        var status = (item.hipotesis || '').toLowerCase();
        var chosenIcon = (status === 'naik') ? iconRawan : iconWaspada;

        var marker = L.marker([lat, lng], { icon: chosenIcon });

        var popupContent = `
            <strong>Nama Lokasi:</strong> ${item.kecamatan || '-'}<br>
            <strong>Status:</strong> ${item.hipotesis || '-'}<br>
            <strong>Persentase PHBS Baik:</strong> ${Number(item.phbs || 0).toFixed(2)}%<br>
            <strong>Persentase Imunisasi:</strong> ${Number(item.imunisasi || 0).toFixed(2)}%<br>
            <strong>Persentase Merokok:</strong> ${Number(item.merokok || 0).toFixed(2)}%<br>
            <strong>Jumlah Kasus ISPA:</strong> ${item.kasus_2023 ?? 0}
        `;

        marker.bindPopup(popupContent);
        markers.addLayer(marker);
    });
</script>
<script>
    // Data dari controller Laravel
    const dataKasusByYear = @json($kasusPerBulanByYear);
    const bulanLabels = [
        "Januari", "Februari", "Maret", "April", "Mei", "Juni",
        "Juli", "Agustus", "September", "Oktober", "November", "Desember"
    ];

    // Ambil tahun terpilih dari Laravel
    let selectedYear = "{{ $selectedYear }}";

    // Ambil data sesuai tahun
    function getKasusPerBulan(year) {
        const dataTahun = dataKasusByYear[year] || [];
        const jumlahKasusPerBulan = bulanLabels.map(bulan => {
            const item = dataTahun.find(d => d.bulan === bulan);
            return item ? item.jumlah_kasus : 0;
        });
        return jumlahKasusPerBulan;
    }

    // Inisialisasi chart
    const ctx = document.getElementById('kasusLineChart').getContext('2d');
    let lineChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: bulanLabels,
            datasets: [{
                label: 'Jumlah Kasus',
                data: getKasusPerBulan(selectedYear),
                borderColor: 'rgba(255, 99, 132, 0.8)',
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: 'Jumlah Kasus per Bulan',
                    font: {
                        size: 16
                    }
                },
                legend: {
                    display: true,
                    position: 'top'
                }
            }
        }
    });

    // Event saat dropdown tahun diganti
    document.getElementById('filterYear').addEventListener('change', function () {
        selectedYear = this.value;
        const newData = getKasusPerBulan(selectedYear);

        lineChart.data.datasets[0].data = newData;
        lineChart.options.plugins.title.text = `Jumlah Kasus per Bulan - Tahun ${selectedYear}`;
        lineChart.update();
    });
</script>

@endsection