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

// Filter default bulan & tahun ini
$bulan = isset($_GET['bulan']) ? (int)$_GET['bulan'] : (int)date('m');
$tahun = isset($_GET['tahun']) ? (int)$_GET['tahun'] : (int)date('Y');
$nama_bulan = ['','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];

// ===== PENDAPATAN =====
// 1. Pendapatan Air (dari buku_kas kategori Pembayaran Air)
$pendapatan_air = (float)$pdo->prepare("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='masuk' AND kategori='Pembayaran Air' AND MONTH(tanggal)=? AND YEAR(tanggal)=?")->execute([$bulan, $tahun]) ? 
    $pdo->query("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='masuk' AND kategori='Pembayaran Air' AND MONTH(tanggal)=$bulan AND YEAR(tanggal)=$tahun")->fetchColumn() : 0;

// 2. Pendapatan Pasang Baru
$pendapatan_pasang = (float)$pdo->query("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='masuk' AND kategori='Pasang Baru' AND MONTH(tanggal)=$bulan AND YEAR(tanggal)=$tahun")->fetchColumn();

// 3. Pendapatan Lain
$pendapatan_lain = (float)$pdo->query("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='masuk' AND kategori NOT IN ('Pembayaran Air','Pasang Baru') AND MONTH(tanggal)=$bulan AND YEAR(tanggal)=$tahun")->fetchColumn();

$total_pendapatan = $pendapatan_air + $pendapatan_pasang + $pendapatan_lain;

// ===== PENGELUARAN =====
$beban_operasional = (float)$pdo->query("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='keluar' AND kategori='Operasional' AND MONTH(tanggal)=$bulan AND YEAR(tanggal)=$tahun")->fetchColumn();
$beban_honor = (float)$pdo->query("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='keluar' AND kategori='Honor Petugas' AND MONTH(tanggal)=$bulan AND YEAR(tanggal)=$tahun")->fetchColumn();
$beban_lain = (float)$pdo->query("SELECT COALESCE(SUM(nominal),0) FROM buku_kas WHERE jenis='keluar' AND kategori NOT IN ('Operasional','Honor Petugas') AND MONTH(tanggal)=$bulan AND YEAR(tanggal)=$tahun")->fetchColumn();

$total_pengeluaran = $beban_operasional + $beban_honor + $beban_lain;
$saldo_bersih = $total_pendapatan - $total_pengeluaran;

// Detail Transaksi untuk Laporan
$transaksi_masuk = $pdo->query("SELECT * FROM buku_kas WHERE jenis='masuk' AND MONTH(tanggal)=$bulan AND YEAR(tanggal)=$tahun ORDER BY tanggal ASC")->fetchAll(PDO::FETCH_ASSOC);
$transaksi_keluar = $pdo->query("SELECT * FROM buku_kas WHERE jenis='keluar' AND MONTH(tanggal)=$bulan AND YEAR(tanggal)=$tahun ORDER BY tanggal ASC")->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>Laporan Keuangan - 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">
<style>
body { background:#f4f7fe; font-family:'Segoe UI'; }
.bg-header{
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color:white; padding:18px;
    border-bottom-left-radius:20px; border-bottom-right-radius:20px;
}
.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; }
.laporan-row {
    display: flex; justify-content: space-between; align-items: center;
    padding: 10px 0; border-bottom: 1px dashed #e0e0e0;
}
.laporan-row:last-child { border-bottom: none; }
.laporan-label { color: #5a6270; font-size: 0.9rem; }
.laporan-value { font-weight: 700; color: #2f3440; font-size: 0.95rem; }
.total-box {
    background: #f0f7ff; border-radius: 12px; padding: 15px;
    display: flex; justify-content: space-between; align-items: center; margin-top: 10px;
}
.total-box.pengeluaran { background: #fff5f5; }
.total-box.saldo { background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%); color: white; }
.total-box.saldo .laporan-label { color: rgba(255,255,255,0.9); }
.total-box.saldo .laporan-value { color: white; font-size: 1.3rem; }
.transaksi-item {
    display: flex; justify-content: space-between; align-items: center;
    padding: 10px 0; border-bottom: 1px solid #f0f0f0;
}
.transaksi-item:last-child { border-bottom: none; }
.trans-info { flex: 1; }
.trans-ket { font-weight: 600; font-size: 0.85rem; color: #2f3440; }
.trans-meta { font-size: 0.75rem; color: #7a8190; }
.trans-nominal { font-weight: 800; font-size: 0.9rem; }
.text-masuk { color: #198754; }
.text-keluar { color: #dc3545; }
.form-select { border-radius: 10px; }
</style>
</head>
<body>

<div class="bg-header shadow-sm">
    <div class="container d-flex justify-content-between align-items-center">
        <a href="dashboard.php" class="text-white"><i class="fa fa-arrow-left"></i></a>
        <h5 class="mb-0 fw-bold">Laporan Keuangan</h5>
        <div style="width: 20px;"></div>
    </div>
</div>

<div class="container pb-5 mt-3">
    <!-- Filter Periode -->
    <form method="GET" class="d-flex gap-2 mb-3">
        <select name="bulan" class="form-select form-select-sm">
            <?php foreach($nama_bulan as $i => $b): if($i==0) continue; ?>
                <option value="<?= $i ?>" <?= ($i == $bulan) ? 'selected' : '' ?>><?= $b ?></option>
            <?php endforeach; ?>
        </select>
        <select name="tahun" class="form-select form-select-sm" style="width: 90px;">
            <?php for($y = date('Y'); $y >= date('Y')-3; $y--): ?>
                <option value="<?= $y ?>" <?= ($y == $tahun) ? 'selected' : '' ?>><?= $y ?></option>
            <?php endfor; ?>
        </select>
        <button class="btn btn-sm text-white" style="background:#3A7CA5; border-radius:10px;"><i class="fa fa-filter"></i></button>
    </form>

    <!-- Ringkasan Laporan -->
    <div class="card-soft">
        <div class="section-title"><i class="fa fa-chart-pie me-2 text-primary"></i>Ringkasan <?= $nama_bulan[$bulan] ?> <?= $tahun ?></div>
        
        <div class="fw-bold small text-muted mb-2 mt-2">PENDAPATAN</div>
        <div class="laporan-row">
            <span class="laporan-label"><i class="fa fa-droplet me-1 text-primary"></i> Pendapatan Air</span>
            <span class="laporan-value text-masuk"><?= format_rupiah($pendapatan_air) ?></span>
        </div>
        <div class="laporan-row">
            <span class="laporan-label"><i class="fa fa-plug me-1 text-warning"></i> Pasang Baru</span>
            <span class="laporan-value text-masuk"><?= format_rupiah($pendapatan_pasang) ?></span>
        </div>
        <div class="laporan-row">
            <span class="laporan-label"><i class="fa fa-coins me-1 text-secondary"></i> Pendapatan Lain</span>
            <span class="laporan-value text-masuk"><?= format_rupiah($pendapatan_lain) ?></span>
        </div>
        <div class="total-box">
            <span class="laporan-label fw-bold">Total Pendapatan</span>
            <span class="laporan-value text-masuk"><?= format_rupiah($total_pendapatan) ?></span>
        </div>

        <div class="fw-bold small text-muted mb-2 mt-4">PENGELUARAN</div>
        <div class="laporan-row">
            <span class="laporan-label"><i class="fa fa-store me-1 text-danger"></i> Operasional</span>
            <span class="laporan-value text-keluar"><?= format_rupiah($beban_operasional) ?></span>
        </div>
        <div class="laporan-row">
            <span class="laporan-label"><i class="fa fa-user-tie me-1 text-danger"></i> Honor Petugas</span>
            <span class="laporan-value text-keluar"><?= format_rupiah($beban_honor) ?></span>
        </div>
        <div class="laporan-row">
            <span class="laporan-label"><i class="fa fa-receipt me-1 text-danger"></i> Pengeluaran Lain</span>
            <span class="laporan-value text-keluar"><?= format_rupiah($beban_lain) ?></span>
        </div>
        <div class="total-box pengeluaran">
            <span class="laporan-label fw-bold">Total Pengeluaran</span>
            <span class="laporan-value text-keluar"><?= format_rupiah($total_pengeluaran) ?></span>
        </div>

        <div class="total-box saldo mt-4">
            <span class="laporan-label fw-bold"><i class="fa fa-wallet me-1"></i> Saldo Bersih</span>
            <span class="laporan-value"><?= format_rupiah($saldo_bersih) ?></span>
        </div>
    </div>

    <!-- Detail Transaksi Masuk -->
    <div class="card-soft">
        <div class="section-title"><i class="fa fa-arrow-down me-2 text-success"></i>Detail Pemasukan</div>
        <?php if (empty($transaksi_masuk)): ?>
            <div class="text-center text-muted py-3 small">Tidak ada pemasukan pada periode ini.</div>
        <?php else: ?>
            <?php foreach ($transaksi_masuk as $t): ?>
            <div class="transaksi-item">
                <div class="trans-info">
                    <div class="trans-ket"><?= htmlspecialchars($t['kategori']) ?></div>
                    <div class="trans-meta"><?= date('d/m/Y', strtotime($t['tanggal'])) ?> • <?= htmlspecialchars($t['keterangan']) ?></div>
                </div>
                <div class="trans-nominal text-masuk">+ <?= format_rupiah($t['nominal']) ?></div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- Detail Transaksi Keluar -->
    <div class="card-soft">
        <div class="section-title"><i class="fa fa-arrow-up me-2 text-danger"></i>Detail Pengeluaran</div>
        <?php if (empty($transaksi_keluar)): ?>
            <div class="text-center text-muted py-3 small">Tidak ada pengeluaran pada periode ini.</div>
        <?php else: ?>
            <?php foreach ($transaksi_keluar as $t): ?>
            <div class="transaksi-item">
                <div class="trans-info">
                    <div class="trans-ket"><?= htmlspecialchars($t['kategori']) ?></div>
                    <div class="trans-meta"><?= date('d/m/Y', strtotime($t['tanggal'])) ?> • <?= htmlspecialchars($t['keterangan']) ?></div>
                </div>
                <div class="trans-nominal text-keluar">- <?= format_rupiah($t['nominal']) ?></div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

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