<?php
  // rekap.php - UPDATED WITH CLEANED CSS
  if (session_status() == PHP_SESSION_NONE) {
      session_start();
  }
  include_once __DIR__ . '/../koneksi.php'; 

  if (!isset($alamat_admin)) {
      $current_dir_url_path = dirname($_SERVER['SCRIPT_NAME']);
      $alamat_admin = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . $current_dir_url_path . '/';
  }

  if (!isset($_SESSION['kode_admin'])) {
    echo '<script>alert("Terjadi kesalahan, harap masuk kembali!"); window.location.replace("'.rtrim($alamat_admin, '/').'/keluar.php");</script>';
    exit();
  }

  function getRekapTransaksiAnggota($koneksi) {
    $rekap_data = [];
    $sql_anggota = "SELECT id_anggota, nama_pengguna_anggota FROM anggota ORDER BY nama_pengguna_anggota ASC";
    $query_anggota = mysqli_query($koneksi, $sql_anggota);

    if (!$query_anggota) {
        error_log("Rekap Transaksi Admin: Gagal query data anggota: " . mysqli_error($koneksi));
        return $rekap_data;
    }

    while ($row_anggota = mysqli_fetch_assoc($query_anggota)) {
        $id_anggota = $row_anggota['id_anggota'];
        $nama_pengguna = $row_anggota['nama_pengguna_anggota'];
        $total_deposit_disetujui = 0;
        $total_withdraw_disetujui = 0;

        $sql_deposit = "SELECT SUM(CAST(REPLACE(jumlah_deposit, ',', '') AS DECIMAL(15,2))) AS total_depo 
                        FROM deposit 
                        WHERE id_anggota_deposit = ? AND status_deposit = 'disetujui'";
        $stmt_deposit = $koneksi->prepare($sql_deposit);
        if ($stmt_deposit) {
            $stmt_deposit->bind_param("i", $id_anggota);
            $stmt_deposit->execute();
            $result_deposit = $stmt_deposit->get_result();
            if ($data_depo = $result_deposit->fetch_assoc()) {
                $total_deposit_disetujui = (float)($data_depo['total_depo'] ?? 0);
            }
            $stmt_deposit->close();
        }
            
        $sql_withdraw = "SELECT SUM(CAST(REPLACE(jumlah_withdraw, ',', '') AS DECIMAL(15,2))) AS total_wd 
                         FROM withdraw 
                         WHERE id_anggota_withdraw = ? AND status_withdraw = 'disetujui'";
        $stmt_withdraw = $koneksi->prepare($sql_withdraw);
        if ($stmt_withdraw) {
            $stmt_withdraw->bind_param("i", $id_anggota);
            $stmt_withdraw->execute();
            $result_withdraw = $stmt_withdraw->get_result();
            if ($data_wd = $result_withdraw->fetch_assoc()) {
                $total_withdraw_disetujui = (float)($data_wd['total_wd'] ?? 0);
            }
            $stmt_withdraw->close();
        }
            
        $rekap_data[] = [
            'id_anggota' => $id_anggota,
            'nama_pengguna' => $nama_pengguna,
            'total_deposit_disetujui' => $total_deposit_disetujui,
            'total_withdraw_disetujui' => $total_withdraw_disetujui,
        ];
    }
    mysqli_free_result($query_anggota);
    return $rekap_data;
  }

  $data_rekap_transaksi = getRekapTransaksiAnggota($koneksi);

  $pesan_notifikasi = '';
  $tipe_notifikasi = 'info'; 
  if (isset($_SESSION['pesan_rekap_admin'])) { 
      $pesan_notifikasi = $_SESSION['pesan_rekap_admin']['teks'];
      $tipe_notifikasi = $_SESSION['pesan_rekap_admin']['tipe'];
      unset($_SESSION['pesan_rekap_admin']); 
  }
?>

<!-- FORCE LOAD JQUERY & DATATABLES -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>

<style>
/* ===== CUSTOM DATATABLES STYLING ===== */

/* Wrapper Controls - Top Bar */
#tabelRekapTransaksi_wrapper .dataTables_length,
#tabelRekapTransaksi_wrapper .dataTables_filter {
    margin-bottom: 20px;
}

#tabelRekapTransaksi_wrapper .dataTables_length {
    float: left;
}

#tabelRekapTransaksi_wrapper .dataTables_filter {
    float: right;
}

#tabelRekapTransaksi_wrapper .dataTables_length label,
#tabelRekapTransaksi_wrapper .dataTables_filter label {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 0;
    font-weight: 500;
    color: #b4b7bd;
}

/* Select Dropdown (Show entries) */
#tabelRekapTransaksi_wrapper .dataTables_length select {
    background-color: #2f3349;
    border: 1px solid #444564;
    border-radius: 6px;
    padding: 8px 35px 8px 12px;
    color: #b4b7bd;
    font-size: 14px;
    outline: none;
    cursor: pointer;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23b4b7bd' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 10px center;
    appearance: none;
}

#tabelRekapTransaksi_wrapper .dataTables_length select:hover {
    border-color: #696cff;
}

#tabelRekapTransaksi_wrapper .dataTables_length select:focus {
    border-color: #696cff;
    box-shadow: 0 0 0 3px rgba(105, 108, 255, 0.1);
}

/* Search Input */
#tabelRekapTransaksi_wrapper .dataTables_filter input {
    background-color: #2f3349;
    border: 1px solid #444564;
    border-radius: 6px;
    padding: 8px 15px 8px 35px;
    color: #b4b7bd;
    font-size: 14px;
    width: 280px;
    outline: none;
    transition: all 0.3s ease;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23b4b7bd' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cpath d='m21 21-4.35-4.35'%3E%3C/path%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: 10px center;
}

#tabelRekapTransaksi_wrapper .dataTables_filter input:hover {
    border-color: #696cff;
}

#tabelRekapTransaksi_wrapper .dataTables_filter input:focus {
    border-color: #696cff;
    box-shadow: 0 0 0 3px rgba(105, 108, 255, 0.1);
    background-color: #383b52;
}

#tabelRekapTransaksi_wrapper .dataTables_filter input::placeholder {
    color: #6c7293;
}

/* Bottom Info & Pagination */
#tabelRekapTransaksi_wrapper .dataTables_info {
    padding-top: 15px;
    color: #b4b7bd;
    font-size: 14px;
}

#tabelRekapTransaksi_wrapper .dataTables_paginate {
    padding-top: 15px;
    text-align: right;
}

/* Pagination Buttons */
#tabelRekapTransaksi_wrapper .dataTables_paginate .paginate_button {
    display: inline-block;
    padding: 8px 14px;
    margin: 0 3px;
    border: 1px solid #444564;
    border-radius: 6px;
    background-color: #2f3349;
    color: #b4b7bd !important;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 14px;
    text-decoration: none;
}

#tabelRekapTransaksi_wrapper .dataTables_paginate .paginate_button:hover {
    background-color: #383b52;
    border-color: #696cff;
    color: #fff !important;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(105, 108, 255, 0.2);
}

#tabelRekapTransaksi_wrapper .dataTables_paginate .paginate_button.current {
    background: linear-gradient(135deg, #696cff 0%, #5a5ddb 100%) !important;
    border-color: #696cff !important;
    color: #fff !important;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(105, 108, 255, 0.4);
}

#tabelRekapTransaksi_wrapper .dataTables_paginate .paginate_button.current:hover {
    background: linear-gradient(135deg, #5a5ddb 0%, #4b4ec7 100%) !important;
    transform: translateY(-1px);
}

#tabelRekapTransaksi_wrapper .dataTables_paginate .paginate_button.disabled,
#tabelRekapTransaksi_wrapper .dataTables_paginate .paginate_button.disabled:hover {
    opacity: 0.4;
    cursor: not-allowed;
    background-color: #2f3349;
    border-color: #444564;
    color: #6c7293 !important;
    transform: none;
    box-shadow: none;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    #tabelRekapTransaksi_wrapper .dataTables_length,
    #tabelRekapTransaksi_wrapper .dataTables_filter {
        float: none;
        text-align: center;
        margin-bottom: 15px;
    }
    
    #tabelRekapTransaksi_wrapper .dataTables_filter input {
        width: 100%;
    }
    
    #tabelRekapTransaksi_wrapper .dataTables_info,
    #tabelRekapTransaksi_wrapper .dataTables_paginate {
        text-align: center;
    }
    
    #tabelRekapTransaksi_wrapper .dataTables_paginate .paginate_button {
        padding: 6px 10px;
        font-size: 12px;
        margin: 2px;
    }
}

/* Clear floats */
#tabelRekapTransaksi_wrapper .row::after {
    content: "";
    display: table;
    clear: both;
}
</style>

<div class="container-xxl flex-grow-1 container-p-y">
  <h4 class="py-3 mb-4">
    <span class="text-muted fw-light">Menu Utama /</span> Rekapitulasi Transaksi Anggota
  </h4>

  <?php if (!empty($pesan_notifikasi)): ?>
    <div class="alert alert-<?php echo htmlspecialchars($tipe_notifikasi); ?> alert-dismissible fade show" role="alert">
      <?php echo htmlspecialchars($pesan_notifikasi); ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  <?php endif; ?>

  <div class="row">
    <div class="col-md-12">
      <div class="card">
        <h5 class="card-header">Rekap Total Deposit & Withdraw (Disetujui)</h5>
        <div class="card-body">
          <?php if (!empty($data_rekap_transaksi)): ?>
          <div class="table-responsive text-nowrap">
            <table id="tabelRekapTransaksi" class="table table-striped table-hover" style="width: 100%;">
              <thead>
                <tr>
                  <th>No.</th>
                  <th>Nama Anggota</th>
                  <th>Total Deposit</th>
                  <th>Total Withdraw</th>
                  <th>Aksi</th>
                </tr>
              </thead>
              <tbody>
                <?php 
                $nomor = 1;
                foreach ($data_rekap_transaksi as $data): ?>
                <tr>
                  <td><?php echo $nomor++; ?></td>
                  <td><?php echo htmlspecialchars($data['nama_pengguna']); ?></td>
                  <td>Rp <?php echo number_format($data['total_deposit_disetujui'], 0, ',', '.'); ?></td>
                  <td>Rp <?php echo number_format($data['total_withdraw_disetujui'], 0, ',', '.'); ?></td>
                  <td>
                    <button type="button" class="btn btn-sm btn-primary" onclick="lihatDetail(<?php echo $data['id_anggota']; ?>, '<?php echo htmlspecialchars($data['nama_pengguna'], ENT_QUOTES); ?>')">
                      <i class="bx bx-detail"></i> Lihat Detail
                    </button>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
          <?php else: ?>
            <p class="text-center">Tidak ada data transaksi anggota untuk ditampilkan.</p>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Modal Member Statistic -->
<div class="modal fade" id="modalMemberStatistic" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Member Statistic</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="modalContent">
        <div class="text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
          <p class="mt-2">Memuat data...</p>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
// Tunggu sampai document ready dan pastikan jQuery loaded
(function() {
    function initDataTable() {
        console.log('Checking jQuery and DataTables...');
        
        if (typeof jQuery === 'undefined') {
            console.error('❌ jQuery not loaded!');
            setTimeout(initDataTable, 100);
            return;
        }
        
        if (!jQuery.fn.DataTable) {
            console.error('❌ DataTables not loaded!');
            setTimeout(initDataTable, 100);
            return;
        }
        
        console.log('✅ jQuery and DataTables loaded!');
        
        jQuery(document).ready(function($) {
            console.log('Initializing DataTable...');
            
            // Destroy existing DataTable if any
            if ($.fn.DataTable.isDataTable('#tabelRekapTransaksi')) {
                $('#tabelRekapTransaksi').DataTable().destroy();
            }
            
            var table = $('#tabelRekapTransaksi').DataTable({
                "language": {
                     "search": "Cari User:",
                     "searchPlaceholder": "Ketik nama anggota...",
                     "lengthMenu": "Tampilkan _MENU_ data per halaman",
                     "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ anggota",
                     "infoEmpty": "Tidak ada data anggota",
                     "infoFiltered": "(difilter dari _MAX_ total anggota)",
                     "zeroRecords": "Tidak ada anggota yang cocok",
                     "paginate": {
                         "first": "Pertama",
                         "last": "Terakhir",
                         "next": "Selanjutnya",
                         "previous": "Sebelumnya"
                     },
                     "loadingRecords": "Memuat data...",
                     "processing": "Memproses..."
                },
                "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
                "pageLength": 10,
                "order": [[1, "asc"]],
                "searching": true,
                "paging": true,
                "info": true,
                "autoWidth": false,
                "responsive": true,
                "dom": '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rt<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
                "columnDefs": [
                    { "orderable": false, "targets": 4 }
                ]
            });
            
            console.log('✅ DataTable initialized successfully!');
        });
    }
    
    initDataTable();
})();

function lihatDetail(idAnggota, namaAnggota) {
    jQuery(document).ready(function($) {
        $('#modalMemberStatistic').modal('show');
        $('#modalMemberStatistic .modal-title').text('Member Statistic - ' + namaAnggota);
        
        $('#modalContent').html(`
            <div class="text-center py-5">
              <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
              </div>
              <p class="mt-2">Memuat data...</p>
            </div>
        `);
        
        $.ajax({
            url: 'get_member_detail.php',
            method: 'POST',
            data: { id_anggota: idAnggota },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#modalContent').html(response.html);
                    
                    if ($.fn.DataTable) {
                        $('#tabelTransaksiModal').DataTable({
                            "language": {
                                 "search": "Cari:",
                                 "lengthMenu": "Tampilkan _MENU_ entri",
                                 "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ entri",
                                 "infoEmpty": "Menampilkan 0 sampai 0 dari 0 entri",
                                 "infoFiltered": "(difilter dari _MAX_ total entri)",
                                 "zeroRecords": "Tidak ada data yang cocok ditemukan",
                                 "paginate": {
                                     "first": "Pertama",
                                     "last": "Terakhir",
                                     "next": "Berikutnya",
                                     "previous": "Sebelumnya"
                                 }
                            },
                            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "Semua"]],
                            "order": [[0, "asc"]],
                            "pageLength": 10
                        });
                    }
                } else {
                    $('#modalContent').html(`
                        <div class="alert alert-danger">
                            <i class="bx bx-error-circle"></i> ${response.message || 'Gagal memuat data'}
                        </div>
                    `);
                }
            },
            error: function() {
                $('#modalContent').html(`
                    <div class="alert alert-danger">
                        <i class="bx bx-error-circle"></i> Terjadi kesalahan saat memuat data
                    </div>
                `);
            }
        });
    });
}
</script>

<?php
if (isset($koneksi) && $koneksi instanceof mysqli && $koneksi->thread_id) {
    $koneksi->close();
}
?>