<?php
require_once '../config.php';

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

$id_pelanggan = $_SESSION['id'];
$nama_bulan = ['','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];

// Ambil Data Pelanggan
$stmt = $pdo->prepare("SELECT * FROM pelanggan WHERE id = ?");
$stmt->execute([$id_pelanggan]);
$pelanggan = $stmt->fetch();

// Ambil Tarif Terkini (untuk rincian)
$tarif = $pdo->query("SELECT harga_m3, biaya_abonemen FROM tarif ORDER BY id DESC LIMIT 1")->fetch();
$harga_m3 = $tarif['harga_m3'] ?? 0;
$biaya_abonemen_default = $tarif['biaya_abonemen'] ?? 0;

// Ambil Tagihan Terbaru
$stmt_tagihan = $pdo->prepare("
    SELECT t.*, m.pemakaian, m.meter_awal, m.meter_akhir 
    FROM tagihan t
    LEFT JOIN meteran m ON t.id_meteran = m.id
    WHERE t.id_pelanggan = ?
    ORDER BY t.tahun DESC, t.bulan DESC
    LIMIT 1
");
$stmt_tagihan->execute([$id_pelanggan]);
$tagihan_terbaru = $stmt_tagihan->fetch();

// Ambil Data untuk Grafik Pemakaian (12 bulan terakhir)
$stmt_grafik = $pdo->prepare("
    SELECT bulan, tahun, pemakaian 
    FROM meteran 
    WHERE id_pelanggan = ?
    ORDER BY tahun ASC, bulan ASC
");
$stmt_grafik->execute([$id_pelanggan]);
$data_grafik = $stmt_grafik->fetchAll(PDO::FETCH_ASSOC);

// Ambil Histori Pembayaran Lengkap
$stmt_histori = $pdo->prepare("
    SELECT t.bulan, t.tahun, t.biaya_pemakaian, t.biaya_abonemen, t.total, t.status, t.tgl_bayar, 
           COALESCE(m.pemakaian, 0) AS pemakaian
    FROM tagihan t
    LEFT JOIN meteran m ON t.id_meteran = m.id
    WHERE t.id_pelanggan = ?
    ORDER BY t.tahun DESC, t.bulan DESC
");
$stmt_histori->execute([$id_pelanggan]);
$histori = $stmt_histori->fetchAll(PDO::FETCH_ASSOC);
?>
<!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 Pelanggan - SPAM</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: #f4f7fe; font-family: 'Segoe UI', sans-serif; }
.header-section {
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color: white;
    padding: 30px 20px 40px;
    border-bottom-left-radius: 40px;
    border-bottom-right-radius: 40px;
    margin-bottom: -20px;
}
.header-content h5 { font-weight: 300; opacity: 0.9; margin-bottom: 2px; font-size: 0.95rem; }
.header-content h2 { font-weight: 800; font-size: 1.6rem; margin-bottom: 5px; }
.pelanggan-tag {
    display: inline-block;
    background: rgba(255,255,255,0.2);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.75rem;
    backdrop-filter: blur(5px);
}
.menu-container { padding: 0 15px; }
.card-soft {
    background: white; border: none; border-radius: 20px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.05); padding: 20px; margin-bottom: 15px;
}
.section-title { font-size: 1rem; font-weight: 800; color: #354052; margin-bottom: 15px; }
.status-lunas { background: #d4edda; color: #155724; padding: 4px 10px; border-radius: 12px; font-weight: 700; font-size: 0.75rem; }
.status-belum { background: #fff3cd; color: #856404; padding: 4px 10px; border-radius: 12px; font-weight: 700; font-size: 0.75rem; }

/* Rincian Tagihan */
.rincian-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px dashed #e0e0e0;
    font-size: 0.9rem;
}
.rincian-item:last-child { border-bottom: none; }
.rincian-label { color: #5a6270; }
.rincian-value { font-weight: 700; color: #2f3440; }
.rincian-total {
    background: #f0f7ff;
    border-radius: 12px;
    padding: 12px;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.rincian-total .label { font-size: 0.9rem; color: #5a6270; font-weight: 600; }
.rincian-total .value { font-size: 1.3rem; font-weight: 800; color: #3A7CA5; }

/* Tabel Histori */
.histori-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0 8px;
}
.histori-table th {
    font-size: 0.75rem;
    color: #7a8190;
    font-weight: 700;
    text-transform: uppercase;
    padding: 8px 10px;
    text-align: left;
}
.histori-table td {
    background: #f8f9fc;
    padding: 12px 10px;
    font-size: 0.85rem;
    vertical-align: middle;
}
.histori-table tr td:first-child { border-radius: 10px 0 0 10px; }
.histori-table tr td:last-child { border-radius: 0 10px 10px 0; }
.histori-table .col-bulan { font-weight: 700; color: #2f3440; }
.histori-table .col-pakai { color: #3A7CA5; font-weight: 600; }
.histori-table .col-abonemen { color: #6c757d; }
.histori-table .col-total { font-weight: 800; color: #2f3440; }

.btn-logout {
    display: inline-flex; align-items: center; padding: 8px 25px; border-radius: 30px;
    font-size: 0.85rem; font-weight: 700; margin: 25px 0 10px;
    border: 2px solid #e74c3c; color: #e74c3c; text-decoration: none;
}
.app-footer { font-size: 0.65rem; color: #aaa; letter-spacing: 0.5px; padding-bottom: 20px; text-align: center; }
.chart-container { position: relative; height: 220px; }
.empty-chart { text-align: center; padding: 30px 10px; color: #8a909b; font-size: 0.85rem; }
</style>
</head>
<body>

<div class="header-section">
    <div class="header-content">
        <h5>Halo,</h5>
        <h2><?= htmlspecialchars($pelanggan['nama']) ?></h2>
        <div class="pelanggan-tag">
            <i class="fa fa-droplet me-1"></i> ID: <?= htmlspecialchars($pelanggan['id_meteran']) ?>
        </div>
    </div>
</div>

<div class="menu-container">
    <!-- Tagihan Terbaru dengan Rincian -->
    <div class="card-soft">
        <div class="section-title">
            <i class="fa-solid fa-file-invoice me-2 text-primary"></i>Tagihan Terbaru
        </div>
        <?php if ($tagihan_terbaru): ?>
            <div class="d-flex justify-content-between align-items-center mb-3 pb-2 border-bottom">
                <div>
                    <div class="fw-bold"><?= $nama_bulan[$tagihan_terbaru['bulan']] ?> <?= $tagihan_terbaru['tahun'] ?></div>
                    <div class="small text-muted">
                        <i class="fa fa-gauge-high me-1"></i> 
                        <?= number_format($tagihan_terbaru['pemakaian'], 3) ?> m³ 
                        (<?= number_format($tagihan_terbaru['meter_awal'], 3) ?> → <?= number_format($tagihan_terbaru['meter_akhir'], 3) ?>)
                    </div>
                </div>
                <div>
                    <?php if ($tagihan_terbaru['status'] === 'lunas'): ?>
                        <span class="status-lunas"><i class="fa-solid fa-check-circle me-1"></i> LUNAS</span>
                        <div class="small text-muted text-end mt-1">Dibayar: <?= date('d/m/Y', strtotime($tagihan_terbaru['tgl_bayar'])) ?></div>
                    <?php else: ?>
                        <span class="status-belum"><i class="fa-solid fa-clock me-1"></i> BELUM LUNAS</span>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Rincian Pembayaran -->
            <div class="px-1">
                <div class="rincian-item">
                    <span class="rincian-label">
                        <i class="fa fa-droplet me-1 text-primary"></i>
                        Pemakaian Air (<?= number_format($tagihan_terbaru['pemakaian'], 3) ?> m³ × <?= format_rupiah($harga_m3) ?>)
                    </span>
                    <span class="rincian-value"><?= format_rupiah($tagihan_terbaru['biaya_pemakaian']) ?></span>
                </div>
                <div class="rincian-item">
                    <span class="rincian-label">
                        <i class="fa fa-file-contract me-1 text-warning"></i>
                        Biaya Abonemen
                    </span>
                    <span class="rincian-value"><?= format_rupiah($tagihan_terbaru['biaya_abonemen']) ?></span>
                </div>
                <div class="rincian-total">
                    <span class="label"><i class="fa fa-coins me-1"></i> Total Tagihan</span>
                    <span class="value"><?= format_rupiah($tagihan_terbaru['total']) ?></span>
                </div>
            </div>

            <?php if ($tagihan_terbaru['status'] !== 'lunas'): ?>
                <div class="alert alert-info small mb-0 mt-3" style="border-radius: 12px;">
                    <i class="fa-solid fa-info-circle me-1"></i> Silakan lakukan pembayaran tunai kepada petugas penarik iuran.
                </div>
            <?php endif; ?>
        <?php else: ?>
            <div class="text-center text-muted py-3 small">Belum ada data tagihan.</div>
        <?php endif; ?>
    </div>

    <!-- Grafik Pemakaian Air -->
    <div class="card-soft">
        <div class="section-title">
            <i class="fa-solid fa-chart-line me-2 text-primary"></i>Grafik Pemakaian Air
        </div>
        <?php if (!empty($data_grafik)): ?>
            <div class="chart-container">
                <canvas id="chartPemakaian"></canvas>
            </div>
        <?php else: ?>
            <div class="empty-chart">
                <i class="fa fa-chart-bar fa-2x mb-2 d-block text-muted opacity-50"></i>
                Belum ada data pemakaian.
            </div>
        <?php endif; ?>
    </div>

    <!-- Histori Pembayaran -->
    <div class="card-soft">
        <div class="section-title">
            <i class="fa-solid fa-clock-rotate-left me-2 text-primary"></i>Histori Pembayaran
        </div>
        <?php if (!empty($histori)): ?>
            <div class="table-responsive">
                <table class="histori-table">
                    <thead>
                        <tr>
                            <th>Periode</th>
                            <th>Pemakaian</th>
                            <th>Abonemen</th>
                            <th>Total</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($histori as $h): ?>
                        <tr>
                            <td class="col-bulan">
                                <?= substr($nama_bulan[$h['bulan']], 0, 3) ?> <?= $h['tahun'] ?>
                                <?php if ($h['tgl_bayar']): ?>
                                    <div class="small text-muted" style="font-size:0.7rem;"><?= date('d/m/Y', strtotime($h['tgl_bayar'])) ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="col-pakai"><?= number_format($h['pemakaian'], 3) ?> m³</td>
                            <td class="col-abonemen"><?= format_rupiah($h['biaya_abonemen']) ?></td>
                            <td class="col-total"><?= format_rupiah($h['total']) ?></td>
                            <td>
                                <?php if ($h['status'] === 'lunas'): ?>
                                    <span class="status-lunas">Lunas</span>
                                <?php else: ?>
                                    <span class="status-belum">Belum</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center text-muted py-3 small">Belum ada riwayat pembayaran.</div>
        <?php endif; ?>
    </div>

    <div class="text-center">
        <a href="../logout.php" class="btn-logout" onclick="return confirm('Yakin ingin keluar?')">
            <i class="fa-solid fa-arrow-right-from-bracket me-2"></i> KELUAR
        </a>
        <div class="app-footer">SPAM Desa Gemuruh v.1.0</div>
    </div>
</div>

<script>
<?php if (!empty($data_grafik)): ?>
const ctx = document.getElementById('chartPemakaian').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?= json_encode(array_map(function($d) use ($nama_bulan) { 
            return substr($nama_bulan[$d['bulan']], 0, 3) . ' ' . $d['tahun']; 
        }, $data_grafik)) ?>,
        datasets: [{
            label: 'Pemakaian (m³)',
            data: <?= json_encode(array_map(function($d) { return (float)$d['pemakaian']; }, $data_grafik)) ?>,
            borderColor: '#3A7CA5',
            backgroundColor: 'rgba(58, 124, 165, 0.15)',
            borderWidth: 2.5,
            tension: 0.3,
            fill: true,
            pointBackgroundColor: '#3A7CA5',
            pointRadius: 4,
            pointHoverRadius: 6
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: { display: false },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        return context.parsed.y.toFixed(3) + ' m³';
                    }
                }
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: { color: 'rgba(0,0,0,0.04)' },
                ticks: { font: { size: 10 } }
            },
            x: {
                grid: { display: false },
                ticks: { font: { size: 10 }, maxRotation: 45 }
            }
        }
    }
});
<?php endif; ?>
</script>

</body>
</html>