<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'kader') {
    header("Location: ../login.php");
    exit;
}

$id_posyandu = $_SESSION['posyandu'];
$search = isset($_GET['search']) ? $_GET['search'] : '';

$query = "SELECT *,
TIMESTAMPDIFF(MONTH, tgl_lahir, CURDATE()) AS usia_bulan
FROM balita
WHERE id_posyandu = ?
AND nama_balita LIKE ?
ORDER BY nama_balita ASC";
$stmt = $pdo->prepare($query);
$stmt->execute([$id_posyandu, "%$search%"]);
$balitas = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Balita - Posyandu</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<!-- QR GENERATOR -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

<!-- SCANNER -->
<script src="https://unpkg.com/html5-qrcode"></script>

<style>
body { background-color: #f8f9fa; font-family: 'Segoe UI', sans-serif; }
.bg-header { background: #0d6efd; color: white; padding: 20px; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; }
.btn-tambah { border-radius: 50px; padding: 12px; font-weight: bold; background-color: #198754; border: none; }
.card-balita { border: none; border-radius: 15px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 12px; position: relative; }
.card-lulus {
    background-color: #d3d3d3 !important;
}
.badge-lulus {
    position: absolute;
    top: 10px;
    right: 12px;
    background: #6c757d;
    color: white;
    font-size: 11px;
    padding: 4px 8px;
    border-radius: 12px;
    font-weight: 600;
}
.search-box { border-radius: 25px; padding: 12px 20px; border: none; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
.btn-periksa { border-radius: 20px; border: 1px solid #0d6efd; color: #0d6efd; font-size: 13px; padding: 5px 15px; text-decoration: none; font-weight: 500; }
.btn-qr { border-radius: 20px; border: 1px solid #198754; color: #198754; font-size: 13px; padding: 5px 12px; margin-right:6px; }
.dropdown-toggle::after { display: none; }
#reader{width:100%;}
</style>
</head>
<body>

<div class="bg-header mb-4 shadow-sm">
    <div class="container d-flex justify-content-between align-items-center">
        <a href="dashboard.php" class="text-white text-decoration-none"><i class="fa fa-arrow-left"></i> Kembali</a>
        <h5 class="mb-0 fw-bold">Data Balita</h5>
        <div></div>
    </div>
</div>

<div class="container pb-5">

<form action="" method="GET" class="mb-3">
    <div class="input-group">
        <input type="text" name="search" class="form-control search-box" placeholder="Ketik nama balita..." value="<?= htmlspecialchars($search) ?>">
        <button class="btn btn-primary rounded-end-pill px-4" type="submit"><i class="fa fa-search"></i></button>
    </div>
</form>

<!-- SCAN BUTTON -->
<div class="d-grid mb-3">
    <button class="btn btn-dark rounded-pill py-3 shadow-sm" onclick="openScanner()">
        <i class="fa fa-qrcode me-2"></i> Scan Buku KIA
    </button>
</div>

<div class="d-grid mb-4">
    <a href="balita_tambah.php" class="btn btn-success btn-tambah shadow-sm">
        <i class="fa fa-plus me-2"></i> Tambah Balita Baru
    </a>
</div>

<div class="row">
<?php foreach($balitas as $b): ?>
<div class="col-12">
<div class="card card-balita <?= ($b['usia_bulan'] > 60) ? 'card-lulus' : '' ?>">
<div class="card-body">

<?php if($b['usia_bulan'] > 60): ?>
    <div class="badge-lulus">LULUS</div>
    <div class="small text-secondary">
Umur: <?= $b['usia_bulan'] ?> bulan
</div>
<?php endif; ?>

<div class="d-flex justify-content-between align-items-start">
<div>
<h6 class="fw-bold mb-1 text-dark"><?= strtoupper(htmlspecialchars($b['nama_balita'])) ?></h6>
<small class="text-muted d-block mb-1">
<i class="fa fa-calendar-alt me-1 text-danger"></i> <?= date('d/m/Y', strtotime($b['tgl_lahir'])) ?> |
<i class="fa fa-venus-mars me-1 text-primary"></i> <?= $b['jenis_kelamin']=='L'?'Laki-laki':'Perempuan' ?>
</small>
<div class="small text-secondary">Ibu: <?= htmlspecialchars($b['nama_ibu']) ?></div>
</div>

<div class="dropdown">
<button class="btn btn-link text-secondary p-0 dropdown-toggle shadow-none" data-bs-toggle="dropdown">
<i class="fa fa-ellipsis-v"></i>
</button>
<ul class="dropdown-menu dropdown-menu-end border-0 shadow rounded-3">
<li><a class="dropdown-item py-2" href="balita_edit.php?id=<?= $b['id_balita'] ?>"><i class="fa fa-edit me-2 text-warning"></i>Edit Profil</a></li>
<li><hr class="dropdown-divider"></li>
<li>
<a class="dropdown-item py-2 text-danger"
   href="balita_hapus.php?id=<?= $b['id_balita'] ?>"
   onclick="return confirm('Yakin ingin menghapus data balita ini? Ini akan menghapus juga riwayat penimbangannya')">
   <i class="fa fa-trash me-2"></i>Hapus
</a>
</li>
</ul>
</div>
</div>

<div class="d-flex justify-content-end mt-2">
<button class="btn-qr" onclick="showQR('<?= $b['id_balita'] ?>','<?= strtoupper(htmlspecialchars($b['nama_balita'])) ?>')">
<i class="fa fa-qrcode"></i>
</button>

<a href="balita_detail.php?id=<?= $b['id_balita'] ?>" class="btn-periksa">
Periksa <i class="fa fa-chevron-right ms-1"></i>
</a>
</div>

</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>

<!-- MODAL QR -->
<div class="modal fade" id="qrModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content text-center">
<div class="modal-body">
<h5 id="qrNama" class="mb-3"></h5>
<div id="qrcode" style="display:flex;justify-content:center;"></div>
<button onclick="printQR()" class="btn btn-dark mt-3 rounded-pill px-4">
<i class="fa fa-print me-2"></i> Cetak
</button>
</div>
</div>
</div>
</div>

<!-- MODAL SCANNER -->
<div class="modal fade" id="scanModal">
<div class="modal-dialog modal-fullscreen">
<div class="modal-content bg-dark">
<div class="modal-header border-0">
<h5 class="modal-title text-white">Scan Buku KIA</h5>
<button type="button" class="btn-close btn-close-white" onclick="stopScanner()"></button>
</div>
<div class="modal-body">
<div id="reader"></div>
</div>
</div>
</div>
</div>

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

<script>
let qr,currentName='',html5Qr;

// QR GENERATOR
function showQR(id,nama){
currentName=nama;
document.getElementById('qrNama').innerText=nama;
document.getElementById('qrcode').innerHTML='';
qr=new QRCode(document.getElementById('qrcode'),{text:id,width:220,height:220,correctLevel:QRCode.CorrectLevel.H});
new bootstrap.Modal(document.getElementById('qrModal')).show();
}

function printQR(){
let isi=document.getElementById('qrcode').innerHTML;
let w=window.open('');
w.document.write(`<html><body onload="window.print();window.close()" style="text-align:center;font-family:Arial"><h3>${currentName}</h3>${isi}</body></html>`);
}

// SCANNER
function openScanner(){
let modal=new bootstrap.Modal(document.getElementById('scanModal'));
modal.show();
html5Qr=new Html5Qrcode("reader");
html5Qr.start({facingMode:"environment"},{fps:10,qrbox:250},msg=>{
window.location.href="balita_detail.php?id="+msg;
});
}

function stopScanner(){
if(html5Qr){html5Qr.stop().then(()=>html5Qr.clear());}
bootstrap.Modal.getInstance(document.getElementById('scanModal')).hide();
}
</script>

</body>
</html>
