<?php
require_once __DIR__ . '/includes/functions.php';
requireLogin();
$pageTitle = 'Pengeluaran';
$TIPE = 'pengeluaran';

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

    if ($action === 'save') {
        $id = $_POST['id'] ?? '';
        $buktiFile = null;

        if (!empty($_FILES['bukti']['name'])) {
            $ext = pathinfo($_FILES['bukti']['name'], PATHINFO_EXTENSION);
            $buktiFile = 'bukti_' . time() . '_' . rand(100,999) . '.' . $ext;
            move_uploaded_file($_FILES['bukti']['tmp_name'], __DIR__ . '/assets/uploads/bukti/' . $buktiFile);
        }

        $params = [
            'tanggal' => $_POST['tanggal'],
            'kategori_id' => $_POST['kategori_id'],
            'akun_id' => $_POST['akun_id'],
            'jumlah' => (float)str_replace('.', '', $_POST['jumlah']),
            'keterangan' => trim($_POST['keterangan']),
        ];

        if ($id) {
            $params['id'] = $id;
            $sql = "UPDATE transaksi SET tanggal=:tanggal, kategori_id=:kategori_id, akun_id=:akun_id, jumlah=:jumlah, keterangan=:keterangan";
            if ($buktiFile) $sql .= ", bukti_file=:bukti";
            $sql .= " WHERE id=:id AND tipe='pengeluaran'";
            if ($buktiFile) $params['bukti'] = $buktiFile;
            $pdo->prepare($sql)->execute($params);
            flash('success', 'Transaksi pengeluaran berhasil diperbarui.');
        } else {
            $params['no'] = generateNoTransaksi($pdo, 'pengeluaran');
            $params['bukti'] = $buktiFile;
            $params['uid'] = currentUser()['id'];
            $pdo->prepare("INSERT INTO transaksi (no_transaksi, tanggal, tipe, kategori_id, akun_id, jumlah, keterangan, bukti_file, created_by)
                           VALUES (:no, :tanggal, 'pengeluaran', :kategori_id, :akun_id, :jumlah, :keterangan, :bukti, :uid)")->execute($params);
            flash('success', 'Transaksi pengeluaran berhasil ditambahkan.');
        }
    } elseif ($action === 'delete') {
        $pdo->prepare("DELETE FROM transaksi WHERE id=:id AND tipe='pengeluaran'")->execute(['id'=>$_POST['id']]);
        flash('success', 'Transaksi berhasil dihapus.');
    }
    header('Location: transaksi_pengeluaran.php');
    exit;
}

$bulan = $_GET['bulan'] ?? date('m');
$tahun = $_GET['tahun'] ?? date('Y');

$stmt = $pdo->prepare("
    SELECT t.*, k.nama as kategori_nama, a.nama_akun
    FROM transaksi t JOIN kategori k ON k.id=t.kategori_id JOIN akun_kas a ON a.id=t.akun_id
    WHERE t.tipe='pengeluaran' AND k.kelompok='umum' AND MONTH(t.tanggal)=:b AND YEAR(t.tanggal)=:t
    ORDER BY t.tanggal DESC, t.id DESC
");
$stmt->execute(['b'=>$bulan,'t'=>$tahun]);
$data = $stmt->fetchAll();
$total = array_sum(array_column($data, 'jumlah'));

$kategoriList = $pdo->query("SELECT * FROM kategori WHERE tipe='pengeluaran' AND kelompok='umum' AND status='aktif' ORDER BY nama")->fetchAll();
$akunList = $pdo->query("SELECT * FROM akun_kas WHERE status='aktif' ORDER BY nama_akun")->fetchAll();

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

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">Transaksi Pengeluaran</h5>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalTx" onclick="resetForm()"><i class="bi bi-plus-lg"></i> Tambah Pengeluaran</button>
</div>

<form method="GET" class="row g-2 mb-3">
    <div class="col-md-2">
        <select name="bulan" class="form-select">
            <?php for ($i=1;$i<=12;$i++): ?><option value="<?= $i ?>" <?= $i==$bulan?'selected':'' ?>><?= namaBulan($i) ?></option><?php endfor; ?>
        </select>
    </div>
    <div class="col-md-2"><input type="number" name="tahun" value="<?= htmlspecialchars($tahun) ?>" class="form-control"></div>
    <div class="col-md-2"><button class="btn btn-outline-primary w-100"><i class="bi bi-funnel"></i> Filter</button></div>
</form>

<div class="card">
    <div class="card-header d-flex justify-content-between">
        <span>Daftar Pengeluaran - <?= namaBulan($bulan) ?> <?= $tahun ?></span>
        <span class="text-danger fw-bold">Total: <?= rupiah($total) ?></span>
    </div>
    <div class="card-body">
        <table class="table table-hover datatable w-100">
            <thead><tr><th>No. Transaksi</th><th>Tanggal</th><th>Kategori</th><th>Akun</th><th>Jumlah</th><th>Keterangan</th><th>Bukti</th><th>Aksi</th></tr></thead>
            <tbody>
            <?php foreach ($data as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['no_transaksi']) ?></td>
                    <td><?= tanggalIndo($row['tanggal']) ?></td>
                    <td><?= htmlspecialchars($row['kategori_nama']) ?></td>
                    <td><?= htmlspecialchars($row['nama_akun']) ?></td>
                    <td class="text-danger fw-semibold"><?= rupiah($row['jumlah']) ?></td>
                    <td><?= htmlspecialchars($row['keterangan']) ?></td>
                    <td><?php if ($row['bukti_file']): ?><a href="assets/uploads/bukti/<?= htmlspecialchars($row['bukti_file']) ?>" target="_blank"><i class="bi bi-paperclip"></i></a><?php endif; ?></td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick='editRow(<?= htmlspecialchars(json_encode($row), ENT_QUOTES) ?>)'><i class="bi bi-pencil"></i></button>
                        <form method="POST" class="d-inline" onsubmit="return confirmDelete()">
                            <input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= $row['id'] ?>">
                            <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="modalTx" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" enctype="multipart/form-data" class="modal-content">
            <div class="modal-header"><h5 class="modal-title" id="modalTitle">Tambah Pengeluaran</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" value="save"><input type="hidden" name="id" id="f_id">
                <div class="mb-3"><label class="form-label">Tanggal</label><input type="date" name="tanggal" id="f_tanggal" class="form-control" required></div>
                <div class="mb-3">
                    <label class="form-label">Kategori</label>
                    <select name="kategori_id" id="f_kategori" class="form-select" required>
                        <?php foreach ($kategoriList as $k): ?><option value="<?= $k['id'] ?>"><?= htmlspecialchars($k['nama']) ?></option><?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Akun Sumber</label>
                    <select name="akun_id" id="f_akun" class="form-select" required>
                        <?php foreach ($akunList as $a): ?><option value="<?= $a['id'] ?>"><?= htmlspecialchars($a['nama_akun']) ?></option><?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3"><label class="form-label">Jumlah</label><input type="text" name="jumlah" id="f_jumlah" class="form-control" oninput="formatRupiahInput(this)" required></div>
                <div class="mb-3"><label class="form-label">Keterangan</label><textarea name="keterangan" id="f_keterangan" class="form-control" rows="2"></textarea></div>
                <div class="mb-3"><label class="form-label">Bukti (opsional)</label><input type="file" name="bukti" class="form-control"></div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button><button class="btn btn-primary">Simpan</button></div>
        </form>
    </div>
</div>

<script>
function resetForm() {
    document.getElementById('modalTitle').innerText = 'Tambah Pengeluaran';
    document.getElementById('f_id').value = '';
    document.getElementById('f_tanggal').value = new Date().toISOString().split('T')[0];
    document.getElementById('f_jumlah').value = '';
    document.getElementById('f_keterangan').value = '';
}
function editRow(row) {
    document.getElementById('modalTitle').innerText = 'Edit Pengeluaran';
    document.getElementById('f_id').value = row.id;
    document.getElementById('f_tanggal').value = row.tanggal;
    document.getElementById('f_kategori').value = row.kategori_id;
    document.getElementById('f_akun').value = row.akun_id;
    document.getElementById('f_jumlah').value = new Intl.NumberFormat('id-ID').format(row.jumlah);
    document.getElementById('f_keterangan').value = row.keterangan;
    new bootstrap.Modal(document.getElementById('modalTx')).show();
}
</script>

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