<?php
include('../includes/session.php');
include('../includes/config.php');

// Admin check
if(checkAdmin($udata['type']) == false){
    echo "<script>window.location='index.php';</script>";
    die();
}

include('../template/tngweb/header.php');

// Password reset
if(isset($_GET['id'], $_GET['reset']) && $_GET['reset'] == 1){
    $id = base64_decode($_GET['id']);
    $vpass = rand(100000,999999); // 6-digit random password
    $pass = password_hash($vpass, PASSWORD_DEFAULT);
    $reset = mysqli_query($tng_conn, "UPDATE users SET password='$pass' WHERE id='$id'");
    if($reset){
        echo "<script>
            $(function(){
                Swal.fire('Password Reset Successfully', 'New: $vpass', 'success');
            });
        </script>";
    }
}

// Login as user
if(isset($_GET['login'], $_GET['phone']) && $_GET['login'] == 1 && $_GET['phone'] != NULL){
    $phone = base64_decode($_GET['phone']);
    $_SESSION['phone'] = $phone;
    $_SESSION['adminasuser'] = true;
    $_SESSION['adminusername'] = $udata['phone'];
    echo "<script>setTimeout(function(){ window.location=''; }, 0);</script>";
}

// Admin actions: delete, ban, approve
if(checkAdmin($udata['type']) == true){
    if(isset($_GET['deleteuser'], $_GET['id']) && $_GET['deleteuser'] == 1){
        $id = base64_decode(mysqli_real_escape_string($tng_conn, $_GET['id']));
        if(mysqli_query($tng_conn, "DELETE FROM users WHERE id='$id'")){
            showAlert('User Deleted Successfully');
            ahkRedirect('users.php', 1200);
        }
    }

    if(isset($_GET['banid'], $_GET['ban']) && $_GET['ban'] == 1){
        $banid = base64_decode(getSafe($_GET['banid']));
        if(ahkQuery("UPDATE users SET status='0' WHERE id='$banid'")){
            showAlert('User Banned Successfully');
            ahkRedirect('users.php', 1200);
        }
    }

    if(isset($_GET['apid'], $_GET['approve']) && $_GET['approve'] == 1){
        $apid = base64_decode(getSafe($_GET['apid']));
        if(ahkQuery("UPDATE users SET status='1' WHERE id='$apid'")){
            showAlert('User Activated Successfully');
            ahkRedirect('users.php', 1200);
        }
    }
}else{
    header("Location: index.php");
    die();
}
?>

<!--start page wrapper -->
<div class="page-wrapper">
  <div class="page-content">
    <div class="card radius-15 shadow-lg border-0">
      <div class="card-body">
        <!-- Back Button -->
        <div class="d-flex align-items-center justify-content-between mb-3">
          <a href="javascript:void(0);" onclick="window.history.back();" class="btn btn-outline-primary rounded-pill px-4 py-2 fw-semibold">
            <i class="bi bi-arrow-left-circle me-2"></i> Go Back
          </a>
          <h5 class="mb-0 fw-bold text-primary">🌟 All Member History</h5>
        </div>
        <hr>

        <div class="table-responsive">
          <table id="walletTable" class="table table-hover table-striped align-middle text-center">
            <thead class="table-dark">
              <tr>
                <th class="text-center">SL.</th>
                <th class="text-center">Username</th>
                <th class="text-center">Name</th>
                <th class="text-center">Email</th>
                <th class="text-center">Type</th>
                <th class="text-center">Balance</th>
                <th class="text-center">Action</th>
              </tr>
            </thead>
            <tbody>
<?php
$res = mysqli_query($tng_conn, "SELECT * FROM users ORDER BY id DESC");
if(mysqli_num_rows($res) > 0){
    $sr = 1; // Serial number start
    while($data = mysqli_fetch_assoc($res)){
        if($data['type'] == 'admin') continue; // Skip admin
?>
        <tr>
            <td class="text-center"><?= $sr++; ?></td>
            <td class="text-center"><?= htmlspecialchars($data['phone']); ?></td>
            <td class="text-center"><?= htmlspecialchars($data['name']); ?></td>
            <td class="text-center"><?= htmlspecialchars($data['email']); ?></td>
            <td class="text-center"><?= strtoupper($data['type']); ?></td>
            <td class="text-center">
                <?= $data['balance'] !== NULL ? strtoupper($data['balance']) : '0.00'; ?>
                <form action="BalanceTransfer.php" method="POST" class="mt-1">
                    <input type="hidden" name="username" value="<?= htmlspecialchars($data['email']); ?>">
                    <button class="btn btn-success btn-sm" type="submit">Balance Transfer</button>
                </form>
            </td>
            <td class="text-center">
                <div class="d-flex justify-content-center gap-2">
                    <a class="text-success bg-light-success p-2 rounded" title="Reset Password" href="users.php?id=<?= base64_encode($data['id']); ?>&reset=1">
                        <i class='bx bx-refresh'></i>
                    </a>
                    <a class="text-primary bg-light-primary p-2 rounded" title="Edit User" href="EditUser.php?id=<?= base64_encode($data['id']); ?>">
                        <i class='bx bx-pencil'></i>
                    </a>
                    <?php if($data['status']== '0'){ ?>
                        <a class="text-success bg-light-success p-2 rounded" title="Approve User" href="?apid=<?= base64_encode($data['id']); ?>&approve=1">
                            <i class='bx bx-check'></i>
                        </a>
                    <?php }else{ ?>
                        <a class="text-danger bg-light-danger p-2 rounded" title="Ban User" href="?banid=<?= base64_encode($data['id']); ?>&ban=1">
                            <i class='bx bx-x'></i>
                        </a>
                    <?php } ?>
                    <a class="text-danger bg-light-danger p-2 rounded" title="Delete User" href="?deleteuser=1&id=<?= base64_encode($data['id']); ?>" onclick="return confirm('Are you sure?')">
                        <i class='bx bx-trash'></i>
                    </a>
                </div>
            </td>
        </tr>
<?php
    }
}
?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
<!--end page wrapper -->

<?php include('../template/tngweb/footer.php'); ?>

<!-- DataTables & Scripts -->
<script src="../template/tngweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/tngweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/tngweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

<script>
  $(document).ready(function() {
    $('#walletTable').DataTable({
      lengthChange: false,
      pageLength: 10,
      order: [[0, "asc"]],
      buttons: ['copy', 'excel', 'pdf', 'print'],
      dom: '<"d-flex justify-content-between align-items-center mb-3"Bf>rt<"d-flex justify-content-between align-items-center"ip>'
    });
  });
</script>

<style>
  .table thead th { vertical-align: middle; font-weight: 600; letter-spacing: 0.3px; }
  .table tbody tr:hover { background: #f5f8ff; transition: 0.2s ease; }
  .card { background: #fff; border-radius: 15px; }
  .btn-outline-primary { border-color: #0055ff; color: #0055ff; }
  .btn-outline-primary:hover { background-color: #0055ff; color: #fff; }
  .dataTables_wrapper .dataTables_filter input { border-radius: 8px; padding: 5px 10px; }
  .dataTables_wrapper .dataTables_paginate .paginate_button { border-radius: 5px; }
  .dataTables_wrapper .dt-buttons .btn { border-radius: 20px !important; font-size: 0.85rem; margin-right: 6px; }
  .badge { font-size: 0.8rem; padding: 6px 10px; }
</style>
