<?php
include 'koneksi.php';

// 1. Tangkap id_foto dari parameter GET (jika ada)
$id_foto = isset($_GET['id_foto']) ? intval($_GET['id_foto']) : 0;

// Jika tidak ada id_foto yang dikirim, cari id_foto terbaru
if ($id_foto == 0) {
    $q_last = $koneksi->query("SELECT id_foto FROM foto_telur_galeri ORDER BY id_foto DESC LIMIT 1");
    if ($q_last && $q_last->num_rows > 0) {
        $row_last = $q_last->fetch_assoc();
        $id_foto = $row_last['id_foto'];
    }
}

// 2. Ambil data riwayat pemilahan telur HANYA untuk id_foto yang dipilih (Maksimal 30 Data)
$sql = "SELECT * FROM riwayat_telur WHERE id_foto = '$id_foto' ORDER BY id_telur DESC LIMIT 30";
$result = $koneksi->query($sql);

$riwayat = array();
$fertil = 0;
$infertil = 0;

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        if (strtolower($row['status']) == 'fertil') {
            $fertil++;
        } else {
            $infertil++;
        }

        $riwayat[] = array(
            'id_telur' => $row['id_telur'],
            'koordinat' => !empty($row['koordinat']) ? $row['koordinat'] : '-',
            'status' => $row['status'],
            'tanggal_format' => isset($row['tanggal_jam']) ? date('d M Y - H:i:s', strtotime($row['tanggal_jam'])) . ' WIB' : '-'
        );
    }
}

// =====================================================================
// 3. HITUNG TOTAL AKUMULASI DARI SELURUH DATA DATABASE (TAMBAHAN PENTING)
// =====================================================================
$q_tot_fertil = $koneksi->query("SELECT COUNT(*) as total FROM riwayat_telur WHERE LOWER(status) = 'fertil'");
$q_tot_infertil = $koneksi->query("SELECT COUNT(*) as total FROM riwayat_telur WHERE LOWER(status) = 'infertil'");

$total_fertil = ($q_tot_fertil && $row = $q_tot_fertil->fetch_assoc()) ? intval($row['total']) : 0;
$total_infertil = ($q_tot_infertil && $row = $q_tot_infertil->fetch_assoc()) ? intval($row['total']) : 0;

// Response JSON untuk ajax.js
header('Content-Type: application/json');
echo json_encode(array(
    'id_foto_aktif' => $id_foto,
    'fertil' => $fertil,
    'infertil' => $infertil,
    'total_fertil' => $total_fertil,     // Dipakai oleh ajax.js
    'total_infertil' => $total_infertil, // Dipakai oleh ajax.js
    'riwayat' => $riwayat
));
?>