<?php
include 'koneksi.php';
include 'auth.php';         // Mengecek login
include 'akses_ditolak.php'; // Tambahkan ini


$filter_nama = isset($_GET['nama']) ? $_GET['nama'] : '';
$filter_periode = isset($_GET['periode']) ? $_GET['periode'] : date('Y-m'); // Default: bulan ini

// Query total tabungan sukarela (per bulan yg dipilih)
$totalSukarelaQuery = "SELECT SUM(tabungan_sukarela) AS total_sukarela FROM tabungan WHERE DATE_FORMAT(created_at, '%Y-%m') = '$filter_periode'";
$totalSukarelaResult = mysqli_query($koneksi, $totalSukarelaQuery);
$totalSukarela = mysqli_fetch_assoc($totalSukarelaResult)['total_sukarela'] ?? 0;

// Query utama
$query = "SELECT nama, no_handphone, SUM(tabungan_sukarela) AS total_sukarela 
          FROM tabungan 
          WHERE DATE_FORMAT(created_at, '%Y-%m') = '$filter_periode'";

if (!empty($filter_nama)) {
    $safe_nama = mysqli_real_escape_string($koneksi, $filter_nama);
    $query .= " AND nama LIKE '%$safe_nama%'";
}

$query .= " GROUP BY no_handphone ORDER BY nama ASC";

// Eksekusi query & error handling
$result = mysqli_query($koneksi, $query);
if (!$result) {
    die("Query Error: " . mysqli_error($koneksi));
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tabungan Sukarela</title>
    <link rel="stylesheet" href="css/navbar.css">
    <link rel="stylesheet" href="css/tabungan.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />
</head>
<style>
        thead th {
      position: sticky;
      top: 0;
      background-color: #333;
      color: #f5d216;
      z-index: 1;
    }
            td {
            padding-left:10px;
            padding:5px;
            border: 1px solid #333;
            text-align: left;
        }
</style>
<body>
    <div class="container">
        <h4>RINCIAN TABUNGAN SUKARELA</h4>

        <!-- Filter Nama & Periode -->
        <form method="GET" style="margin-bottom: 10px; display: flex; flex-wrap: wrap; gap: 10px;">
            <input type="text" id="searchNama" name="nama" placeholder="Cari nama..."
                value="<?= htmlspecialchars($filter_nama) ?>"
                style="flex: 1; padding: 8px 12px; border-radius: 6px; border: 1px solid #ccc;">
            <button type="submit"
                style="padding: 8px 16px; background-color: #f0ad00; border: none; border-radius: 6px; font-weight: bold;">
                Filter</button>
            <input type="month" name="periode" value="<?= $filter_periode ?>"
                style="width:100%; padding: 8px 12px; border-radius: 6px; border: 1px solid #ccc;">

        </form>

        <!-- Total -->
        <form method="POST">
            <div class="input-button-group">
                <div class="input-wrapper">
                    <i class="fas fa-money-bill input-icon"></i>
                    <input  style="pointer-events: none;" type="text" value="Rp <?= number_format($totalSukarela, 0, ',', '.') ?>" readonly>
                </div>
                <button type="button" class="action-btn" onclick="window.location.href='rincian_tabungan_wajib.php';">➥
                    Wajib</button>
            </div>
        </form>
    </div>

    <!-- Tabel -->
    <div class="table-container" style="max-height: 50vh; min-height: 50vh;">
        <table>
            <thead>
                <tr>
                    <th>Nama</th>
                    <th>Total Tabungan</th>
                </tr>
            </thead>
            <tbody id="tabelBody">
                <?php if (mysqli_num_rows($result) > 0): ?>
                    <?php while ($row = mysqli_fetch_assoc($result)): ?>
                        <tr>
                            <td>
                                <a
                                    onclick="toggleRincian('<?= $row['no_handphone'] ?>', '<?= htmlspecialchars($row['nama'], ENT_QUOTES) ?>')">
                                    <?= htmlspecialchars($row['nama']) ?>
                                </a>
                            </td>
                            <td>Rp <?= number_format($row['total_sukarela'], 0, ',', '.') ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="2" style="text-align: center; color: red;">Nama tidak ditemukan</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <p style="text-align:center ; color: gray;">Klik Nama Member untuk detail Rincian</p>
    <?php include 'navbar4.php'; ?>
</body>

</html>

<script>
    function toggleRincian(no_hp, nama) {
        $.ajax({
            url: 'rincian_tabungan2.php',
            type: 'GET',
            data: { no_hp: no_hp },
            success: function (data) {
                Swal.fire({
                    title: nama,
                    html: data,
                    width: '120%',
                    customClass: {
                        popup: 'rincian-popup'
                    },
                    showConfirmButton: true,
                    confirmButtonColor: '#FFD700'
                });
            },
            error: function () {
                Swal.fire('Error', 'Gagal mengambil data rincian.', 'error');
            }
        });
    }

    function toggleRincian(no_hp, nama) {
        $.ajax({
            url: 'rincian_tabungan2.php',
            type: 'GET',
            data: { no_hp: no_hp },
            success: function (data) {
                Swal.fire({
                    title: nama,
                    html: data,
                    width: '120%',
                    customClass: {
                        popup: 'rincian-popup'
                    },
                    showConfirmButton: true,
                    confirmButtonColor: '#FFD700'
                });
            },
            error: function () {
                Swal.fire('Error', 'Gagal mengambil data rincian.', 'error');
            }
        });
    }

    // 🔍 Live Search
    $(document).ready(function () {
        $('#searchNama').on('input', function () {
            const nama = $(this).val();
            const periode = $('input[name="periode"]').val(); // Ambil juga periode yang dipilih

            $.get('rincian_tabungan_sukarela_ajax.php', { nama: nama, periode: periode }, function (data) {
                $('#tabelBody').html(data); // Ganti isi tabel
            });
        });
    });

</script>