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

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

$nik_ibu = $_SESSION['nik_ibu_kunci'] ?? '';

try {
    $stmt_anak = $pdo->prepare("SELECT id_balita, nama_balita, tgl_lahir, nama_ibu FROM balita WHERE nik_ibu_kunci = ?");
    $stmt_anak->execute([$nik_ibu]);
    $daftar_anak = $stmt_anak->fetchAll();

    if (!$daftar_anak) {
        die("Data anak tidak ditemukan.");
    }

    $id_terpilih = $_GET['id'] ?? $daftar_anak[0]['id_balita'];

// Validasi: pastikan ID ada dalam daftar anak milik ibu
    $ids_milik_ibu = array_column($daftar_anak, 'id_balita');

    if (!in_array($id_terpilih, $ids_milik_ibu)) {
    die("Akses ditolak.");
    }
    
    $stmt_detail = $pdo->prepare("SELECT b.*, p.nama_posyandu FROM balita b LEFT JOIN posyandu p ON b.id_posyandu = p.id_posyandu WHERE b.id_balita = ?");
    $stmt_detail->execute([$id_terpilih]);
    $balita = $stmt_detail->fetch();

    $stmt_r = $pdo->prepare("SELECT * FROM pemeriksaan_balita WHERE id_balita = ? ORDER BY tgl_periksa ASC");
    $stmt_r->execute([$id_terpilih]);
    $riwayat = $stmt_r->fetchAll();
    
    $riwayat_tabel = !empty($riwayat) ? array_reverse($riwayat) : [];


} catch (PDOException $e) {
    die("Kesalahan Database: " . $e->getMessage());
}

$labels = []; $data_bb = []; $data_tb = [];
foreach($riwayat as $r) {
    $labels[] = date('d/m', strtotime($r['tgl_periksa']));
    $data_bb[] = (float)$r['bb'];
    $data_tb[] = (float)$r['tb'];
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Dashboard Ibu - Desa Gemuruh</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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { background-color: #f8f9fa; font-family: 'Segoe UI', sans-serif; }
        
        .header-pink { 
            background: linear-gradient(180deg, #ff6db3 0%, #ff4b91 100%); 
            color: white; padding: 20px 15px 45px; 
            border-radius: 0 0 30px 30px; 
        }
        .badge-posyandu { 
            background: rgba(255, 255, 255, 0.2); 
            border: 1px solid rgba(255, 255, 255, 0.5); 
            border-radius: 20px; padding: 2px 12px; 
            font-size: 0.75rem; display: inline-block; margin-bottom: 8px;
        }
        .nama-anak { font-size: 1.4rem; font-weight: 700; margin-bottom: 2px; line-height: 1.2; }
        .nama-ibu-sub { font-size: 0.8rem; opacity: 0.9; }

        .card-stats { 
            border: none; border-radius: 15px; margin-top: -25px; 
            box-shadow: 0 8px 20px rgba(0,0,0,0.06); background: white; 
            max-width: 90%; margin-left: auto; margin-right: auto;
        }
        .stat-val { font-size: 1.1rem; font-weight: 700; color: #333; }
        .stat-unit { font-size: 0.75rem; font-weight: 400; color: #777; }
        .stat-label { font-size: 0.7rem; color: #999; text-transform: uppercase; letter-spacing: 0.5px; }

        .section-title { 
            font-size: 0.85rem; font-weight: 700; color: #555; 
            margin: 20px 0 10px 10px; display: flex; align-items: center; 
        }
        .chart-card { 
            border: none; border-radius: 15px; background: white; 
            padding: 12px; margin-bottom: 15px; box-shadow: 0 2px 10px rgba(0,0,0,0.02);
        }
        .table-responsive {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        }
        .table-responsive { border-radius: 15px; background: white; box-shadow: 0 2px 10px rgba(0,0,0,0.02); }
        .table-custom { font-size: 0.72rem; white-space: nowrap; }
        .table-custom th { 
            background: #fff5f8; color: #ff4b91; text-align: center; 
            padding: 10px 8px; border-bottom: 1px solid #ffeef4; 
        }
        .table-custom td { padding: 8px; text-align: center; border-bottom: 1px solid #f8f9fa; vertical-align: middle; }
        
        .badge-status { 
            background: #f8f9fa; border: 1px solid #eee; 
            padding: 2px 6px; border-radius: 4px; color: #555; font-size: 0.65rem;
        }
        .select-anak { 
            background: white; border: none; color: #ff4b91; 
            border-radius: 10px; font-weight: bold; padding: 4px 15px; 
            box-shadow: 0 2px 8px rgba(0,0,0,0.1); font-size: 0.9rem;
        }
        .footer-text { font-size: 0.65rem; color: #bbb; letter-spacing: 1px; margin-top: 15px; text-transform: uppercase; }
    </style>
</head>
<body>

<div class="header-pink text-center">
    <div class="badge-posyandu">
        <i class="fa fa-home-alt me-1"></i> <?= htmlspecialchars($balita['nama_posyandu'] ?? 'Posyandu Desa Gemuruh') ?>
    </div>
    
    <?php if (count($daftar_anak) > 1): ?>
        <form method="GET" class="mb-2">
            <select name="id" onchange="this.form.submit()" class="select-anak">
                <?php foreach ($daftar_anak as $anak): ?>
                    <option value="<?= $anak['id_balita'] ?>" <?= $id_terpilih == $anak['id_balita'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($anak['nama_balita']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </form>
    <?php else: ?>
        <div class="nama-anak"><?= htmlspecialchars($balita['nama_balita']) ?></div>
    <?php endif; ?>
    
    <div class="nama-ibu-sub">Anak dari Ibu <b><?= htmlspecialchars($balita['nama_ibu']) ?></b></div>
</div>

<div class="container mb-5">
    <div class="card card-stats mb-3">
        <div class="card-body py-2">
            <div class="row text-center align-items-center">
                <div class="col-6 border-end">
                    <div class="stat-label">Berat Terakhir</div>
                    <div class="stat-val text-primary"><?= !empty($data_bb) ? end($data_bb) : '-' ?> <span class="stat-unit">kg</span></div>
                </div>
                <div class="col-6">
                    <div class="stat-label">Tinggi Terakhir</div>
                    <div class="stat-val text-success"><?= !empty($data_tb) ? end($data_tb) : '-' ?> <span class="stat-unit">cm</span></div>
                </div>
            </div>
        </div>
    </div>

    <div class="section-title"><i class="fa fa-chart-line text-danger me-2"></i> Grafik Berat Badan</div>
    <div class="chart-card">
        <canvas id="chartBB" style="height: 160px;"></canvas>
    </div>

    <div class="section-title"><i class="fa fa-chart-area text-success me-2"></i> Grafik Tinggi Badan</div>
    <div class="chart-card">
        <canvas id="chartTB" style="height: 160px;"></canvas>
    </div>

    <div class="section-title"><i class="fa fa-clipboard-list text-primary me-2"></i> Riwayat Pemeriksaan Lengkap</div>
    <div class="table-responsive">
        <table class="table table-custom mb-0">
            <thead>
<tr>
    <th>TGL</th>
    <th>USIA</th>
    <th>BB</th>
    <th>TB</th>
    <th>LILA</th>
    <th>LIKA</th>
    <th>VIT A</th>
    <th>IMUN</th>
    <th>CACING</th>
    <th>BB/U</th>
    <th>TB/U</th>
    <th>BB/TB</th>
    <th>IMT/U</th>
    <th>ASI</th>
    <th>KET</th>
</tr>
</thead>
            <tbody>
<?php if (!$riwayat_tabel): ?>
    <tr>
        <td colspan="15" class="py-4 text-muted small">
            Belum ada data pemeriksaan.
        </td>
    </tr>
<?php else: ?>
<?php foreach ($riwayat_tabel as $row): 
    $tgl_l = new DateTime($balita['tgl_lahir']);
    $tgl_p = new DateTime($row['tgl_periksa']);
    $usia_bln = ($tgl_l->diff($tgl_p)->y * 12) + $tgl_l->diff($tgl_p)->m;
?>
<tr>
    <td class="fw-bold"><?= date('d/m/y', strtotime($row['tgl_periksa'])) ?></td>
    <td><?= $usia_bln ?> bln</td>
    <td class="fw-bold text-primary"><?= $row['bb'] ?></td>
    <td class="fw-bold text-success"><?= $row['tb'] ?></td>
    <td><?= $row['lila'] ?: '-' ?></td>
    <td><?= $row['lika'] ?: '-' ?></td>
    <td><?= $row['vit_a'] ?: '-' ?></td>
    <td><small><?= $row['imunisasi'] ?: '-' ?></small></td>
    <td><?= $row['obat_cacing'] ?: '-' ?></td>

    <!-- BB/U -->
    <td>
    <?php 
    $s_bbu = $row['z_score_bbu'];
    if ($s_bbu == 'Normal') $bg_bbu = 'success';
    elseif ($s_bbu == 'BB Sangat Kurang') $bg_bbu = 'danger';
    else $bg_bbu = 'warning';
    echo "<span class='badge bg-$bg_bbu'>$s_bbu</span>";
    ?>
    </td>

    <!-- TB/U -->
    <td>
    <?php 
    $s_tbu = $row['status_stunting'];
    if ($s_tbu == 'Normal') $bg_tbu = 'success';
    elseif ($s_tbu == 'Sangat Pendek') $bg_tbu = 'danger';
    else $bg_tbu = 'warning';
    echo "<span class='badge bg-$bg_tbu'>$s_tbu</span>";
    ?>
    </td>

    <!-- BB/TB -->
    <td>
    <?php 
    $s_bbtb = $row['status_bbtb'];
    if ($s_bbtb == 'Gizi Baik') $bg_bbtb = 'success';
    elseif ($s_bbtb == 'Gizi Buruk' || $s_bbtb == 'Obesitas') $bg_bbtb = 'danger';
    else $bg_bbtb = 'warning';
    echo "<span class='badge bg-$bg_bbtb'>$s_bbtb</span>";
    ?>
    </td>

    <!-- IMT/U -->
    <td>
    <?php 
    $s_imtu = $row['status_imtu'];
    if ($s_imtu == 'Gizi Baik') $bg_imtu = 'success';
    elseif ($s_imtu == 'Gizi Buruk' || $s_imtu == 'Obesitas') $bg_imtu = 'danger';
    else $bg_imtu = 'warning';
    echo "<span class='badge bg-$bg_imtu'>$s_imtu</span>";
    ?>
    </td>

    <td><?= $row['asi_eksklusif'] ?: '-' ?></td>
    <td class="text-start"><small class="text-muted"><?= $row['keterangan'] ?: '-' ?></small></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
        </table>
    </div>

    <div class="text-center mt-4 pb-4">
        <a href="../logout.php" class="btn btn-sm btn-light rounded-pill px-4 text-muted border shadow-sm" style="font-size: 0.7rem;">
            LOGOUT
        </a>
        <div class="footer-text">Digitalisasi Posyandu v.1.0 Desa Gemuruh</div>
    </div>
</div>

<script>
const commonOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: { legend: { display: false } },
    scales: { 
        y: { ticks: { font: { size: 9 } }, grid: { color: '#f5f5f5' } },
        x: { ticks: { font: { size: 9 } }, grid: { display: false } }
    }
};

new Chart(document.getElementById('chartBB'), {
    type: 'line',
    data: {
        labels: <?= json_encode($labels) ?>,
        datasets: [{
            data: <?= json_encode($data_bb) ?>,
            borderColor: '#ff4b91',
            backgroundColor: 'rgba(255, 75, 145, 0.1)',
            fill: true, tension: 0.4, pointRadius: 3
        }]
    },
    options: commonOptions
});

new Chart(document.getElementById('chartTB'), {
    type: 'line',
    data: {
        labels: <?= json_encode($labels) ?>,
        datasets: [{
            data: <?= json_encode($data_tb) ?>,
            borderColor: '#28a745',
            backgroundColor: 'rgba(40, 167, 69, 0.1)',
            fill: true, tension: 0.4, pointRadius: 3
        }]
    },
    options: commonOptions
});
</script>
</body>
</html>