<?php
include 'koneksi.php';

$search_query = "";
if (isset($_POST['search'])) {
    $search_query = mysqli_real_escape_string($conn, $_POST['search']);
}

$query = "SELECT p.id_pinjaman, p.id_anggota, p.tanggal_pinjam, p.nominal, p.jumlah_bunga, p.status, a.nama_anggota 
          FROM pinjaman p
          JOIN anggota a ON p.id_anggota = a.id_anggota
          WHERE a.nama_anggota LIKE '%$search_query%' OR p.id_pinjaman LIKE '%$search_query%' 
          ORDER BY p.tanggal_pinjam DESC";

$result = mysqli_query($conn, $query);

// Tambah
if (isset($_POST['submit'])) {
    $id_anggota = $_POST['id_anggota'];
    $tanggal_pinjam = $_POST['tanggal_pinjam'];
    $nominal = $_POST['nominal'];
    $jumlah_bunga = $_POST['jumlah_bunga'];
    $status = $_POST['status'];

    if (empty($id_anggota) || empty($tanggal_pinjam) || empty($nominal) || empty($jumlah_bunga)) {
        echo "<script>alert('Semua kolom harus diisi.');</script>";
    } else {
        $query_insert = "INSERT INTO pinjaman (id_anggota, tanggal_pinjam, nominal, jumlah_bunga, status) 
                         VALUES ('$id_anggota', '$tanggal_pinjam', '$nominal', '$jumlah_bunga', '$status')";
        if (mysqli_query($conn, $query_insert)) {
            echo "<script>alert('Pinjaman berhasil ditambahkan!'); window.location='?pages=pinjaman';</script>";
        } else {
            echo "<script>alert('Gagal menambahkan pinjaman. Error: " . mysqli_error($conn) . "');</script>";
        }
    }
}

// Edit
if (isset($_POST['update'])) {
    $id_pinjaman = $_POST['id_pinjaman'];
    $id_anggota = $_POST['id_anggota'];
    $tanggal_pinjam = $_POST['tanggal_pinjam'];
    $nominal = $_POST['nominal'];
    $jumlah_bunga = $_POST['jumlah_bunga'];
    $status = $_POST['status'];

    $query_update = "UPDATE pinjaman 
                     SET id_anggota='$id_anggota', tanggal_pinjam='$tanggal_pinjam', nominal='$nominal', jumlah_bunga='$jumlah_bunga', status='$status' 
                     WHERE id_pinjaman='$id_pinjaman'";
    if (mysqli_query($conn, $query_update)) {
        echo "<script>alert('Pinjaman berhasil diperbarui!'); window.location='?pages=pinjaman';</script>";
    } else {
        echo "<script>alert('Gagal memperbarui pinjaman. Error: " . mysqli_error($conn) . "');</script>";
    }
}

// Pembayaran bunga
if (isset($_POST['bayar_bunga'])) {
    $id_pinjaman = $_POST['id_pinjaman_bayar'];
    $nominal_bayar = $_POST['nominal_bayar'];

    $query_anggota = mysqli_query($conn, "SELECT id_anggota FROM pinjaman WHERE id_pinjaman = '$id_pinjaman'");
    $data_anggota = mysqli_fetch_assoc($query_anggota);
    $id_anggota = $data_anggota['id_anggota'];

    if (!is_numeric($nominal_bayar) || $nominal_bayar <= 0) {
        echo "<script>alert('Nominal pembayaran tidak valid.');</script>";
    } else {
        $query_bayar = "INSERT INTO bunga (id_anggota, nominal, tanggal_bayar) VALUES ('$id_anggota', '$nominal_bayar', NOW())";
        if (mysqli_query($conn, $query_bayar)) {
            echo "<script>alert('Pembayaran bunga berhasil!'); window.location='?pages=pinjaman';</script>";
        } else {
            echo "<script>alert('Gagal menyimpan pembayaran bunga.');</script>";
        }
    }
}
?>

<main class="main-content position-relative border-radius-lg ">
    <div class="container-fluid py-4">
        <div class="header-section">
            <h5 class="page-title">
                <span class="text-white">Pinjaman</span>
            </h5>
            <div> <button class="btn btn-success-custom" data-bs-toggle="modal" data-bs-target="#addPinjamanModal">
                    <i class="mdi mdi-plus-circle"></i> Tambah Pinjaman
                </button>
            </div>
        </div>
        <div class="card shadow-sm rounded-4">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="DataTable" class="table table-hover table-bordered">
                        <thead>
                            <tr>
                                <th>Anggota</th>
                                <th>Tanggal Pinjaman</th>
                                <th>Nominal</th>
                                <th>Jumlah Bunga</th>
                                <th>Status</th>
                                <th>Tempo Pinjaman</th>
                                <th class="aksi">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i = 1;
                            while ($row = mysqli_fetch_assoc($result)): ?>
                                <tr>
                                    <td><?php echo $row['nama_anggota']; ?></td>
                                    <td><?php echo date('d-m-Y', strtotime($row['tanggal_pinjam'])); ?></td>
                                    <td>Rp <?php echo number_format($row['nominal'], 0, ',', '.'); ?></td>
                                    <td>Rp <?php echo number_format($row['jumlah_bunga'], 0, ',', '.'); ?></td>
                                    <td>
                                        <?php
                                        if ($row['status'] == 'Belum Lunas') {
                                            echo '<span class="badge bg-danger">Belum Lunas</span>';  // Warna merah untuk Belum Lunas
                                        } else {
                                            echo '<span class="badge bg-success">Lunas</span>';  // Warna hijau untuk Lunas
                                        }
                                        ?>
                                    </td>

                                    <td><?php echo date('d-m-Y', strtotime("+6 months", strtotime($row['tanggal_pinjam']))); ?></td> <!-- Tempo Pinjaman -->
                                    <td>
                                        <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editPinjamanModal<?= $row['id_pinjaman'] ?>">Edit</button>
                                        <?php if ($row['status'] !== 'Lunas'): ?>
                                            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#bayarBungaModal<?= $row['id_pinjaman'] ?>">Bayar Bunga</button>
                                        <?php endif; ?>
                                    </td>

                                </tr>
                            <?php endwhile; ?>
                        </tbody>


                        <?php
                        mysqli_data_seek($result, 0); // Reset pointer hasil query
                        while ($row = mysqli_fetch_assoc($result)):
                        ?>
                            <div class="modal fade" id="bayarBungaModal<?php echo $row['id_pinjaman']; ?>" tabindex="-1" aria-labelledby="bayarBungaModalLabel<?php echo $row['id_pinjaman']; ?>" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form method="POST" action="">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="bayarBungaModalLabel<?php echo $row['id_pinjaman']; ?>">Bayar Bunga - ID <?php echo $row['id_pinjaman']; ?></h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">
                                                <input type="hidden" name="id_pinjaman_bayar" value="<?php echo $row['id_pinjaman']; ?>">
                                                <div class="mb-3">
                                                    <label for="nominal_bayar" class="form-label">Nominal Pembayaran Bunga</label>
                                                    <input type="number" class="form-control" name="nominal_bayar" required value="<?php echo $row['jumlah_bunga']; ?>">
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="submit" name="bayar_bunga" class="btn btn-success">Bayar</button>
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <!-- Modal Edit Pinjaman -->
                            <div class="modal fade" id="editPinjamanModal<?= $row['id_pinjaman'] ?>" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form method="POST">
                                            <div class="modal-header">
                                                <h5 class="modal-title">Edit Pinjaman - ID <?= $row['id_pinjaman'] ?></h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">
                                                <input type="hidden" name="id_pinjaman" value="<?= $row['id_pinjaman'] ?>">
                                                <div class="mb-3">
                                                    <label>Anggota</label>
                                                    <select class="form-select" name="id_anggota" required>
                                                        <?php
                                                        $anggota_result = mysqli_query($conn, "SELECT * FROM anggota");
                                                        while ($anggota = mysqli_fetch_assoc($anggota_result)): ?>
                                                            <option value="<?= $anggota['id_anggota'] ?>" <?= $anggota['id_anggota'] == $row['id_anggota'] ? 'selected' : '' ?>>
                                                                <?= $anggota['nama_anggota'] ?>
                                                            </option>
                                                        <?php endwhile; ?>
                                                    </select>
                                                </div>
                                                <div class="mb-3">
                                                    <label>Tanggal</label>
                                                    <input type="date" class="form-control" name="tanggal_pinjam" required value="<?= $row['tanggal_pinjam'] ?>">
                                                </div>
                                                <div class="mb-3">
                                                    <label>Nominal</label>
                                                    <input type="number" class="form-control" name="nominal" required value="<?= $row['nominal'] ?>">
                                                </div>
                                                <div class="mb-3">
                                                    <label>Bunga</label>
                                                    <input type="number" class="form-control" name="jumlah_bunga" required value="<?= $row['jumlah_bunga'] ?>">
                                                </div>
                                                <div class="mb-3">
                                                    <label>Status</label>
                                                    <select class="form-select" name="status">
                                                        <option value="Belum Lunas" <?= $row['status'] == 'Belum Lunas' ? 'selected' : '' ?>>Belum Lunas</option>
                                                        <option value="Lunas" <?= $row['status'] == 'Lunas' ? 'selected' : '' ?>>Lunas</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="submit" name="update" class="btn btn-primary">Simpan Perubahan</button>
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>

                            <!-- Modal Tambah Pinjaman -->
                            <div class="modal fade" id="addPinjamanModal" tabindex="-1" aria-labelledby="addPinjamanModalLabel" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form method="POST">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="addPinjamanModalLabel">Tambah Pinjaman</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">
                                                <div class="mb-3">
                                                    <label for="id_anggota" class="form-label">Anggota</label>
                                                    <select class="form-select" name="id_anggota" required>
                                                        <?php
                                                        $anggota_result = mysqli_query($conn, "SELECT * FROM anggota");
                                                        while ($anggota = mysqli_fetch_assoc($anggota_result)): ?>
                                                            <option value="<?= $anggota['id_anggota'] ?>"><?= $anggota['nama_anggota'] ?></option>
                                                        <?php endwhile; ?>
                                                    </select>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="tanggal_pinjam" class="form-label">Tanggal Pinjam</label>
                                                    <input type="date" class="form-control" name="tanggal_pinjam" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="nominal" class="form-label">Nominal</label>
                                                    <input type="number" class="form-control" name="nominal" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="jumlah_bunga" class="form-label">Jumlah Bunga</label>
                                                    <input type="number" class="form-control" name="jumlah_bunga" required>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="status" class="form-label">Status</label>
                                                    <select class="form-select" name="status" required>
                                                        <option value="Belum Lunas">Belum Lunas</option>
                                                        <option value="Lunas">Lunas</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="submit" name="submit" class="btn btn-success">Simpan</button>
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>

                        <?php endwhile; ?>
                    </table>
                </div>
            </div>
        </div>
</main>