<?php
require_once __DIR__ . '/includes/functions.php';
requireLogin();
$pageTitle = 'Buku Besar';

$akunList = $pdo->query("SELECT * FROM akun_kas ORDER BY nama_akun")->fetchAll();
$akunId = $_GET['akun_id'] ?? ($akunList[0]['id'] ?? null);
$dari = $_GET['dari'] ?? date('Y-m-01');
$sampai = $_GET['sampai'] ?? date('Y-m-d');

$saldoAwalPeriode = 0;
$transaksiList = [];

if ($akunId) {
    $akun = $pdo->prepare("SELECT * FROM akun_kas WHERE id=:id"); $akun->execute(['id'=>$akunId]); $akun = $akun->fetch();

    // Saldo sebelum periode = saldo_awal akun + transaksi sebelum tanggal "dari"
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(CASE WHEN tipe='pemasukan' THEN jumlah ELSE -jumlah END),0) FROM transaksi WHERE akun_id=:id AND tanggal < :dari");
    $stmt->execute(['id'=>$akunId, 'dari'=>$dari]);
    $saldoAwalPeriode = $akun['saldo_awal'] + $stmt->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT t.*, k.nama as kategori_nama
        FROM transaksi t JOIN kategori k ON k.id=t.kategori_id
        WHERE t.akun_id=:id AND t.tanggal BETWEEN :dari AND :sampai
        ORDER BY t.tanggal, t.id
    ");
    $stmt->execute(['id'=>$akunId, 'dari'=>$dari, 'sampai'=>$sampai]);
    $transaksiList = $stmt->fetchAll();
}

include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3 no-print">
    <h5 class="mb-0">Buku Besar</h5>
    <button class="btn btn-outline-secondary" onclick="window.print()"><i class="bi bi-printer"></i> Cetak</button>
</div>

<div class="card mb-3 no-print">
    <div class="card-body">
        <form method="GET" class="row g-2">
            <div class="col-md-4">
                <select name="akun_id" class="form-select">
                    <?php foreach ($akunList as $a): ?>
                        <option value="<?= $a['id'] ?>" <?= $akunId==$a['id']?'selected':'' ?>><?= htmlspecialchars($a['nama_akun']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3"><input type="date" name="dari" value="<?= htmlspecialchars($dari) ?>" class="form-control"></div>
            <div class="col-md-3"><input type="date" name="sampai" value="<?= htmlspecialchars($sampai) ?>" class="form-control"></div>
            <div class="col-md-2"><button class="btn btn-primary w-100"><i class="bi bi-funnel"></i> Tampilkan</button></div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <?= renderKopSurat(getPengaturan($pdo)) ?>
        <div class="judul-laporan-resmi d-none d-print-block">
            <h5>BUKU BESAR</h5>
            <p>Akun: <?= htmlspecialchars($akun['nama_akun'] ?? '-') ?> &mdash; Periode <?= tanggalIndo($dari) ?> s/d <?= tanggalIndo($sampai) ?></p>
        </div>
        <div class="card-header no-print">
            Buku Besar Akun: <?= htmlspecialchars($akun['nama_akun'] ?? '-') ?>
            &mdash; Periode <?= tanggalIndo($dari) ?> s/d <?= tanggalIndo($sampai) ?>
        </div>
        <table class="table table-bordered">
            <thead>
                <tr><th>Tanggal</th><th>No. Transaksi</th><th>Keterangan</th><th>Kategori</th><th class="text-end">Debit (Masuk)</th><th class="text-end">Kredit (Keluar)</th><th class="text-end">Saldo</th></tr>
            </thead>
            <tbody>
                <tr class="table-light fw-semibold">
                    <td colspan="6">Saldo Awal Periode</td>
                    <td class="text-end"><?= rupiah($saldoAwalPeriode) ?></td>
                </tr>
                <?php $saldoBerjalan = $saldoAwalPeriode; ?>
                <?php foreach ($transaksiList as $row): ?>
                    <?php $saldoBerjalan += $row['tipe']==='pemasukan' ? $row['jumlah'] : -$row['jumlah']; ?>
                    <tr>
                        <td><?= tanggalIndo($row['tanggal']) ?></td>
                        <td><?= htmlspecialchars($row['no_transaksi']) ?></td>
                        <td><?= htmlspecialchars($row['keterangan']) ?></td>
                        <td><?= htmlspecialchars($row['kategori_nama']) ?></td>
                        <td class="text-end text-success"><?= $row['tipe']==='pemasukan' ? rupiah($row['jumlah']) : '' ?></td>
                        <td class="text-end text-danger"><?= $row['tipe']==='pengeluaran' ? rupiah($row['jumlah']) : '' ?></td>
                        <td class="text-end"><?= rupiah($saldoBerjalan) ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($transaksiList)): ?>
                    <tr><td colspan="7" class="text-center text-muted py-3">Tidak ada transaksi pada periode ini</td></tr>
                <?php endif; ?>
                <tr class="table-secondary fw-bold">
                    <td colspan="6">Saldo Akhir</td>
                    <td class="text-end"><?= rupiah($saldoBerjalan) ?></td>
                </tr>
            </tbody>
        </table>
        <?= renderTandaTanganLaporan(getPengaturan($pdo), $sampai) ?>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>