<?php
include "koneksi.php";

// ===== Tambah Pengeluaran =====
if (isset($_POST['tambah'])) {
    $tanggal    = $_POST['tanggal'];
    $keterangan = $_POST['keterangan'];
    $jumlah     = (float)$_POST['jumlah'];

    $stmt = $conn->prepare("INSERT INTO tabel_pengeluaran (tanggal, keterangan, jumlah) VALUES (?,?,?)");
    $stmt->bind_param("ssd", $tanggal, $keterangan, $jumlah);

    if ($stmt->execute()) {
        echo "<script>alert('Pengeluaran berhasil ditambahkan!'); location.href='index.php?page=pengeluaran';</script>";
    } else {
        echo "Gagal tambah pengeluaran: " . $stmt->error;
    }
}

// ===== Update Pengeluaran =====
if (isset($_POST['update'])) {
    $id         = (int)$_POST['id'];
    $tanggal    = $_POST['tanggal'];
    $keterangan = $_POST['keterangan'];
    $jumlah     = (float)$_POST['jumlah'];

    $stmt = $conn->prepare("UPDATE tabel_pengeluaran SET tanggal=?, keterangan=?, jumlah=? WHERE id=?");
    $stmt->bind_param("ssdi", $tanggal, $keterangan, $jumlah, $id);

    if ($stmt->execute()) {
        echo "<script>alert('Data berhasil diupdate!'); location.href='index.php?page=pengeluaran';</script>";
    } else {
        echo "Gagal update: " . $stmt->error;
    }
}

// ===== Hapus Pengeluaran =====
if (isset($_GET['hapus'])) {
    $id = (int)$_GET['hapus'];
    $conn->query("DELETE FROM tabel_pengeluaran WHERE id=$id");
    echo "<script>alert('Data berhasil dihapus!'); location.href='index.php?page=pengeluaran';</script>";
}

// ===== Ambil Data (Pagination + Search Bulan) =====
$limit = 10;
$page  = isset($_GET['page_num']) ? (int)$_GET['page_num'] : 1;
$start = ($page - 1) * $limit;

$bulan  = $_GET['bulan'] ?? '';
$where  = "";
if ($bulan) {
    $where = "WHERE MONTH(tanggal) = " . intval($bulan);
}

$total = $conn->query("SELECT COUNT(*) as jml FROM tabel_pengeluaran $where")->fetch_assoc()['jml'];
$jmlHal = ceil($total / $limit);

$data = $conn->query("SELECT * FROM tabel_pengeluaran $where ORDER BY tanggal DESC LIMIT $start, $limit");

// Hitung jumlah total sesuai filter
$totalJumlah = $conn->query("SELECT SUM(jumlah) as jml FROM tabel_pengeluaran $where")->fetch_assoc()['jml'] ?? 0;
?>

<div class="container mt-4">
    <h3>Daftar Pengeluaran</h3>

    <!-- Form Tambah -->
    <form method="post" class="row g-3 mb-4">
        <div class="col-md-3">
            <input type="date" name="tanggal" class="form-control" required>
        </div>
        <div class="col-md-5">
            <input type="text" name="keterangan" class="form-control" placeholder="Keterangan" required>
        </div>
        <div class="col-md-2">
            <input type="number" step="0.01" name="jumlah" class="form-control" placeholder="Jumlah" required>
        </div>
        <div class="col-md-2">
            <button type="submit" name="tambah" class="btn btn-success w-100">+ Tambah</button>
        </div>
    </form>

    <!-- Filter Bulan -->
    <form method="get" class="mb-3">
        <input type="hidden" name="page" value="pengeluaran">
        <div class="row g-2">
            <div class="col-md-3">
                <select name="bulan" class="form-control" onchange="this.form.submit()">
                    <option value="">-- Semua Bulan --</option>
                    <?php for ($i=1;$i<=12;$i++): ?>
                        <option value="<?= $i ?>" <?= ($bulan==$i)?'selected':'' ?>>
                            <?= date("F", mktime(0,0,0,$i,1)) ?>
                        </option>
                    <?php endfor; ?>
                </select>
            </div>
        </div>
    </form>

    <!-- Tabel Data -->
    <table class="table table-bordered">
        <thead class="table-light">
            <tr>
                <th>No</th>
                <th>Tanggal</th>
                <th>Keterangan</th>
                <th>Jumlah</th>
                <th>Aksi</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($data->num_rows > 0): $no=$start+1; ?>
                <?php while($row=$data->fetch_assoc()): ?>
                <tr>
                    <td><?= $no++ ?></td>
                    <td><?= date('d-m-Y', strtotime($row['tanggal'])) ?></td>
                    <td><?= htmlspecialchars($row['keterangan']) ?></td>
                    <td>Rp <?= number_format($row['jumlah'],0,',','.') ?></td>
                    <td>
                        <button type="button" class="btn btn-sm btn-warning"
                            onclick="editData('<?= $row['id'] ?>','<?= $row['tanggal'] ?>','<?= htmlspecialchars($row['keterangan']) ?>','<?= $row['jumlah'] ?>')">
                            ✏️
                        </button>
                        <a href="index.php?page=pengeluaran&hapus=<?= $row['id'] ?>" onclick="return confirm('Yakin hapus?')" class="btn btn-sm btn-danger">🗑</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="5" class="text-center">Belum ada data</td></tr>
            <?php endif; ?>
        </tbody>
        <tfoot>
            <tr>
                <th colspan="3" class="text-end">Total</th>
                <th colspan="2">Rp <?= number_format($totalJumlah,0,',','.') ?></th>
            </tr>
        </tfoot>
    </table>

    <!-- Pagination -->
    <nav>
        <ul class="pagination">
            <?php for($i=1;$i<=$jmlHal;$i++): ?>
                <li class="page-item <?= ($i==$page)?'active':'' ?>">
                    <a class="page-link" href="index.php?page=pengeluaran&page_num=<?= $i ?>&bulan=<?= $bulan ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
</div>

<!-- Modal Edit -->
<div class="modal fade" id="modalEdit" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Edit Pengeluaran</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="editId">
        <div class="mb-3">
          <label>Tanggal</label>
          <input type="date" name="tanggal" id="editTanggal" class="form-control" required>
        </div>
        <div class="mb-3">
          <label>Keterangan</label>
          <input type="text" name="keterangan" id="editKeterangan" class="form-control" required>
        </div>
        <div class="mb-3">
          <label>Jumlah</label>
          <input type="number" step="0.01" name="jumlah" id="editJumlah" class="form-control" required>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="update" class="btn btn-success">Update</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function editData(id, tanggal, keterangan, jumlah) {
    document.getElementById('editId').value = id;
    document.getElementById('editTanggal').value = tanggal;
    document.getElementById('editKeterangan').value = keterangan;
    document.getElementById('editJumlah').value = jumlah;
    var modal = new bootstrap.Modal(document.getElementById('modalEdit'));
    modal.show();
}
</script>
