<?php
require_once __DIR__ . '/../config/database.php';
$db = getDB();

$dari = $_GET['dari'] ?? date('Y-m-01');
$sampai = $_GET['sampai'] ?? date('Y-m-t');

// Calculate Jasa (dari Angsuran)
$pinjamanStmt = $db->prepare("
    SELECT p.no_pinjaman, ang.tanggal_bayar, ang.bayar_jasa as jasa, a.nama, ang.angsuran_ke
    FROM angsuran ang
    JOIN pinjaman p ON ang.pinjaman_id = p.id
    JOIN anggota a ON p.anggota_id = a.id
    WHERE ang.tanggal_bayar BETWEEN ? AND ?
    ORDER BY ang.tanggal_bayar DESC
");
$pinjamanStmt->execute([$dari, $sampai]);
$jasaList = $pinjamanStmt->fetchAll();

// Get LabA/Rugi records
$lrStmt = $db->prepare("SELECT * FROM laba_rugi WHERE tanggal BETWEEN ? AND ? ORDER BY tanggal DESC");
$lrStmt->execute([$dari, $sampai]);
$manualList = $lrStmt->fetchAll();

$allTransactions = [];
$totalPendapatan = 0;
$totalPengeluaran = 0;

foreach($jasaList as $j) {
    $allTransactions[] = [
        'tanggal' => $j['tanggal_bayar'],
        'jenis' => 'pendapatan',
        'kategori' => 'Jasa Pinjaman',
        'keterangan' => 'Angsuran Ke-' . $j['angsuran_ke'] . ' - PNJ: ' . $j['no_pinjaman'] . ' (' . $j['nama'] . ')',
        'jumlah' => $j['jasa']
    ];
    $totalPendapatan += $j['jasa'];
}

foreach($manualList as $m) {
    $allTransactions[] = [
        'tanggal' => $m['tanggal'],
        'jenis' => $m['jenis'],
        'kategori' => $m['kategori'],
        'keterangan' => $m['keterangan'] ?? '-',
        'jumlah' => $m['jumlah']
    ];
    if ($m['jenis'] === 'pendapatan') {
        $totalPendapatan += $m['jumlah'];
    } else {
        $totalPengeluaran += $m['jumlah'];
    }
}

// Sort by date desc
usort($allTransactions, function($a, $b) {
    return strtotime($b['tanggal']) - strtotime($a['tanggal']);
});

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=Laba_Rugi_{$dari}_{$sampai}.xls");
header("Pragma: no-cache");
header("Expires: 0");
?>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body>
    <h2>Laporan Laba/Rugi Operasional</h2>
    <p>Periode: <?= $dari ?> s/d <?= $sampai ?></p>

    <table border="1" cellpadding="5" cellspacing="0">
        <thead>
            <tr style="background-color: #e2efda;">
                <th>No</th>
                <th>Tanggal</th>
                <th>Jenis</th>
                <th>Kategori / Sumber</th>
                <th>Pendapatan (Debit)</th>
                <th>Pengeluaran (Kredit)</th>
                <th>Keterangan</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $no = 1;
            foreach ($allTransactions as $t): 
                $isSetoran = $t['jenis'] === 'pendapatan';
            ?>
            <tr>
                <td><?= $no++ ?></td>
                <td><?= $t['tanggal'] ?></td>
                <td><?= ucfirst($t['jenis']) ?></td>
                <td><?= htmlspecialchars($t['kategori']) ?></td>
                <td><?= $isSetoran ? $t['jumlah'] : '' ?></td>
                <td><?= !$isSetoran ? $t['jumlah'] : '' ?></td>
                <td><?= htmlspecialchars($t['keterangan'] ?? '-') ?></td>
            </tr>
            <?php endforeach; ?>
            <tr style="background-color: #f2f2f2; font-weight: bold;">
                <td colspan="4" align="right">TOTAL</td>
                <td><?= $totalPendapatan ?></td>
                <td><?= $totalPengeluaran ?></td>
                <td></td>
            </tr>
            <tr style="background-color: #fff2cc; font-weight: bold;">
                <td colspan="4" align="right">LABA KOTOR / BERSIH</td>
                <td colspan="2" align="center"><?= $totalPendapatan - $totalPengeluaran ?></td>
                <td></td>
            </tr>
        </tbody>
    </table>
</body>
</html>
