<?php

// Sertakan file koneksi

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

include 'koneksi.php';
if (!isset($_SESSION['admin_id'])) {
  header("Location: index");
  exit();
}
// Ambil daftar tabel dalam database
$tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);

// Tabel yang perlu disembunyikan
$hiddenTables = ['otps', 'modules', 'ngadmin'];

// Filter tabel yang tidak perlu ditampilkan
$tables = array_filter($tables, function ($table) use ($hiddenTables) {
  return !in_array($table, $hiddenTables);
});
function getForeignKeyValue($pdo, $table, $keyColumn, $keyValue, $targetColumn)
{
  if (empty($keyValue)) {
    return "-"; // Jika nilai foreign key kosong, tampilkan "-"
  }

  $stmt = $pdo->prepare("SELECT $targetColumn FROM $table WHERE $keyColumn = :keyValue LIMIT 1");
  $stmt->execute(['keyValue' => $keyValue]);
  $result = $stmt->fetch(PDO::FETCH_ASSOC);

  return $result[$targetColumn] ?? "-";
}
// Daftar kolom sensitif yang perlu disembunyikan
define('HIDDEN_COLUMNS', ['password', 'private_key', 'wallet_address', 'token', 'api_key', 'secret', 'hash', 'tx_hash']);

?>
<!DOCTYPE html>
<html lang="en" dir="ltr" data-bs-theme="light" data-color-theme="Blue_Theme" data-layout="vertical">

<head>
  <!-- Required meta tags -->
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <!-- Favicon icon-->
  <link rel="shortcut icon" type="image/png" href="assets/images/logos/logo.png" />

  <!-- Core Css -->
  <link rel="stylesheet" href="assets/css/styles.css" />

  <title>Master Admin</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <!-- DataTables CSS -->
  <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css">

  <!-- DataTables JS -->
  <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
  <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
  <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.dataTables.min.css">

  <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
  <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
  <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
  <style>
    table.dataTable {
      width: 100% !important;
      table-layout: auto !important;
    }

    /* Memastikan tabel bisa di-scroll secara horizontal di layar lebar */
    @media (min-width: 992px) {
      .table-responsive {
        overflow-x: auto !important;
        white-space: nowrap !important;
      }
    }

    #table_chats_filter {
      width: 100%;
    }

    #table_chats_filter label {
      display: block;
      width: 100%;
    }

    #table_chats_filter input {
      width: 100%;
    }
  </style>

</head>

<body>
  <!-- Preloader -->
  <div class="preloader">
    <img src="assets/images/logos/logo.png" alt="loader" class="lds-ripple img-fluid" style="width: 10vw; max-width: 1000px; min-width: 100px;" />
  </div>
  <div id="main-wrapper">
    <!-- Sidebar Start -->
    <aside class="left-sidebar with-vertical">
      <div><!-- ---------------------------------- -->
        <!-- Start Vertical Layout Sidebar -->
        <!-- ---------------------------------- -->
        <!-- Sidebar scroll-->
        <nav class="sidebar-nav scroll-sidebar" data-simplebar>
          <!-----------Profile------------------>
          <div class="user-profile position-relative" style="background: url(assets/images/backgrounds/user-info.jpg) no-repeat;">
            <!-- User profile image -->
            <div class="profile-img">
              <img src="assets/images/profile/user-1.jpg" alt="user" class="w-100 rounded-circle overflow-hidden" />
            </div>
            <!-- User profile text-->
            <div class="profile-text hide-menu pt-1 dropdown">
              <a href="javascript:void(0)" class="dropdown-toggle u-dropdown w-100 text-white
                  d-block
                  position-relative
                " id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false"><?= $_SESSION['admin_username'] ?></a>
              <div class="dropdown-menu animated flipInY" aria-labelledby="dropdownMenuLink">

                <a class="dropdown-item d-flex gap-2" href="logout">
                  <i data-feather="log-out" class="feather-sm text-danger "></i>
                  Logout
                </a>

              </div>
            </div>
          </div>
          <!-----------Profile End------------------>

          <ul id="sidebarnav">
            <li class="nav-small-cap">
              <iconify-icon icon="solar:menu-dots-bold" class="nav-small-cap-icon fs-4"></iconify-icon>
              <span class="hide-menu">Dashboard</span>
            </li>
            <li class="sidebar-item">
              <a class="sidebar-link" href="dashboard">
                <iconify-icon icon="bi-house" class="aside-icon"></iconify-icon>
                <span class="hide-menu">Dashboard</span>
              </a>
            </li>
            <?php
            $icons = [
              'chats' => 'bi-chat',
              'chat_messages' => 'bi-envelope',
              'chat_participants' => 'bi-person',
              'jenis_iuran' => 'bi-cash-coin',
              'pembayaran_iuran' => 'bi-credit-card',
              'ppob' => 'bi-coin',
              'transactions' => 'bi-wallet',
              'menu_items' => 'bi-list',
              'setting' => 'bi-sliders',
              'users' => 'bi-person-fill',

            ];

            $menuSections = [
              'Message' => ['chats', 'chat_messages', 'chat_participants'],
              'Koperasi' => ['jenis_iuran', 'pembayaran_iuran', 'ppob', 'transactions'],
              'Admin' => ['menu_items', 'setting', 'users']
            ];
            $firstTable = true; // Menandai menu pertama agar aktif saat pertama kali dibuka

            foreach ($menuSections as $sectionName => $tables): ?>
              <li class="nav-small-cap">
                <iconify-icon icon="solar:menu-dots-bold" class="nav-small-cap-icon fs-4"></iconify-icon>
                <span class="hide-menu"><?php echo $sectionName; ?></span>
              </li>

              <?php foreach ($tables as $table):
                $tableLabel = ucwords(str_replace('_', ' ', $table));
                $icon = $icons[$table] ?? 'bi-question-circle';
              ?>
                <li class="sidebar-item">
                  <a class="sidebar-link tab-link <?php echo $firstTable ? 'active' : ''; ?>" data-bs-toggle="tab" href="#<?php echo $table; ?>">
                    <iconify-icon icon="<?php echo $icon; ?>" class="aside-icon"></iconify-icon>
                    <span class="hide-menu"><?php echo $tableLabel; ?></span>
                  </a>
                </li>

                <?php $firstTable = false; ?>
              <?php endforeach; ?>
              <?php
              if ($sectionName == "Koperasi"): ?>
                <li class="sidebar-item">
                  <a class="sidebar-link" href="deposit">
                    <iconify-icon icon="bi-piggy-bank" class="aside-icon"></iconify-icon>
                    <span class="hide-menu">Deposit</span>
                  </a>
                </li>
                <li class="sidebar-item">
                  <a class="sidebar-link" href="withdraw">
                    <iconify-icon icon="mdi:wallet-outline" class="aside-icon"></iconify-icon>
                    <span class="hide-menu">Withdraw</span>
                  </a>
                </li>

              <?php endif; ?>
            <?php endforeach; ?>

            <li class="nav-small-cap">
              <iconify-icon icon="solar:menu-dots-bold" class="nav-small-cap-icon fs-4"></iconify-icon>
              <span class="hide-menu">Laporan</span>
            </li>
            <li class="sidebar-item">
              <a class="sidebar-link" href="unpaid_users">
                <iconify-icon icon="bi-exclamation-circle" class="aside-icon"></iconify-icon>
                <span class="hide-menu">Anggota belum bayar iuran</span>
              </a>
            </li>
            <li class="nav-small-cap">
              <iconify-icon icon="solar:menu-dots-bold" class="nav-small-cap-icon fs-4"></iconify-icon>
              <span class="hide-menu">Blogs</span>
            </li>
            <li class="sidebar-item">
              <a class="sidebar-link" href="kategori">
                <iconify-icon icon="bi-bookmark" class="aside-icon"></iconify-icon>
                <span class="hide-menu">Kategori</span>
              </a>
            </li>
            <li class="sidebar-item">
              <a class="sidebar-link" href="post">
                <iconify-icon icon="bi-file-earmark-text" class="aside-icon"></iconify-icon>
                <span class="hide-menu">Post</span>
              </a>
            </li>
            <li class="sidebar-item">
              <a class="sidebar-link" href="comment">
                <iconify-icon icon="bi-chat-text" class="aside-icon"></iconify-icon>
                <span class="hide-menu">Comment</span>
              </a>
            </li>
          </ul>



        </nav>

        <!-- End Sidebar scroll-->
      </div>
    </aside>
    <!--  Sidebar End -->
    <div class="page-wrapper">
      <!--  Header Start -->
      <header class="topbar rounded-0 border-0 bg-primary">
        <div class="with-vertical"><!-- ---------------------------------- -->
          <!-- Start Vertical Layout Header -->
          <!-- ---------------------------------- -->
          <nav class="navbar navbar-expand-lg px-lg-0 px-3 py-0">
            <div class="d-none d-lg-block">
              <div class="brand-logo d-flex align-items-center justify-content-between">
                <a href="home" class="text-nowrap logo-img d-flex align-items-center gap-2">
                  <b class="logo-icon">
                    <!--You can put here icon as well // <i class="wi wi-sunset"></i> //-->
                    <!-- Dark Logo icon -->
                    <img src="assets/images/logos/logo.png" alt="homepage" class="dark-logo" style="width: 5vw; max-width: 50px; min-width: 50px;" />
                    <!-- Light Logo icon -->
                    <img src="assets/images/logos/logo.png" alt="homepage" class="light-logo" style="width: 5vw; max-width: 50px; min-width: 50px;" />
                  </b>
                  <!--End Logo icon -->
                  <!-- Logo text -->

                </a>
              </div>
            </div>

            <ul class="navbar-nav gap-2">

              <li class="nav-item nav-icon-hover-bg rounded-circle">
                <a class="nav-link nav-icon-hover sidebartoggler" id="headerCollapse" href="javascript:void(0)">
                  <iconify-icon icon="solar:list-bold"></iconify-icon>
                </a>
              </li>
            </ul>

            <div class="d-block d-lg-none">
              <div class="brand-logo d-flex align-items-center justify-content-between">
                <a href="../main/index.html" class="text-nowrap logo-img d-flex align-items-center gap-2">
                  <b class="logo-icon">
                    <!--You can put here icon as well // <i class="wi wi-sunset"></i> //-->
                    <!-- Dark Logo icon -->
                    <img src="assets/images/logos/logo.png" alt="homepage" class="dark-logo" style="width: 5vw; max-width: 50px; min-width: 50px;" />
                    <!-- Light Logo icon -->
                    <img src="assets/images/logos/logo.png" alt="homepage" class="light-logo" style="width: 5vw; max-width: 50px; min-width: 50px;" />
                  </b>
                  <!--End Logo icon -->
                  <!-- Logo text -->

                </a>
              </div>
            </div>
            <ul class="navbar-nav flex-row  gap-2 align-items-center justify-content-center d-flex d-lg-none">
              <li class="nav-item dropdown nav-icon-hover-bg rounded-circle">
                <a class="navbar-toggler nav-link text-white nav-icon-hover border-0" href="javascript:void(0)" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                  <span class="">
                    <i class="ti ti-dots fs-7"></i>
                  </span>
                </a>
              </li>
            </ul>
            <div class="collapse navbar-collapse justify-content-end" id="navbarNav">
              <div class="d-flex align-items-center justify-content-between py-2 py-lg-0">

                <ul class="navbar-nav gap-2 flex-row ms-auto align-items-center justify-content-center">

                  <li class="nav-item nav-icon-hover-bg rounded-circle">
                    <a class="nav-link nav-icon-hover moon dark-layout" href="javascript:void(0)">
                      <iconify-icon icon="solar:moon-line-duotone" class="moon"></iconify-icon>
                    </a>
                    <a class="nav-link nav-icon-hover sun light-layout" href="javascript:void(0)">
                      <iconify-icon icon="solar:sun-2-line-duotone" class="sun"></iconify-icon>
                    </a>
                  </li>

                  <!-- ------------------------------- -->
                  <!-- start profile Dropdown -->
                  <!-- ------------------------------- -->
                  <li class="nav-item hover-dd dropdown">
                    <a class="nav-link nav-icon-hover" href="javascript:void(0)" id="drop2" aria-expanded="false">
                      <img src="assets/images/profile/user-1.jpg" alt="user" class="profile-pic rounded-circle round-30" />
                    </a>
                    <div class="dropdown-menu pt-0 content-dd overflow-hidden pt-0 dropdown-menu-end user-dd" aria-labelledby="drop2">
                      <div class="profile-dropdown position-relative" data-simplebar>
                        <div class=" py-3 border-bottom">
                          <div class="d-flex align-items-center px-3">
                            <img src="assets/images/profile/user-1.jpg" class="rounded-circle round-50" alt="" />
                            <div class="ms-3">
                              <h5 class="mb-1 fs-4"><?= $_SESSION['admin_username'] ?></h5>
                              <p class="mb-0 fs-2 d-flex align-items-center text-muted">
                                <?= $_SESSION['admin_username'] ?>
                              </p>
                            </div>
                          </div>
                        </div>
                        <div class="message-body pb-3">


                          <div class="px-3">
                            <div class="py-8 px-3 d-flex justify-content-between dropdown-item align-items-center h6 mb-0  rounded-2 link">
                              <a href="javascript:void(0)" class="">
                                Mode
                              </a>
                              <div>
                                <a class="moon dark-layout" href="javascript:void(0)">
                                  <iconify-icon icon="solar:moon-line-duotone" class="moon"></iconify-icon>
                                </a>
                                <a class="sun light-layout" href="javascript:void(0)">
                                  <iconify-icon icon="solar:sun-2-line-duotone" class="sun"></iconify-icon>
                                </a>
                              </div>
                            </div>

                            <div class="h6 mb-0 dropdown-item py-8 px-3 rounded-2 link">
                              <a href="logout" class=" d-flex  align-items-center ">
                                Sign Out
                              </a>
                            </div>
                          </div>
                        </div>

                      </div>
                    </div>
                  </li>


                  <!-- ------------------------------- -->
                  <!-- end profile Dropdown -->
                  <!-- ------------------------------- -->
                </ul>
              </div>
            </div>
          </nav>
          <!-- ---------------------------------- -->
          <!-- End Vertical Layout Header -->
          <!-- ---------------------------------- -->

          <!-- ------------------------------- -->
          <!-- apps Dropdown in Small screen -->
          <!-- ------------------------------- -->
          <!--  Mobilenavbar -->
          <div class="offcanvas offcanvas-start" data-bs-scroll="true" tabindex="-1" id="mobilenavbar" aria-labelledby="offcanvasWithBothOptionsLabel">
            <nav class="sidebar-nav scroll-sidebar">
              <div class="offcanvas-header justify-content-between">
                <a href="../main/index.html" class="text-nowrap logo-img d-block">
                  <b class="logo-icon">
                    <!--You can put here icon as well // <i class="wi wi-sunset"></i> //-->
                    <!-- Dark Logo icon -->
                    <img src="assets/images/logos/logo.png" alt="homepage">
                  </b>
                  <!--End Logo icon -->
                  <!-- Logo text -->

                </a>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
              </div>

            </nav>
          </div>
        </div>
        <div class="app-header with-horizontal">
          <nav class="navbar navbar-expand-xl container-fluid">
            <ul class="navbar-nav gap-2 align-items-center">
              <li class="nav-item d-block d-xl-none">
                <a class="nav-link sidebartoggler ms-n3" id="sidebarCollapse" href="javascript:void(0)">
                  <iconify-icon icon="solar:hamburger-menu-line-duotone"></iconify-icon>
                </a>
              </li>
              <li class="nav-item d-none d-xl-block">
                <div class="brand-logo d-flex align-items-center justify-content-between">
                  <a href="../main/index.html" class="text-nowrap logo-img d-flex align-items-center gap-2">
                    <b class="logo-icon">
                      <!--You can put here icon as well // <i class="wi wi-sunset"></i> //-->
                      <!-- Dark Logo icon -->
                      <img src="assets/images/logos/logo.png" alt="homepage" class="dark-logo" />
                      <!-- Light Logo icon -->
                      <img src="assets/images/logos/logo.png" alt="homepage" class="light-logo" />
                    </b>
                    <!--End Logo icon -->

                  </a>
                </div>
              </li>

              <li class="nav-item d-none d-lg-block search-box">
                <a class="nav-link nav-icon-hover d-none d-md-flex waves-effect waves-dark" href="javascript:void(0)" data-bs-toggle="modal" data-bs-target="#exampleModal">
                  <iconify-icon icon="solar:magnifer-linear"></iconify-icon>
                </a>
              </li>


            </ul>


            <a class="navbar-toggler nav-icon-hover p-0 border-0 text-white" href="javascript:void(0)" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
              <span class="p-2">
                <i class="ti ti-dots fs-7"></i>
              </span>
            </a>
            <div class="collapse navbar-collapse justify-content-end" id="navbarNav">
              <div class="d-flex align-items-center justify-content-between">
                <ul class="navbar-nav gap-2 flex-row ms-auto align-items-center justify-content-center">





                  <!-- ------------------------------- -->
                  <!-- start profile Dropdown -->
                  <!-- ------------------------------- -->
                  <li class="nav-item hover-dd dropdown">
                    <a class="nav-link nav-icon-hover" href="javascript:void(0)" id="drop2" aria-expanded="false">
                      <img src="assets/images/profile/user-1.jpg" alt="user" width="30" class="profile-pic rounded-circle" />
                    </a>
                    <div class="dropdown-menu pt-0 content-dd overflow-hidden pt-0 dropdown-menu-end user-dd" aria-labelledby="drop2">
                      <div class="profile-dropdown position-relative" data-simplebar>
                        <div class=" py-3 border-bottom">
                          <div class="d-flex align-items-center px-3">
                            <img src="assets/images/profile/user-1.jpg" class="rounded-circle round-50" alt="" />
                            <div class="ms-3">
                              <h5 class="mb-1 fs-4"><?= $_SESSION['admin_username'] ?></h5>
                              <p class="mb-0 fs-2 d-flex align-items-center text-muted">
                                <?= $_SESSION['admin_username'] ?>
                              </p>
                            </div>
                          </div>
                        </div>
                        <div class="message-body pb-3">

                          <div class="px-3">
                            <div class="py-8 px-3 d-flex justify-content-between dropdown-item align-items-center h6 mb-0  rounded-2 link">
                              <a href="javascript:void(0)" class="">
                                Mode
                              </a>
                              <div>
                                <a class="moon dark-layout" href="javascript:void(0)">
                                  <iconify-icon icon="solar:moon-line-duotone" class="moon"></iconify-icon>
                                </a>
                                <a class="sun light-layout" href="javascript:void(0)">
                                  <iconify-icon icon="solar:sun-2-line-duotone" class="sun"></iconify-icon>
                                </a>
                              </div>
                            </div>

                            <div class="h6 mb-0 dropdown-item py-8 px-3 rounded-2 link">
                              <a href="../main/authentication-login.html" class=" d-flex  align-items-center ">
                                Sign Out
                              </a>
                            </div>
                          </div>
                        </div>

                      </div>
                    </div>
                  </li>

                  <!-- ------------------------------- -->
                  <!-- end profile Dropdown -->
                  <!-- ------------------------------- -->
                </ul>
              </div>
            </div>
          </nav>
        </div>
      </header>
      <!--  Header End -->



      <div class="body-wrapper">
        <div class="container-fluid">
          <div class="font-weight-medium shadow-none position-relative overflow-hidden mb-7">
            <div class="card-body px-0">
              <div class="d-flex justify-content-between align-items-center">
                <div>
                  <h4 class="font-weight-medium  mb-0">DataTable</h4>
                  <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                      <li class="breadcrumb-item">
                        <a class="text-muted text-decoration-none" href="">Home
                        </a>
                      </li>
                      <li class="breadcrumb-item text-muted" aria-current="page">Datatable </li>
                    </ol>
                  </nav>
                </div>

              </div>
            </div>
          </div>

          <div class="datatables">
            <div class="tab-content mt-3">
              <?php foreach (array_merge(...array_values($menuSections)) as $index => $table):
                $tableLabel = ucwords(str_replace('_', ' ', $table));
                $isReportTable = in_array($table, ['chat_messages', 'chat_participants', 'pembayaran_iuran', 'transactions']);
              ?>
                <div class="tab-pane fade <?php echo $index === 0 ? 'show active' : ''; ?>" id="<?php echo $table; ?>">
                  <div class="card">
                    <div class="card-body">
                      <h4 class="card-title mb-3"><?php echo $tableLabel; ?></h4>

                      <!-- Filter Tanggal -->
                      <?php if ($table === 'transactions' || $table === 'pembayaran_iuran'): ?>
                        <h5>Filter Created At</h5>
                        <div class="row mb-3">
                          <div class="col-md-4">
                            <label for="start_date_<?php echo $table; ?>">Tanggal Awal:</label>
                            <input type="date" id="start_date_<?php echo $table; ?>" class="form-control">
                          </div>
                          <div class="col-md-4">
                            <label for="end_date_<?php echo $table; ?>">Tanggal Akhir:</label>
                            <input type="date" id="end_date_<?php echo $table; ?>" class="form-control">
                          </div>
                          <div class="col-md-4 d-flex align-items-end">
                            <button class="btn btn-primary w-100" id="filter_<?php echo $table; ?>">Filter</button>
                          </div>
                        </div>
                      <?php endif; ?>


                      <?php if (!$isReportTable): ?>
                        <a href='add?table=<?php echo $table; ?>' class='btn btn-primary mb-3'>Tambah Data</a>
                      <?php endif; ?>

                      <div class="table-responsive">
                        <table id="table_<?php echo $table; ?>" class="table table-striped table-bordered display nowrap">
                          <thead>
                            <tr>
                              <?php
                              $columns = $pdo->query("SHOW COLUMNS FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);
                              $visible_columns = array_filter($columns, function ($column) {
                                return !in_array(strtolower($column['Field']), HIDDEN_COLUMNS);
                              });

                              foreach ($visible_columns as $column) {
                                echo "<th>" . htmlspecialchars(ucwords(str_replace('_', ' ', $column['Field']))) . "</th>";
                              }
                              echo "<th>Aksi</th>";
                              ?>
                            </tr>
                          </thead>
                          <tbody>
                            <?php
                            $rows = $pdo->query("SELECT * FROM `$table` ")->fetchAll(PDO::FETCH_ASSOC);
                            foreach ($rows as $row) {
                              echo "<tr>";
                              foreach ($visible_columns as $column) {
                                $colName = $column['Field'];
                                $value = $row[$colName];

                                switch ("$table.$colName") {
                                  case "chat_messages.chat_id":
                                  case "chat_participants.chat_id":
                                    $value = getForeignKeyValue($pdo, 'chats', 'id', $value, 'name');
                                    break;
                                  case "chat_messages.sender_id":
                                  case "chat_participants.user_id":
                                  case "pembayaran_iuran.user_id":
                                  case "transactions.user_id":
                                    $value = getForeignKeyValue($pdo, 'users', 'id', $value, 'name');
                                    break;
                                  case "pembayaran_iuran.iuran_id":
                                    $value = getForeignKeyValue($pdo, 'jenis_iuran', 'id', $value, 'nama');
                                    break;
                                }

                                if ($colName === 'status') {
                                  $status = htmlspecialchars($value);
                                  $badgeClass = ($status === 'aktif' || $status === 'success') ? 'badge bg-success' : 'badge bg-danger';
                                  echo "<td><span class='$badgeClass'>$status</span></td>";
                                } else {
                                  echo "<td>" . htmlspecialchars($value) . "</td>";
                                }
                              }
                            ?>
                              <td>
                                <?php if (!$isReportTable): ?>
                                  <a href='edit?table=<?php echo $table; ?>&id=<?php echo $row[$columns[0]['Field']]; ?>' class='btn btn-warning btn-sm'>Edit</a>
                                <?php endif; ?>
                                <a href='delete?table=<?php echo $table; ?>&id=<?php echo $row[$columns[0]['Field']]; ?>' class='btn btn-danger btn-sm' onclick='return confirm("Yakin ingin menghapus?")'>Hapus</a>
                              </td>
                            <?php echo "</tr>";
                            }
                            ?>
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          </div>


        </div>
      </div>
    </div>


  </div>

  <script src="assets/js/vendor.min.js"></script>
  <!-- Import Js Files -->
  <script src="assets/js/breadcrumb/breadcrumbChart.js"></script>
  <script src="assets/libs/apexcharts/dist/apexcharts.min.js"></script>
  <script src="assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
  <script src="assets/libs/simplebar/dist/simplebar.min.js"></script>
  <script src="assets/js/theme/app.init.js"></script>
  <script src="assets/js/theme/theme.js"></script>
  <script src="assets/js/theme/app.min.js"></script>
  <script src="assets/js/theme/sidebarmenu.js"></script>
  <script src="assets/js/theme/feather.min.js"></script>

  <!-- solar icons -->
  <script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.8/dist/iconify-icon.min.js"></script>
  <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.dataTables.min.css">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
  <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
  <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
  <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
  <script>
    $(document).ready(function() {
      $("table[id^='table_']").each(function() {
        let tableId = $(this).attr("id");
        let dataTable = $("#" + tableId).DataTable({
          responsive: true,
          autoWidth: false,
          lengthMenu: [10, 25, 50, 100],
          pageLength: 10,
          language: {
            search: "Cari:",
            lengthMenu: "Tampilkan Data _MENU_",
            info: "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
            paginate: {
              first: "Awal",
              last: "Akhir",
              next: "›",
              previous: "‹"
            }
          },
          dom: 'fBrtip',
          buttons: [{
              extend: 'copy',
              footer: false,
              exportOptions: {
                columns: ':not(:last-child)'
              },
              customize: function(copy) {
                return appendTotal(copy, tableId);
              }
            },
            {
              extend: 'csv',
              footer: false,
              exportOptions: {
                columns: ':not(:last-child)'
              },
              customize: function(csv) {
                return appendTotal(csv, tableId);
              }
            },
            {
              extend: 'excel',
              footer: false,
              exportOptions: {
                columns: ':not(:last-child)'
              },
              customize: function(xlsx) {
                return appendTotal(xlsx, tableId);
              }
            },
            {
              extend: 'pdf',
              footer: false,
              exportOptions: {
                columns: ':not(:last-child)'
              },
              customize: function(doc) {
                if (tableId === "table_transactions" || tableId === "table_pembayaran_iuran") {
                  doc.content.push({
                    text: getTotalText(tableId),
                    style: 'tableBody'
                  });
                }
              }
            },
            {
              extend: 'print',
              footer: false,
              exportOptions: {
                columns: ':not(:last-child)'
              },
              customize: function(win) {
                if (tableId === "table_transactions" || tableId === "table_pembayaran_iuran") {
                  $(win.document.body).append('<br><strong>' + getTotalText(tableId) + '</strong>');
                }
              }
            }
          ]
        });

        // Event filter khusus untuk transaksi
        if (tableId === "table_transactions" || tableId === "table_pembayaran_iuran") {
          let tableName = tableId.replace("table_", "");

          $("#filter_" + tableName).off("click").on("click", function() {
            dataTable.draw();
          });

          let createdAtIndex = $("#" + tableId + " thead th").filter(function() {
            return $(this).text().trim().toLowerCase() === "created at";
          }).index();

          if (createdAtIndex !== -1) {
            $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
              if (settings.nTable.id !== tableId) return true;
              let createdAt = data[createdAtIndex].trim();
              let startDate = $("#start_date_" + tableName).val();
              let endDate = $("#end_date_" + tableName).val();
              if (!startDate || !endDate) return true;
              let createdAtDate = createdAt.split(" ")[0];
              return createdAtDate >= startDate && createdAtDate <= endDate;
            });
            dataTable.draw();
          }
        }
      });
    });

    // Fungsi untuk mendapatkan teks total
    function getTotalText(tableId) {
      let dataTable = $("#" + tableId).DataTable();
      let total = dataTable
        .column(getAmountColumnIndex(tableId), {
          page: "current"
        })
        .data()
        .reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
      return `Total: ${total.toLocaleString()}`;
    }

    // Fungsi untuk mendapatkan indeks kolom amount/jumlah_bayar
    function getAmountColumnIndex(tableId) {
      let columnName = tableId === "table_transactions" ? "amount" : "jumlah_bayar";
      return $("#" + tableId + " thead th").filter(function() {
        return $(this).text().trim().toLowerCase() === columnName;
      }).index();
    }

    // Fungsi untuk menambahkan total ke hasil export (copy, csv, excel)
    function appendTotal(data, tableId) {
      let totalText = getTotalText(tableId);
      return data + "\n" + totalText;
    }

    // Fungsi untuk mendapatkan teks total dalam format yang sesuai
    function getTotalText(tableId) {
      let dataTable = $("#" + tableId).DataTable();
      let total = dataTable
        .column(getAmountColumnIndex(tableId), {
          search: "applied"
        })
        .data()
        .reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
      return "Total: " + total.toLocaleString();
    }



    $(".nav-link").on("click", function() {
      setTimeout(function() {
        $("table[id^='table_']").DataTable();
      }, 200);
    });

    document.addEventListener("DOMContentLoaded", function() {
      let urlParams = new URLSearchParams(window.location.search);
      let activeTab = urlParams.get("tab");

      if (activeTab) {
        let targetTab = document.querySelector(`.tab-link[href="#${activeTab}"]`);
        let targetPane = document.getElementById(activeTab);

        if (targetTab && targetPane) {
          document.querySelectorAll(".tab-link").forEach(link => link.classList.remove("active"));
          document.querySelectorAll(".tab-pane").forEach(pane => pane.classList.remove("show", "active"));

          targetTab.classList.add("active");
          targetPane.classList.add("show", "active");
        }
      }

      // Pastikan semua tab bisa diklik dan URL diperbarui tanpa reload
      document.querySelectorAll(".tab-link").forEach(tab => {
        tab.addEventListener("click", function(e) {
          e.preventDefault();
          let target = document.querySelector(this.getAttribute("href"));

          document.querySelectorAll(".tab-pane").forEach(pane => pane.classList.remove("show", "active"));
          document.querySelectorAll(".tab-link").forEach(link => link.classList.remove("active"));

          target.classList.add("show", "active");
          this.classList.add("active");

          let newUrl = window.location.pathname + "?tab=" + this.getAttribute("href").substring(1);
          history.pushState(null, "", newUrl);
        });
      });


    });
  </script>

</body>

</html>