<?php
include 'koneksi.php';

$tahun = isset($_POST['tahun_filter']) ? $_POST['tahun_filter'] : date('Y');
$bulan = isset($_POST['bulan_filter']) ? $_POST['bulan_filter'] : date('m');
$search_nama_anggota = isset($_POST['search_nama_anggota']) ? $_POST['search_nama_anggota'] : '';

$query_anggota = "SELECT * FROM anggota";
if (!empty($search_nama_anggota)) {
    $query_anggota .= " WHERE nama_anggota LIKE '%" . mysqli_real_escape_string($conn, $search_nama_anggota) . "%'";
}
$result_anggota = mysqli_query($conn, $query_anggota);
if (!$result_anggota) {
    die("Query Error: " . mysqli_error($conn));
}

if (isset($_POST['submit_iuran'])) {
    $id_anggota = $_POST['id_anggota'];
    $tanggal_iuran = $_POST['tanggal_iuran'];
    $jumlah_iuran = 5000;
    $current_tahun = $_POST['current_tahun'];
    $current_bulan = $_POST['current_bulan'];
    $current_search = $_POST['current_search'];

    $query_check = "SELECT * FROM iuran WHERE id_anggota = '$id_anggota' AND YEAR(tanggal_iuran) = '$current_tahun' AND MONTH(tanggal_iuran) = '$current_bulan'";
    $result_check = mysqli_query($conn, $query_check);

    if (mysqli_num_rows($result_check) > 0) {
        echo "<script>alert('Iuran sudah dibayar untuk bulan ini.');</script>";
    } else {
        $query_insert = "INSERT INTO iuran (id_anggota, tanggal_iuran, nominal, date_created) 
                         VALUES ('$id_anggota', '$tanggal_iuran', '$jumlah_iuran', NOW())";
        if (mysqli_query($conn, $query_insert)) {
            echo "<form id='redirectForm' method='POST' action='iuran_bulanan'>
                    <input type='hidden' name='bulan_filter' value='$current_bulan'>
                    <input type='hidden' name='tahun_filter' value='$current_tahun'>
                    <input type='hidden' name='search_nama_anggota' value='$current_search'>
                  </form>
                  <script>
                    alert('Iuran berhasil disimpan!');
                    document.getElementById('redirectForm').submit();
                  </script>";
        } else {
            echo "<script>alert('Gagal menyimpan iuran. Error: " . mysqli_error($conn) . "');</script>";
        }
    }
}

if (isset($_POST['batal_iuran'])) {
    $id_iuran = $_POST['id_iuran'];
    $current_tahun = $_POST['current_tahun'];
    $current_bulan = $_POST['current_bulan'];
    $current_search = $_POST['current_search'];

    $query_delete = "DELETE FROM iuran WHERE id_iuran = '$id_iuran'";
    if (mysqli_query($conn, $query_delete)) {
        echo "<form id='redirectForm' method='POST' action='iuran_bulanan'>
                <input type='hidden' name='bulan_filter' value='$current_bulan'>
                <input type='hidden' name='tahun_filter' value='$current_tahun'>
                <input type='hidden' name='search_nama_anggota' value='$current_search'>
              </form>
              <script>
                alert('Iuran berhasil dibatalkan!');
                document.getElementById('redirectForm').submit();
              </script>";
    } else {
        echo "<script>alert('Gagal membatalkan iuran. Error: " . mysqli_error($conn) . "');</script>";
    }
}
?>

<main class="main-content position-relative border-radius-lg">
    <div class="container-fluid py-4">
        <div class="header-section mb-4">
            <h5 class="page-title text-white mb-3">Data Iuran Bulanan</h5>
        </div>

        <div class="row mb-4">
            <div class="col-md-6">
                <form method="POST" class="row g-2 align-items-end">
                    <div class="col-md-5">
                        <label for="tahun_filter" class="form-label">Tahun</label>
                        <select name="tahun_filter" class="form-select" id="tahun_filter">
                            <?php for ($i = date('Y') - 5; $i <= date('Y'); $i++): ?>
                                <option value="<?= $i; ?>" <?= ($tahun == $i) ? 'selected' : ''; ?>><?= $i; ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="col-md-5">
                        <label for="bulan_filter" class="form-label">Bulan</label>
                        <select name="bulan_filter" class="form-select" id="bulan_filter">
                            <?php for ($i = 1; $i <= 12; $i++): ?>
                                <?php $bln_pad = str_pad($i, 2, '0', STR_PAD_LEFT); ?>
                                <option value="<?= $bln_pad ?>" <?= ($bulan == $bln_pad || $bulan == $i) ? 'selected' : ''; ?>>
                                    <?= date('F', mktime(0, 0, 0, $i, 1)); ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-info w-100 mb-0">
                            <i class="fas fa-filter"></i> Filter
                        </button>
                    </div>
                    <input type="hidden" name="search_nama_anggota" value="<?= htmlspecialchars($search_nama_anggota); ?>">
                </form>
            </div>
        </div>

        <div class="card shadow-sm rounded-4">
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-8">
                    </div>
                    <div class="col-md-4">
                        <form method="POST" class="row g-2 align-items-end">
                            <input type="hidden" name="tahun_filter" value="<?= $tahun ?>">
                            <input type="hidden" name="bulan_filter" value="<?= $bulan ?>">
                            <div class="col-9">
                                <label for="search_nama_anggota" class="form-label">Cari Nama Anggota</label>
                                <input type="text" name="search_nama_anggota" id="search_nama_anggota" class="form-control" placeholder="Nama anggota..." value="<?= htmlspecialchars($search_nama_anggota); ?>">
                            </div>
                            <div class="col-3">
                                <button type="submit" class="btn btn-primary w-100 mb-0 mt-md-3">
                                    <i class="fas fa-search"></i> Cari
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover table-bordered align-items-center mb-0">
                        <thead class="thead-light">
                            <tr>
                                <th>No</th>
                                <th>Nama Anggota</th>
                                <th>Jumlah</th>
                                <th>Tanggal Iuran</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $no = 1;
                            // Make sure $result_anggota is properly defined before this point
                            // (refer to previous solution for error handling and query setup)
                            mysqli_data_seek($result_anggota, 0); // Reset pointer
                            if (mysqli_num_rows($result_anggota) > 0):
                                while ($anggota = mysqli_fetch_assoc($result_anggota)):
                                    $id = $anggota['id_anggota'];
                                    $cek_iuran = mysqli_query($conn, "SELECT * FROM iuran WHERE id_anggota='$id' AND YEAR(tanggal_iuran)='$tahun' AND MONTH(tanggal_iuran)='$bulan'");
                                    $data_iuran = mysqli_fetch_assoc($cek_iuran);
                                    $sudah_bayar = $data_iuran ? true : false;
                            ?>
                                    <tr id="anggota<?= $anggota['id_anggota'] ?>">
                                        <td><?= $no++ ?></td>
                                        <td><?= $anggota['nama_anggota'] ?></td>
                                        <td>Rp 5.000</td>
                                        <td>
                                            <?php if ($sudah_bayar): ?>
                                                <input type="date" class="form-control" value="<?= $data_iuran['tanggal_iuran']; ?>" disabled>
                                            <?php else: ?>
                                                <input type="date" class="form-control" value="<?= "$tahun-$bulan-01" ?>" disabled>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($sudah_bayar): ?>
                                                <span class="badge bg-gradient-success">Sudah Membayar</span>
                                            <?php else: ?>
                                                <span class="badge bg-gradient-danger">Belum Membayar</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if (!$sudah_bayar): ?>
                                                <form method="POST" class="d-inline">
                                                    <input type="hidden" name="id_anggota" value="<?= $anggota['id_anggota'] ?>">
                                                    <input type="hidden" name="tanggal_iuran" value="<?= "$tahun-$bulan-01" ?>">
                                                    <input type="hidden" name="current_bulan" value="<?= $bulan ?>">
                                                    <input type="hidden" name="current_tahun" value="<?= $tahun ?>">
                                                    <input type="hidden" name="current_search" value="<?= htmlspecialchars($search_nama_anggota); ?>">
                                                    <button type="submit" name="submit_iuran" class="btn btn-success btn-sm mb-0">Bayar</button>
                                                </form>
                                            <?php else: ?>
                                                <form method="POST" class="d-inline batal-form">
                                                    <input type="hidden" name="id_iuran" value="<?= $data_iuran['id_iuran'] ?>">
                                                    <input type="hidden" name="current_bulan" value="<?= $bulan ?>">
                                                    <input type="hidden" name="current_tahun" value="<?= $tahun ?>">
                                                    <input type="hidden" name="current_search" value="<?= htmlspecialchars($search_nama_anggota); ?>">
                                                    <input type="hidden" class="anggota-id" value="<?= $anggota['id_anggota'] ?>">
                                                    <button type="submit" name="batal_iuran" class="btn btn-danger btn-sm mb-0 batal-btn" onclick="return confirm('Batalkan iuran ini?')">Batalkan</button>
                                                </form>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-center">Tidak ada anggota ditemukan untuk filter ini.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
    window.addEventListener('DOMContentLoaded', function() {
        const targetId = localStorage.getItem('scrollToAnggota');
        if (targetId) {
            const row = document.getElementById('anggota' + targetId);
            if (row) {
                row.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center'
                });
                row.style.backgroundColor = '#e6f7ff';
                setTimeout(() => row.style.backgroundColor = '', 2000);
            }
            localStorage.removeItem('scrollToAnggota');
        }

        document.querySelectorAll('form button[name="submit_iuran"]').forEach(button => {
            button.addEventListener('click', function() {
                const inputId = this.closest('form').querySelector('input[name="id_anggota"]');
                if (inputId) localStorage.setItem('scrollToAnggota', inputId.value);
            });
        });

        document.querySelectorAll('form button[name="batal_iuran"]').forEach(button => {
            button.addEventListener('click', function() {
                const inputId = this.closest('form').querySelector('input.anggota-id');
                if (inputId) localStorage.setItem('scrollToAnggota', inputId.value);
            });
        });
    });
</script>