<?php
require_once 'config.php';
$page_title = 'SPAM Desa Gemuruh - Beranda';

// Ambil Statistik
$total_pelanggan = 0;
$saldo_kas = 0;
$total_lunas = 0;
$total_belum = 0;

try {
    // Total pelanggan aktif
    $total_pelanggan = $pdo->query("SELECT COUNT(*) FROM pelanggan WHERE status='aktif'")->fetchColumn();
    
    // Saldo Kas (total pemasukan - total pengeluaran)
    $masuk = $pdo->query("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='masuk'")->fetchColumn();
    $keluar = $pdo->query("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='keluar'")->fetchColumn();
    $saldo_kas = $masuk - $keluar;
    
    // Jumlah pelanggan Lunas bulan ini
    $bulan_ini = (int)date('m');
    $tahun_ini = (int)date('Y');
    
    $stmt_lunas = $pdo->prepare("SELECT COUNT(*) FROM tagihan WHERE status='lunas' AND bulan=? AND tahun=?");
    $stmt_lunas->execute([$bulan_ini, $tahun_ini]);
    $total_lunas = (int)$stmt_lunas->fetchColumn();
    
    $stmt_belum = $pdo->prepare("SELECT COUNT(*) FROM tagihan WHERE status='belum_lunas' AND bulan=? AND tahun=?");
    $stmt_belum->execute([$bulan_ini, $tahun_ini]);
    $total_belum = (int)$stmt_belum->fetchColumn();
} catch (Exception $e) {}

// Ambil Data Grafik Pemakaian Air per Bulan (12 bulan terakhir)
$chart_labels = [];
$chart_values = [];
$chart_colors = [];
try {
    $stmt = $pdo->prepare("
        SELECT
            bulan,
            tahun,
            SUM(pemakaian) as total_pemakaian
        FROM meteran
        WHERE tahun >= YEAR(CURDATE()) - 1
        GROUP BY bulan, tahun
        ORDER BY tahun ASC, bulan ASC
    ");
    $stmt->execute();
    $data_grafik = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $nama_bulan = ['','Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
    foreach ($data_grafik as $row) {
        $chart_labels[] = $nama_bulan[$row['bulan']] . ' ' . substr($row['tahun'], -2);
        $chart_values[] = (float)$row['total_pemakaian'];
        $chart_colors[] = 'rgba(92, 141, 137, 0.7)';
    }
} catch (Exception $e) {
    $chart_labels = [];
    $chart_values = [];
}

// Ambil Berita
$berita = [];
try {
    $stmt = $pdo->query("SELECT * FROM berita ORDER BY tgl_posting DESC LIMIT 3");
    $berita = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}
?>
<!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><?= $page_title ?></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>
:root {
--primary-sage: #5C8D89;
--dark-sage: #3A6B69;
--light-sage: #A4C3B2;
--bg-color: #F4F7F6;
}
body { background: var(--bg-color); font-family: 'Segoe UI', sans-serif; color: #2f3440; margin:0; padding:0; }
.hero-section {
background: linear-gradient(135deg, var(--primary-sage) 0%, var(--dark-sage) 100%);
color: white;
padding: 40px 20px 60px;
border-bottom-left-radius: 40px;
border-bottom-right-radius: 40px;
margin-bottom: -30px;
}
.hero-title { font-size: 1.8rem; font-weight: 800; margin-bottom: 5px; }
.hero-subtitle { font-size: 1rem; opacity: 0.9; margin-bottom: 25px; }
.btn-hero {
background: white; color: var(--primary-sage); border: none;
border-radius: 30px; padding: 12px 24px; font-weight: 700;
text-decoration: none; display: inline-flex; align-items: center; gap: 8px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
.btn-hero-outline {
background: rgba(255,255,255,0.2); color: white;
border: 1px solid rgba(255,255,255,0.3); border-radius: 30px;
padding: 12px 24px; font-weight: 700; text-decoration: none;
display: inline-flex; align-items: center; gap: 8px; backdrop-filter: blur(5px);
}
.main-content { padding: 0 15px; position: relative; z-index: 10; }
.card-soft {
background: white; border: none; border-radius: 20px;
box-shadow: 0 6px 20px rgba(0,0,0,0.04); padding: 20px; margin-bottom: 20px;
}
.stat-card {
background: #F8FAF9; border-radius: 16px; padding: 15px; text-align: center;
}
.stat-value { font-size: 1.2rem; font-weight: 800; color: var(--primary-sage); }
.stat-label { font-size: 0.75rem; color: #7a8190; margin-top: 5px; }
.section-title { font-size: 1.1rem; font-weight: 800; color: #354052; margin-bottom: 15px; }
.news-item {
background: #F8FAF9; border-radius: 16px; padding: 15px; margin-bottom: 12px;
}
.news-title { font-weight: 700; font-size: 1rem; margin-bottom: 5px; }
.news-meta { font-size: 0.75rem; color: #7a8190; margin-bottom: 8px; }
.news-excerpt { font-size: 0.85rem; color: #5a6270; }
.menu-link {
display: flex; align-items: center; padding: 15px;
background: #F8FAF9; border-radius: 16px; text-decoration: none; color: inherit; margin-bottom: 10px;
}
.menu-icon {
width: 45px; height: 45px; border-radius: 12px;
background: #E6F0EF; color: var(--primary-sage);
display: flex; align-items: center; justify-content: center; font-size: 1.2rem; margin-right: 15px;
}
.chart-container {
position: relative;
height: 280px;
margin-top: 15px;
}
/* ===== Carousel Berita Horizontal ===== */
.berita-carousel {
    display: flex;
    overflow-x: auto;
    scroll-snap-type: x mandatory;
    -webkit-overflow-scrolling: touch;
    gap: 12px;
    padding-bottom: 8px;
    scrollbar-width: none; /* Firefox */
}
.berita-carousel::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Edge */
}
.berita-slide {
    flex: 0 0 100%;
    scroll-snap-align: start;
    scroll-snap-stop: always;
    min-width: 0;
}
.carousel-dots {
    display: flex;
    justify-content: center;
    gap: 6px;
    margin-top: 12px;
}
.carousel-dots .dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #d0d7de;
    transition: all 0.3s ease;
}
.carousel-dots .dot.active {
    background: var(--primary-sage);
    width: 22px;
    border-radius: 10px;
}
.stat-lunas .stat-value { color: #198754; }
.stat-belum .stat-value { color: #dc3545; }
footer { text-align: center; padding: 20px; font-size: 0.75rem; color: #8d94a2; }
</style>
</head>
<body>
<section class="hero-section">
<div class="container">
<div class="hero-title">SPAM<br>Tirtha Kedawung<br>Desa Gemuruh</div>
<div class="hero-subtitle">Sistem Penyediaan Air Minum berbasis masyarakat.</div>
<div class="d-flex gap-2 flex-wrap">
<a href="login.php" class="btn-hero"><i class="fa-solid fa-right-to-bracket"></i> Login Aplikasi</a>
<a href="cek_tagihan.php" class="btn-hero-outline"><i class="fa-solid fa-magnifying-glass"></i> Cek Tagihan</a>
</div>
</div>
</section>
<div class="main-content">
<!-- Statistik -->
<div class="card-soft">
<div class="section-title">Statistik Singkat</div>
<div class="row g-3">
<div class="col-6">
    <div class="stat-card">
        <div class="stat-value"><?= $total_pelanggan ?></div>
        <div class="stat-label">Pengguna Aktif</div>
    </div>
</div>
<div class="col-6">
    <div class="stat-card stat-lunas">
        <div class="stat-value"><?= $total_lunas ?></div>
        <div class="stat-label">Lunas</div>
    </div>
</div>
<div class="col-6">
    <div class="stat-card stat-belum">
        <div class="stat-value"><?= $total_belum ?></div>
        <div class="stat-label">Belum Bayar</div>
    </div>
</div>
<div class="col-6">
    <div class="stat-card">
        <div class="stat-value"><?= format_rupiah($saldo_kas) ?></div>
        <div class="stat-label">Kas Tersedia</div>
    </div>
</div>
</div>
</div>

<!-- Grafik Pemakaian Air -->
<div class="card-soft">
<div class="section-title"><i class="fa-solid fa-chart-line me-2" style="color: var(--primary-sage);"></i>Grafik Pemakaian Air Bulanan</div>
<?php if (!empty($chart_labels)): ?>
<div class="chart-container">
<canvas id="chartPemakaian"></canvas>
</div>
<?php else: ?>
<div class="text-center text-muted py-4">
<i class="fa-solid fa-chart-bar fa-3x mb-3 opacity-50"></i>
<p class="mb-0">Data grafik belum tersedia</p>
</div>
<?php endif; ?>
</div>

<!-- Berita & Pengumuman (Carousel Horizontal) -->
<?php if (!empty($berita)): ?>
<div class="card-soft">
    <div class="section-title"><i class="fa-solid fa-newspaper me-2" style="color: var(--primary-sage);"></i>Berita & Pengumuman</div>
    <p class="small text-muted mb-3" style="font-size:0.78rem;">
        <i class="fa-solid fa-hand-pointer me-1"></i> Geser ke samping untuk melihat berita lainnya
    </p>
    
    <div class="berita-carousel">
        <?php foreach ($berita as $b): ?>
        <a href="berita_detail.php?id=<?= $b['id'] ?>" class="berita-slide" style="text-decoration: none; color: inherit;">
            <div class="news-item h-100">
                <span class="badge bg-light text-sage mb-2"><?= ucfirst($b['kategori']) ?></span>
                <div class="news-title"><?= htmlspecialchars($b['judul']) ?></div>
                <div class="news-meta">
                    <i class="fa-regular fa-calendar me-1"></i> <?= date('d M Y', strtotime($b['tgl_posting'])) ?>
                </div>
                <div class="news-excerpt"><?= htmlspecialchars(substr(strip_tags($b['isi']), 0, 120)) ?>...</div>
                <div class="text-end mt-2">
                    <span class="small fw-bold" style="color: var(--primary-sage);">
                        Baca Selengkapnya <i class="fa-solid fa-chevron-right"></i>
                    </span>
                </div>
            </div>
        </a>
        <?php endforeach; ?>
    </div>
    
    <!-- Indikator Dots -->
    <?php if (count($berita) > 1): ?>
    <div class="carousel-dots">
        <?php foreach ($berita as $i => $b): ?>
            <span class="dot <?= $i === 0 ? 'active' : '' ?>"></span>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Akses Cepat -->
<div class="card-soft">
<div class="section-title">Akses Cepat</div>
<a href="login.php" class="menu-link">
<div class="menu-icon"><i class="fa-solid fa-user-shield"></i></div>
<div><div class="fw-bold">Masuk Dashboard</div><div class="small text-muted">Untuk Admin, Petugas, dan Pelanggan</div></div>
<i class="fa-solid fa-chevron-right ms-auto text-muted"></i>
</a>
<a href="laporan_keuangan.php" class="menu-link">
<div class="menu-icon"><i class="fa-solid fa-chart-pie"></i></div>
<div><div class="fw-bold">Laporan Keuangan</div><div class="small text-muted">Transparansi keuangan SPAM berbasis masyarakat</div></div>
<i class="fa-solid fa-chevron-right ms-auto text-muted"></i>
</a>
<a href="cek_tagihan.php" class="menu-link">
<div class="menu-icon"><i class="fa-solid fa-file-invoice-dollar"></i></div>
<div><div class="fw-bold">Cek Tagihan</div><div class="small text-muted">Cek tagihan menggunakan ID Meteran</div></div>
<i class="fa-solid fa-chevron-right ms-auto text-muted"></i>
</a>
</div>
</div>

<footer style="text-align:center; padding:20px 15px; font-size:0.85rem; color:#777; background:white; border-top:1px solid #f0f0f0;">
<div class="d-flex align-items-center justify-content-center gap-2 flex-wrap">
<img src="assets/uploads/logo/tirtha-kedawung.png"
alt="Logo Tirtha Kedawung"
style="height:25px; width:auto; object-fit:contain;">
<span>&copy; 2026 <b>SPAM Tirtha Kedawung</b> v.1.0</span>
</div>
</footer>

<script>
<?php if (!empty($chart_labels)): ?>
const ctx = document.getElementById('chartPemakaian').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: <?= json_encode($chart_labels) ?>,
datasets: [{
label: 'Pemakaian Air (m³)',
data: <?= json_encode($chart_values) ?>,
backgroundColor: <?= json_encode($chart_colors) ?>,
borderColor: 'rgba(92, 141, 137, 1)',
borderWidth: 1,
borderRadius: 8,
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
label: function(context) {
return context.parsed.y.toFixed(2) + ' m³';
}
}
}
},
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function(value) {
return value + ' m³';
}
},
grid: { color: 'rgba(0,0,0,0.05)' }
},
x: { grid: { display: false } }
}
}
});
<?php endif; ?>
</script>
</body>
</html>