// 1. Inisialisasi Chart Pie Foto Aktif
const ctxAktif = document.getElementById('eggChart').getContext('2d');
let eggChartAktif = new Chart(ctxAktif, {
    type: 'pie',
    data: {
        labels: ['Fertil', 'Infertil'],
        datasets: [{
            data: [0, 0],
            backgroundColor: ['#198754', '#dc3545'],
            borderWidth: 2,
            borderColor: '#ffffff'
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { 
                position: 'bottom',
                labels: { font: { size: 12, weight: 'bold' } }
            }
        }
    }
});

// 2. Inisialisasi Chart Pie Total Seluruh Telur
const ctxTotal = document.getElementById('eggChartTotal').getContext('2d');
let eggChartTotal = new Chart(ctxTotal, {
    type: 'pie',
    data: {
        labels: ['Total Fertil', 'Total Infertil'],
        datasets: [{
            data: [0, 0],
            backgroundColor: ['#198754', '#dc3545'],
            borderWidth: 2,
            borderColor: '#ffffff'
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { 
                position: 'bottom',
                labels: { font: { size: 12, weight: 'bold' } }
            }
        }
    }
});

let currentIdFoto = 0;

// 3. Fungsi Load Data Realtime (Foto Aktif & Total Akumulasi)
function muatDataRealtime(idFoto = 0) {
    fetch('ambil_data.php?id_foto=' + idFoto)
        .then(response => response.json())
        .then(data => {
            // --- A. Update Chart Foto Aktif ---
            let fertilVal = data.fertil || 0;
            let infertilVal = data.infertil || 0;
            let totalVal = fertilVal + infertilVal;
            
            let persenFertil = totalVal > 0 ? ((fertilVal / totalVal) * 100).toFixed(1) : 0;
            let persenInfertil = totalVal > 0 ? ((infertilVal / totalVal) * 100).toFixed(1) : 0;

            eggChartAktif.data.labels = [
                'Fertil (' + persenFertil + '%)', 
                'Infertil (' + persenInfertil + '%)'
            ];
            eggChartAktif.data.datasets[0].data = [fertilVal, infertilVal];
            eggChartAktif.update();

            // --- B. Update Chart Total Akumulasi Seluruh Data ---
            let totalFertilAll = data.total_fertil || 0;
            let totalInfertilAll = data.total_infertil || 0;
            let grandTotal = totalFertilAll + totalInfertilAll;

            let persenTotalFertil = grandTotal > 0 ? ((totalFertilAll / grandTotal) * 100).toFixed(1) : 0;
            let persenTotalInfertil = grandTotal > 0 ? ((totalInfertilAll / grandTotal) * 100).toFixed(1) : 0;

            eggChartTotal.data.labels = [
                'Total Fertil (' + persenTotalFertil + '%)', 
                'Total Infertil (' + persenTotalInfertil + '%)'
            ];
            eggChartTotal.data.datasets[0].data = [totalFertilAll, totalInfertilAll];
            eggChartTotal.update();

            // --- C. Update Counter Text di Bawah Chart ---
            const txtFertil = document.getElementById('txt-fertil');
            const txtInfertil = document.getElementById('txt-infertil');
            if (txtFertil) txtFertil.innerText = "Fertil: " + fertilVal;
            if (txtInfertil) txtInfertil.innerText = "Infertil: " + infertilVal;

            const txtTotalFertil = document.getElementById('txt-total-fertil');
            const txtTotalInfertil = document.getElementById('txt-total-infertil');
            if (txtTotalFertil) txtTotalFertil.innerText = "Total Fertil: " + totalFertilAll;
            if (txtTotalInfertil) txtTotalInfertil.innerText = "Total Infertil: " + totalInfertilAll;

            // --- D. Update Tabel Keputusan 30 Lubang ---
            const tabelBody = document.getElementById('tabel-riwayat');
            let barisHTML = "";

            if (data.riwayat && data.riwayat.length > 0) {
                data.riwayat.forEach((telur, index) => {
                    let badgeWarna = (telur.status === 'Fertil') ? 'bg-success' : 'bg-danger';
                    let koordinatTelur = telur.koordinat ? telur.koordinat : '-';

                    barisHTML += `
                        <tr>
                            <td class="fw-bold">${index + 1}</td>
                            <td>#${telur.id_telur}</td>
                            <td class="fw-bold text-dark">${koordinatTelur}</td>
                            <td><span class="badge ${badgeWarna} px-3 py-2 fs-7">${telur.status}</span></td>
                            <td class="small text-muted">${telur.tanggal_format}</td>
                        </tr>
                    `;
                });
            } else {
                barisHTML = "<tr><td colspan='5' class='text-center text-muted py-4 fw-bold'>Belum ada data pemilahan untuk foto ini.</td></tr>";
            }

            if (tabelBody) tabelBody.innerHTML = barisHTML;
        })
        .catch(error => console.error('Gagal memuat data AJAX:', error));
}

// 4. Jam Digital
function updateJamDigital() {
    const namaHari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"];
    const namaBulan = ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des"];
    
    const sekarang = new Date();
    const hari = namaHari[sekarang.getDay()];
    const tanggal = sekarang.getDate().toString().padStart(2, '0');
    const bulan = namaBulan[sekarang.getMonth()];
    const tahun = sekarang.getFullYear(); 
    
    const jam = sekarang.getHours().toString().padStart(2, '0');
    const menit = sekarang.getMinutes().toString().padStart(2, '0');
    const detik = sekarang.getSeconds().toString().padStart(2, '0');

    const formatWaktu = `${hari}, ${tanggal} ${bulan} ${tahun} - ${jam}:${menit}:${detik} WIB`;
    
    const elemenJam = document.getElementById('live-clock');
    if(elemenJam) elemenJam.innerText = formatWaktu;
}

// 5. Inisialisasi Event Listener
document.addEventListener("DOMContentLoaded", function() {
    const rgbEl = document.getElementById('carouselRGB');

    if (rgbEl) {
        const itemAktifAwal = rgbEl.querySelector('.carousel-item.active');
        if (itemAktifAwal && itemAktifAwal.dataset.idFoto) {
            currentIdFoto = itemAktifAwal.dataset.idFoto;
        }

        rgbEl.addEventListener('slid.bs.carousel', function (e) {
            const itemAktif = e.relatedTarget;
            currentIdFoto = itemAktif.dataset.idFoto || 0;
            muatDataRealtime(currentIdFoto);
        });
    }

    muatDataRealtime(currentIdFoto);
    setInterval(() => muatDataRealtime(currentIdFoto), 2000);

    updateJamDigital();
    setInterval(updateJamDigital, 1000);

    // Form Event Handler untuk Tombol Reset Foto Aktif
    const formReset = document.getElementById('form-reset');
    if (formReset) {
        formReset.addEventListener('submit', function(e) {
            e.preventDefault();

            if (!currentIdFoto || currentIdFoto == 0) {
                alert('Tidak ada data foto yang dipilih untuk dihapus.');
                return;
            }

            if (confirm('Apakah Anda yakin ingin menghapus foto dan 30 data riwayat yang sedang ditampilkan ini?')) {
                let formData = new FormData();
                formData.append('id_foto', currentIdFoto);

                fetch('hapus_riwayat.php', { method: 'POST', body: formData })
                .then(response => response.text())
                .then(res => {
                    if (res.trim() === 'success') {
                        alert('Data dan foto aktif berhasil dihapus!');
                        location.reload();
                    } else {
                        alert('Gagal menghapus data: ' + res);
                    }
                })
                .catch(err => alert('Terjadi kesalahan koneksi ke server.'));
            }
        });
    }
});