<?php
session_start();
if(!isset($_SESSION['status']) || $_SESSION['status'] != "login"){
    header("location:index.php?pesan=belum_login");
    exit;
}

include 'koneksi.php';

// Ambil riwayat foto galeri dari database
$query_galeri = mysqli_query($koneksi, "SELECT * FROM foto_telur_galeri ORDER BY id_foto DESC");
$fotos = mysqli_fetch_all($query_galeri, MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Pemilah Telur Ayam Kampung</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
        .navbar { background-color: #1e3c72; }
        .card { border: none; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .marquee-text { color: #ffffff; font-weight: bold; font-size: 0.95rem; margin: 0; }
        
        .card-foto-utama {
            background: #ffffff;
            border-radius: 12px;
            padding: 12px;
            text-align: center;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            height: 100%;
        }
        .carousel-item img {
            width: 100%;
            height: 250px;
            object-fit: contain;
            border-radius: 8px;
            border: 1px solid #dee2e6;
            cursor: pointer;
            transition: 0.2s;
            background-color: #000;
        }
        .carousel-item img:hover {
            transform: scale(1.01);
        }
    </style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark sticky-top shadow-sm py-2">
    <div class="container-fluid px-4 d-flex justify-content-between align-items-center">
        <div class="marquee-container d-none d-md-block" style="flex: 1; max-width: 75%; margin-right: 20px;">
            <marquee direction="left" scrollamount="6" class="marquee-text">
                RANCANG BANGUN PEMILAH TELUR FERTIL DAN INFERTIL PADA TELUR AYAM KAMPUNG MENGGUNAKAN IMAGE PROCESSING
            </marquee>
        </div>
        
        <div class="d-flex align-items-center">
            <span class="text-white me-3 small" id="live-clock" style="font-weight: 500; white-space: nowrap; background: rgba(255,255,255,0.1); padding: 5px 12px; border-radius: 20px;">
                Memuat Waktu...
            </span>
            <a href="logout.php" class="btn btn-sm btn-danger px-3 rounded-pill fw-bold">Keluar</a>
        </div>
    </div>
</nav>

<div class="container-fluid px-4 mt-4">

<!-- BAGIAN ATAS: SLIDER SINKRON (RGB & GRAYSCALE) -->
<div class="row g-3 mb-4">
    <!-- CAROUSEL RGB -->
    <div class="col-md-6">
        <div class="card-foto-utama">
            <h6 class="fw-bold text-uppercase text-secondary mb-2">Citra RGB (Grid Tray)</h6>
            <div id="carouselRGB" class="carousel slide" data-bs-ride="false">
                <div class="carousel-inner">
                    <?php if (!empty($fotos)): ?>
                        <?php foreach ($fotos as $index => $foto): ?>
                            <div class="carousel-item <?= $index === 0 ? 'active' : '' ?>" data-id-foto="<?= $foto['id_foto'] ?>">
                                <img src="assets/img/<?= htmlspecialchars($foto['foto_telur']) ?>" 
                                     alt="Foto RGB" 
                                     onclick="bukaModal(this.src)"
                                     onerror="this.onerror=null; this.src='https://placehold.co/600x400/e9ecef/6c757d?text=Belum+Ada+Foto+RGB';">
                                <div class="carousel-caption d-none d-md-block bg-dark bg-opacity-50 py-1 rounded-bottom">
                                    <small class="text-white"><?= date('d M Y - H:i:s', strtotime($foto['created_at'])) ?> WIB</small>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="carousel-item active" data-id-foto="0">
                            <img src="https://placehold.co/600x400/e9ecef/6c757d?text=Belum+Ada+Foto+RGB" alt="No Data">
                        </div>
                    <?php endif; ?>
                </div>
                <button class="carousel-control-prev" type="button" data-bs-target="#carouselRGB" data-bs-slide="prev">
                    <span class="carousel-control-prev-icon"></span>
                </button>
                <button class="carousel-control-next" type="button" data-bs-target="#carouselRGB" data-bs-slide="next">
                    <span class="carousel-control-next-icon"></span>
                </button>
            </div>
        </div>
    </div>

    <!-- CAROUSEL GRAYSCALE -->
    <div class="col-md-6">
        <div class="card-foto-utama">
            <h6 class="fw-bold text-uppercase text-secondary mb-2">Citra Grayscale</h6>
            <div id="carouselGray" class="carousel slide" data-bs-ride="false">
                <div class="carousel-inner">
                    <?php if (!empty($fotos)): ?>
                        <?php foreach ($fotos as $index => $foto): ?>
                            <div class="carousel-item <?= $index === 0 ? 'active' : '' ?>" data-id-foto="<?= $foto['id_foto'] ?>">
                                <img src="assets/img/<?= htmlspecialchars($foto['foto_grayscale']) ?>" 
                                     alt="Foto Grayscale" 
                                     onclick="bukaModal(this.src)"
                                     onerror="this.onerror=null; this.src='https://placehold.co/600x400/e9ecef/6c757d?text=Belum+Ada+Foto+Grayscale';">
                                <div class="carousel-caption d-none d-md-block bg-dark bg-opacity-50 py-1 rounded-bottom">
                                    <small class="text-white"><?= date('d M Y - H:i:s', strtotime($foto['created_at'])) ?> WIB</small>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="carousel-item active" data-id-foto="0">
                            <img src="https://placehold.co/600x400/e9ecef/6c757d?text=Belum+Ada+Foto+Grayscale" alt="No Data">
                        </div>
                    <?php endif; ?>
                </div>
                <button class="carousel-control-prev" type="button" data-bs-target="#carouselGray" data-bs-slide="prev">
                    <span class="carousel-control-prev-icon"></span>
                </button>
                <button class="carousel-control-next" type="button" data-bs-target="#carouselGray" data-bs-slide="next">
                    <span class="carousel-control-next-icon"></span>
                </button>
            </div>
        </div>
    </div>
</div>

    <!-- ========================================================= -->
    <!-- BAGIAN BAWAH: DIAGRAM KUALITAS & TABEL KEPUTUSAN 30 LUBANG -->
    <!-- ========================================================= -->
    <form id="form-reset">
        <div class="row g-4">
            
            <!-- 1. DIAGRAM KUALITAS (FOTO INI) -->
            <div class="col-xl-3 col-lg-6 col-md-6">
                <div class="card p-3 text-center h-100">
                    <h6 class="fw-bold text-secondary mb-3 text-uppercase fs-7">Kualitas (Foto Ini)</h6>
                    <div style="max-width: 180px; margin: 0 auto;">
                        <canvas id="eggChart"></canvas>
                    </div>
                    <div class="mt-3 d-flex justify-content-center gap-1 flex-wrap">
                        <span class="badge bg-success px-2 py-1 fs-8" id="txt-fertil">Fertil: 0</span>
                        <span class="badge bg-danger px-2 py-1 fs-8" id="txt-infertil">Infertil: 0</span>
                    </div>
                </div>
            </div>

            <!-- 2. DIAGRAM AKUMULASI (TOTAL SELURUH DATA) -->
            <div class="col-xl-3 col-lg-6 col-md-6">
                <div class="card p-3 text-center h-100">
                    <h6 class="fw-bold text-secondary mb-3 text-uppercase fs-7">Total Akumulasi Kualitas</h6>
                    <div style="max-width: 180px; margin: 0 auto;">
                        <canvas id="eggChartTotal"></canvas>
                    </div>
                    <div class="mt-3 d-flex justify-content-center gap-1 flex-wrap">
                        <span class="badge bg-success px-2 py-1 fs-8" id="txt-total-fertil">Total Fertil: 0</span>
                        <span class="badge bg-danger px-2 py-1 fs-8" id="txt-total-infertil">Total Infertil: 0</span>
                    </div>
                </div>
            </div>

            <!-- 3. TABEL KEPUTUSAN REALTIME -->
            <div class="col-xl-6 col-lg-12">
                <div class="card p-4 h-100">
                    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
                        <h6 class="fw-bold text-secondary text-uppercase m-0">Tabel Riwayat Pemilahan (30 Lubang)</h6>
                        <button type="submit" class="btn btn-danger btn-sm px-3 rounded-pill fw-bold shadow-sm">
                            Reset Data Active
                        </button>
                    </div>
                    
                    <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                        <table class="table table-hover align-middle text-center">
                            <thead class="table-primary sticky-top" style="top: 0; z-index: 1;">
                                <tr>
                                    <th width="10%">No</th>
                                    <th width="20%">ID Telur</th>
                                    <th width="25%">Koordinat</th>
                                    <th width="20%">Status</th>
                                    <th width="25%">Waktu</th>
                                </tr>
                            </thead>
                            <tbody id="tabel-riwayat">
                                <!-- Data tabel dimuat secara Real-time oleh ajax.js -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </form>
</div>

<!-- MODAL PREVIEW GAMBAR -->
<div class="modal fade" id="previewModal" tabindex="-1" aria-labelledby="previewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content">
      <div class="modal-header py-2">
        <h6 class="modal-title fw-bold" id="previewModalLabel">Detail Preview Gambar</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body text-center p-2 bg-light">
        <img src="" id="img-modal-besar" class="img-fluid rounded" style="max-height: 500px; width: 100%; object-fit: contain;">
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!-- SCRIPT SINKRONISASI SLIDER OTOMATIS -->
<script>
    function bukaModal(src) {
        document.getElementById('img-modal-besar').src = src;
        var myModal = new bootstrap.Modal(document.getElementById('previewModal'));
        myModal.show();
    }

    document.addEventListener('DOMContentLoaded', function () {
        const rgbEl = document.getElementById('carouselRGB');
        const grayEl = document.getElementById('carouselGray');

        if (rgbEl && grayEl) {
            const carouselRGB = bootstrap.Carousel.getOrCreateInstance(rgbEl);
            const carouselGray = bootstrap.Carousel.getOrCreateInstance(grayEl);

            let isSyncing = false;

            rgbEl.addEventListener('slide.bs.carousel', function (e) {
                if (!isSyncing) {
                    isSyncing = true;
                    carouselGray.to(e.to);
                } else {
                    isSyncing = false;
                }
            });

            grayEl.addEventListener('slide.bs.carousel', function (e) {
                if (!isSyncing) {
                    isSyncing = true;
                    carouselRGB.to(e.to);
                } else {
                    isSyncing = false;
                }
            });
        }
    });
</script>

<script src="ajax.js"></script>
</body>
</html>