<?php
/**
 * Laporan Laba Rugi
 * Koperasi Management System
 */

$pageTitle = 'Laporan Laba Rugi';
$pageSubtitle = 'Rincian pendapatan dan pengeluaran operasional';

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

// Ensure laba_rugi table exists
$db->exec("
    CREATE TABLE IF NOT EXISTS laba_rugi (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tanggal DATE NOT NULL,
        jenis ENUM('pendapatan', 'pengeluaran') NOT NULL,
        kategori VARCHAR(100) NOT NULL,
        jumlah DECIMAL(15,2) NOT NULL,
        keterangan VARCHAR(255) NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB
");

// Handle CRUD operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $tanggal = $_POST['tanggal'];
        $jenis = $_POST['jenis'];
        $kategori = sanitize($_POST['kategori']);
        $jumlah = str_replace('.', '', $_POST['jumlah']);
        $keterangan = sanitize($_POST['keterangan']);

        $stmt = $db->prepare("INSERT INTO laba_rugi (tanggal, jenis, kategori, jumlah, keterangan) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$tanggal, $jenis, $kategori, $jumlah, $keterangan]);
        setFlash('success', 'Data laba/rugi berhasil ditambahkan.');
        header("Location: laporan_laba_rugi.php?bulan=" . ($_GET['bulan'] ?? '') . "&tahun=" . ($_GET['tahun'] ?? ''));
        exit;
    }

    if ($action === 'edit') {
        $id = $_POST['id'];
        $tanggal = $_POST['tanggal'];
        $jenis = $_POST['jenis'];
        $kategori = sanitize($_POST['kategori']);
        $jumlah = str_replace('.', '', $_POST['jumlah']);
        $keterangan = sanitize($_POST['keterangan']);

        $stmt = $db->prepare("UPDATE laba_rugi SET tanggal=?, jenis=?, kategori=?, jumlah=?, keterangan=? WHERE id=?");
        $stmt->execute([$tanggal, $jenis, $kategori, $jumlah, $keterangan, $id]);
        setFlash('success', 'Data laba/rugi berhasil diperbarui.');
        header("Location: laporan_laba_rugi.php?bulan=" . ($_GET['bulan'] ?? '') . "&tahun=" . ($_GET['tahun'] ?? ''));
        exit;
    }

    if ($action === 'delete') {
        $id = $_POST['id'];
        $stmt = $db->prepare("DELETE FROM laba_rugi WHERE id=?");
        $stmt->execute([$id]);
        setFlash('success', 'Data laba/rugi berhasil dihapus.');
        header("Location: laporan_laba_rugi.php?bulan=" . ($_GET['bulan'] ?? '') . "&tahun=" . ($_GET['tahun'] ?? ''));
        exit;
    }
}

// Filters
$bulan = (isset($_GET['bulan']) && is_numeric($_GET['bulan'])) ? (int)$_GET['bulan'] : (int)date('m');
$tahun = (isset($_GET['tahun']) && is_numeric($_GET['tahun'])) ? (int)$_GET['tahun'] : (int)date('Y');

$dari = $tahun . '-' . str_pad($bulan, 2, '0', STR_PAD_LEFT) . '-01';
$sampai = date('Y-m-t', strtotime($dari));

// 1. Fetch Pendapatan Jasa Pinjaman (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();

$totalJasa = array_sum(array_column($jasaList, 'jasa'));

// 2. Fetch manual Laba/Rugi entries
$lrStmt = $db->prepare("SELECT * FROM laba_rugi WHERE tanggal BETWEEN ? AND ? ORDER BY tanggal DESC");
$lrStmt->execute([$dari, $sampai]);
$manualList = $lrStmt->fetchAll();

$totalPendapatanManual = 0;
$totalPengeluaran = 0;

foreach ($manualList as $m) {
    if ($m['jenis'] === 'pendapatan') {
        $totalPendapatanManual += $m['jumlah'];
    } else {
        $totalPengeluaran += $m['jumlah'];
    }
}

$totalPendapatanKeseluruhan = $totalJasa + $totalPendapatanManual;
$labaKotor = $totalPendapatanKeseluruhan - $totalPengeluaran;

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

<!-- Filter Bar -->
<div class="card mb-3">
    <div class="card-body">
        <form method="GET" class="toolbar" style="align-items: flex-end;">
            <div class="form-group" style="margin-bottom: 0;">
                <label style="font-size: 0.78rem; margin-bottom: 4px;">Bulan</label>
                <select name="bulan" class="form-control" id="filter_bulan">
                    <?php 
                    $namaBulan = [1=>'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
                    for ($i=1; $i<=12; $i++): 
                    ?>
                        <option value="<?= $i ?>" <?= $bulan == $i ? 'selected' : '' ?>><?= $namaBulan[$i] ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="form-group" style="margin-bottom: 0;">
                <label style="font-size: 0.78rem; margin-bottom: 4px;">Tahun</label>
                <input type="number" name="tahun" class="form-control" value="<?= $tahun ?>" id="filter_tahun" min="2000" max="2100">
            </div>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-filter"></i> Filter
            </button>
            <button type="button" class="btn btn-success" onclick="openModal('addModal')">
                <i class="fas fa-plus"></i> Tambah Transaksi
            </button>
            <a href="../exports/laba_rugi_export.php?dari=<?= $dari ?>&sampai=<?= $sampai ?>&format=excel" class="btn btn-outline" target="_blank" style="color:var(--success-600); border-color:var(--success-600);">
                <i class="fas fa-file-excel"></i> Export Excel
            </a>
            <button type="button" class="btn btn-outline" onclick="printPage()">
                <i class="fas fa-print"></i> Cetak
            </button>
        </form>
    </div>
</div>

<!-- Laba Rugi Resume -->
<div class="stats-grid">
    <div class="stat-card success">
        <div class="stat-info">
            <h3>Total Pendapatan</h3>
            <div class="stat-value"><?= formatRupiah($totalPendapatanKeseluruhan) ?></div>
            <span class="text-muted" style="font-size: 0.8rem;">(Termasuk Jasa Pinjaman <?= formatRupiah($totalJasa) ?>)</span>
        </div>
        <div class="stat-icon success"><i class="fas fa-arrow-down"></i></div>
    </div>
    <div class="stat-card danger">
        <div class="stat-info">
            <h3>Total Beban / Pengeluaran</h3>
            <div class="stat-value"><?= formatRupiah($totalPengeluaran) ?></div>
        </div>
        <div class="stat-icon danger"><i class="fas fa-arrow-up"></i></div>
    </div>
    <div class="stat-card primary">
        <div class="stat-info">
            <h3>Laba Bersih</h3>
            <div class="stat-value"><?= formatRupiah($labaKotor) ?></div>
        </div>
        <div class="stat-icon primary"><i class="fas fa-balance-scale"></i></div>
    </div>
</div>

<!-- Detailed Data -->
<div class="card">
    <div class="card-header">
        <h2>Rincian Transaksi Laba Rugi (<?= formatTanggal($dari) ?> - <?= formatTanggal($sampai) ?>)</h2>
    </div>
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Tanggal</th>
                    <th>Jenis</th>
                    <th>Kategori / Sumber</th>
                    <th>Keterangan</th>
                    <th class="text-right">Pemasukan</th>
                    <th class="text-right">Pengeluaran</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $no = 1; 
                $allTransactions = [];

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

                // Format Manual
                foreach($manualList as $m) {
                    $allTransactions[] = [
                        'id' => $m['id'],
                        'tanggal' => $m['tanggal'],
                        'jenis' => $m['jenis'],
                        'kategori' => $m['kategori'],
                        'keterangan' => $m['keterangan'] ?? '-',
                        'jumlah' => $m['jumlah'],
                        'is_auto' => false
                    ];
                }

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

                if (empty($allTransactions)) {
                    echo '<tr><td colspan="8" class="text-center text-muted" style="padding: 30px;">Tidak ada transaksi</td></tr>';
                }

                foreach ($allTransactions as $t): 
                ?>
                <tr>
                    <td><?= $no++ ?></td>
                    <td><?= formatTanggal($t['tanggal']) ?></td>
                    <td>
                        <span class="badge <?= $t['jenis'] === 'pendapatan' ? 'badge-success' : 'badge-danger' ?>">
                            <?= ucfirst($t['jenis']) ?>
                        </span>
                    </td>
                    <td>
                        <strong><?= htmlspecialchars($t['kategori']) ?></strong>
                        <?php if($t['is_auto']): ?>
                            <span class="badge badge-info" style="font-size: 0.65rem; margin-left: 5px;">Auto</span>
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($t['keterangan']) ?></td>
                    <td class="text-right text-success fw-bold">
                        <?= $t['jenis'] === 'pendapatan' ? formatRupiah($t['jumlah']) : '-' ?>
                    </td>
                    <td class="text-right text-danger fw-bold">
                        <?= $t['jenis'] === 'pengeluaran' ? formatRupiah($t['jumlah']) : '-' ?>
                    </td>
                    <td>
                        <?php if (!$t['is_auto']): ?>
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-outline-warning" onclick="editLabaRugi(<?= $t['id'] ?>, '<?= $t['tanggal'] ?>', '<?= $t['jenis'] ?>', '<?= addslashes($t['kategori']) ?>', '<?= $t['jumlah'] ?>', '<?= addslashes($t['keterangan']) ?>')">
                                <i class="fas fa-edit"></i>
                            </button>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus data laba/rugi ini?');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $t['id'] ?>">
                                <button class="btn btn-sm btn-outline-danger">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </div>
                        <?php else: ?>
                            <span class="text-muted" style="font-size:0.8rem; font-style:italic;">Dibuat sistem</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                
                <?php if (!empty($allTransactions)): ?>
                <tr style="background: var(--gray-50); font-weight: 700; border-top: 2px solid var(--gray-300);">
                    <td colspan="5" class="text-right">TOTAL KESELURUHAN</td>
                    <td class="text-right text-success"><?= formatRupiah($totalPendapatanKeseluruhan) ?></td>
                    <td class="text-right text-danger"><?= formatRupiah($totalPengeluaran) ?></td>
                    <td></td>
                </tr>
                <tr style="background: var(--primary-50); font-weight: 800;">
                    <td colspan="5" class="text-right text-primary">LABA BERSIH</td>
                    <td colspan="2" class="text-center text-primary" style="font-size: 1.1rem;"><?= formatRupiah($labaKotor) ?></td>
                    <td></td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal Target Laba Rugi -->
<div class="modal" id="addModal">
    <div class="modal-header">
        <h3 id="modalTitle">Tambah Transaksi Laba/Rugi</h3>
        <button class="modal-close" onclick="closeModal('addModal')">&times;</button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" id="modalAction" value="add">
        <input type="hidden" name="id" id="modalId">
        <div class="modal-body">
            <div class="form-row">
                <div class="form-group">
                    <label>Tanggal Transaksi</label>
                    <input type="date" name="tanggal" id="modalTanggal" class="form-control" value="<?= date('Y-m-d') ?>" required>
                </div>
                <div class="form-group">
                    <label>Jenis</label>
                    <select name="jenis" id="modalJenis" class="form-control" required>
                        <option value="pendapatan">Pendapatan (+)</option>
                        <option value="pengeluaran">Pengeluaran / Beban (-)</option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <label>Kategori</label>
                <input type="text" name="kategori" id="modalKategori" class="form-control" placeholder="Contoh: Beban Listrik, Honor, Donasi..." required>
            </div>
            
            <div class="form-group">
                <label>Jumlah (Rp)</label>
                <input type="text" name="jumlah" id="modalJumlah" class="form-control" oninput="formatCurrencyInput(this)" required>
            </div>
            
            <div class="form-group">
                <label>Keterangan Tambahan</label>
                <textarea name="keterangan" id="modalKeterangan" class="form-control" rows="2" placeholder="Detail transaksi..."></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('addModal')">Batal</button>
            <button type="submit" class="btn btn-primary">Simpan Transaksi</button>
        </div>
    </form>
</div>

<script>
function editLabaRugi(id, tanggal, jenis, kategori, jumlah, keterangan) {
    document.getElementById('modalTitle').innerText = 'Edit Transaksi Laba/Rugi';
    document.getElementById('modalAction').value = 'edit';
    document.getElementById('modalId').value = id;
    
    document.getElementById('modalTanggal').value = tanggal;
    document.getElementById('modalJenis').value = jenis;
    document.getElementById('modalKategori').value = kategori;
    document.getElementById('modalJumlah').value = new Intl.NumberFormat('id-ID').format(jumlah);
    document.getElementById('modalKeterangan').value = keterangan;
    
    openModal('addModal');
}
</script>

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