<?php
include(__DIR__ . '/../../session.php');

$getUserBalance = "
    SELECT u.id, u.fullname, u.username, u.phone, u.gameplay, u.status, u.created_at,
           b.total_balance, b.total_turnover, b.last_updated,
           ba.BankName, ba.BankHolder, ba.BankNumber
    FROM user u
    LEFT JOIN balance b ON u.id = b.user_id
    LEFT JOIN bank_user ba ON u.id = ba.user_id
    ORDER BY u.id ASC
";
$stmt = $db->prepare($getUserBalance);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

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

<?php include(__DIR__ . '/../../layouts/header.php'); ?>

<body>
  <div class="wrapper">
    <?php include(__DIR__ . '/../../layouts/sidebar.php'); ?>

    <div class="main-panel">
      <?php include(__DIR__ . '/../../layouts/navbar.php'); ?>

      <div class="container">
        <div class="page-inner">

          <div class="page-header">
            <h3 class="fw-bold mb-3">Saldo Pengguna</h3>
            <ul class="breadcrumbs mb-3">
              <li class="nav-home">
                <a href="#">
                  <i class="icon-home"></i>
                </a>
              </li>
              <li class="separator">
                <i class="icon-arrow-right"></i>
              </li>
              <li class="nav-item">
                <a href="#">Pengguna</a>
              </li>
              <li class="separator">
                <i class="icon-arrow-right"></i>
              </li>
              <li class="nav-item">
                <a href="#">Saldo Pengguna</a>
              </li>
            </ul>
          </div>

          <div class="row">
            <div class="col-md-12">
              <div class="card">
                <div class="card-body">
                  <div class="table-responsive">
                    <table id="basic-datatables" class="display table table-striped table-hover">
                      <thead>
                        <tr>
                          <th>No</th>
                          <th>Nama Lengkap</th>
                          <th>Nama Pengguna</th>
                          <th>Saldo Aktif</th>
                          <th>Bonus</th>
                          <th>Aksi</th>
                          <?php if (isset($_SESSION['admin_id']) && isset($admin['level'])): ?>
                            <?php if ($admin['level'] === 'developer' || $admin['level'] === 'admin'): ?>
                          <th>Diperbaharui Oleh</th>
                            <?php endif; ?>
                          <?php endif; ?>
                        </tr>
                      </thead>
                      <tbody>
                        <?php $no = 1;
                        foreach ($users as $user): ?>
                          <tr>
                            <td><?= $no++; ?></td>
                            <td><?= htmlspecialchars($user['fullname']); ?></td>
                            <td><?= htmlspecialchars($user['username']); ?></td>
                            <td><?= htmlspecialchars(number_format($user['total_balance'], 0, ',', '.')); ?></td>
                            <td>0</td>
                            <td>
                              <button class="btn btn-icon btn-round btn-warning btn-edit"
                                data-id="<?= $user["id"] ?>"
                                data-username="<?= htmlspecialchars($user["username"]) ?>">
                                <i class="fas fa-edit"></i>
                              </button>
                            </td>
                          <?php if (isset($_SESSION['admin_id']) && isset($admin['level'])): ?>
                            <?php if ($admin['level'] === 'developer' || $admin['level'] === 'admin'): ?>
                            <td><?= $user['last_updated']; ?></td>
                            <?php endif; ?>
                          <?php endif; ?>
                          </tr>
                        <?php endforeach; ?>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>

      <div class="modal fade" id="editModal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">Edit Saldo Pengguna</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form id="editForm" method="POST">
                <input type="hidden" name="csrf_token" id="csrf_token" value="<?= $csrf_token; ?>">
                <div class="form-group">
                  <label for="username">Nama Pengguna</label>
                  <input type="text" class="form-control" id="username" name="username" readonly>
                </div>
                <div class="form-group">
                  <label for="amount">Jumlah</label>
                  <input type="number" class="form-control" id="amount" name="Amount" placeholder="Masukan Jumlah" required>
                </div>
                <div class="form-group">
                  <label for="type">Jenis</label>
                  <select class="form-control" id="type" name="type" required>
                    <option value="add">Tambah Saldo</option>
                    <option value="remove">Kurangi Saldo</option>
                  </select>
                </div>
                <input type="hidden" id="id" name="id">
                <button type="submit" class="btn btn-primary">Simpan</button>
              </form>
            </div>
          </div>
        </div>
      </div>


      <?php include(__DIR__ . '/../../layouts/footer.php'); ?>

    </div>
  </div>

  <?php include(__DIR__ . '/../../layouts/script.php'); ?>

  <script>
    $(document).ready(function() {
      $('#basic-datatables').DataTable();

      // Gunakan event delegation untuk tombol edit
      $(document).on('click', '.btn-edit', function() {
        const id = $(this).data('id');
        const username = $(this).data('username');

        $('#username').val(username);
        $('#id').val(id);
        $('#editModal').modal('show');
      });

      $('#editForm').on('submit', function(e) {
        e.preventDefault();

        const formData = $(this).serialize();

        $.ajax({
          url: 'update-balance',
          type: 'POST',
          data: formData,
          success: function(response) {
            const res = JSON.parse(response);
            alert(res.message);
            if (res.status === 'success') {
              location.reload();
            }
          },
          error: function() {
            alert('Terjadi kesalahan, coba lagi!');
          }
        });
      });
    });
  </script>

</body>

</html>