<?php



// Standardized admin page setup



require_once __DIR__ . '/config.php';



require_admin_login();







/**



 * অটো-সাসপেন্ড সিস্টেম:



 * যারা ২৪ ঘণ্টার মধ্যে রিচার্জ করেনি (ব্যালেন্স <= 0) তাদের ব্লক করা।



 */



$pdo->query("UPDATE users 



             SET is_blocked = 1 



             WHERE is_approved = 1 



             AND balance <= 0 



             AND is_blocked = 0 



             AND approved_at <= (NOW() - INTERVAL 24 HOUR)");







// --- POST ACTIONS ---



if (is_post()) {



    verify_csrf();







    // --- ইউজার অ্যাপ্রুভ করা ---



    if (isset($_POST['approve_user'])) {



        $uid = (int)($_POST['uid'] ?? 0);



        $stmt = $pdo->prepare("UPDATE users SET is_approved = 1, approved_at = NOW() WHERE id = ?");



        $stmt->execute([$uid]);



        set_flash("ইউজার সফলভাবে অ্যাপ্রুভ করা হয়েছে।", "success");



        redirect('users.php');



    }







    // সব পেন্ডিং ইউজার একবারে ডিলিট করা



    if (isset($_POST['delete_all_pending'])) {



        $stmt = $pdo->prepare("DELETE FROM users WHERE is_approved = 0");



        $stmt->execute();



        set_flash("সব পেন্ডিং ইউজার ডিলিট করা হয়েছে।", "success");



        redirect('users.php');



    }







    // ব্লক/আনব্লক ইউজার



    if (isset($_POST['toggle_block'])) {



        $uid = (int)($_POST['uid'] ?? 0);



        $stmt = $pdo->prepare("UPDATE users SET is_blocked = NOT is_blocked WHERE id=?");



        $stmt->execute([$uid]);



        set_flash("ইউজারের স্ট্যাটাস পরিবর্তন করা হয়েছে।", "success");



        redirect('users.php');



    }







    // একক ইউজার ডিলিট করা



    if (isset($_POST['delete_user'])) {



        $uid = (int)($_POST['uid'] ?? 0);



        $stmt = $pdo->prepare("DELETE FROM users WHERE id=?");



        $stmt->execute([$uid]);



        set_flash("ইউজার ডিলিট করা হয়েছে।", "success");



        redirect('users.php');



    }







    // জিরো ব্যালেন্স ইউজার ডিলিট করা



    if (isset($_POST['delete_all_zero'])) {



        $stmt = $pdo->prepare("DELETE FROM users WHERE balance <= 0 AND is_approved = 1");



        $stmt->execute();



        set_flash("সব জিরো ব্যালেন্স ইউজার ডিলিট করা হয়েছে।", "success");



        redirect('users.php');



    }







    // ব্যালেন্স আপডেট



    if (isset($_POST['update_balance'])) {



        $uid = (int)($_POST['uid'] ?? 0);



        $amount = (float)($_POST['amount'] ?? 0);



        $action = $_POST['action'] ?? 'add';







        if ($uid > 0 && $amount > 0) {



            if ($action === 'add') {



                $stmt = $pdo->prepare("UPDATE users SET balance = balance + ?, is_blocked = 0 WHERE id = ?");



                $stmt->execute([$amount, $uid]);



            } elseif ($action === 'remove') {



                $stmt = $pdo->prepare("UPDATE users SET balance = GREATEST(0, balance - ?) WHERE id = ?");



                $stmt->execute([$amount, $uid]);



            }



            set_flash("ব্যালেন্স আপডেট করা হয়েছে।", "success");



        }



        redirect('users.php');



    }



}







// --- সার্চ লজিক ---



$search = trim($_GET['search'] ?? '');



$params = [];



$search_sql = "";







if ($search !== '') {



    $search_sql = " AND (name LIKE ? OR email LIKE ? OR phone LIKE ?)"; // ফোনেও সার্চ করা যাবে



    $params[] = "%$search%";



    $params[] = "%$search%";



    $params[] = "%$search%";



}







// ইউজার ডাটা ফেচিং



$stmt_pending = $pdo->prepare("SELECT * FROM users WHERE is_approved = 0 $search_sql ORDER BY id DESC");



$stmt_pending->execute($params);



$users_pending = $stmt_pending->fetchAll();







$stmt1 = $pdo->prepare("SELECT * FROM users WHERE is_approved = 1 AND balance > 0 $search_sql ORDER BY id ASC");



$stmt1->execute($params);



$users_with_balance = $stmt1->fetchAll();







$stmt2 = $pdo->prepare("SELECT * FROM users WHERE is_approved = 1 AND balance <= 0 $search_sql ORDER BY id ASC");



$stmt2->execute($params);



$users_no_balance = $stmt2->fetchAll();







require_once 'header.php';



?>







<div class="d-sm-flex align-items-center justify-content-between mb-4">



    <h1 class="h3 mb-0 text-gray-800 fw-bold">User Management</h1>



    



    <form method="get" class="d-flex shadow-sm" style="width: 100%; max-width: 400px;">



        <input type="text" name="search" class="form-control" placeholder="নাম, ইমেইল বা নাম্বার..." value="<?php echo htmlspecialchars($search); ?>">



        <button class="btn btn-primary px-3" type="submit"><i class="bi bi-search"></i></button>



        <?php if ($search !== ''): ?>



            <a href="users.php" class="btn btn-outline-secondary ms-1">Reset</a>



        <?php endif; ?>



    </form>



</div>







<?php show_flash(); ?>







<ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">



  <li class="nav-item">



    <button class="nav-link <?php echo ($search === '' || count($users_pending) > 0) ? 'active' : ''; ?> fw-bold position-relative" data-bs-toggle="pill" data-bs-target="#pending-tab">



        পেন্টিং রিকোয়েস্ট 



        <?php if(count($users_pending) > 0): ?>



            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"><?php echo count($users_pending); ?></span>



        <?php endif; ?>



    </button>



  </li>



  <li class="nav-item">



    <button class="nav-link fw-bold" data-bs-toggle="pill" data-bs-target="#active-tab">সক্রিয় ইউজার (<?php echo count($users_with_balance); ?>)</button>



  </li>



  <li class="nav-item">



    <button class="nav-link fw-bold" data-bs-toggle="pill" data-bs-target="#zero-tab">জিরো/সাসপেন্ড (<?php echo count($users_no_balance); ?>)</button>



  </li>



</ul>







<div class="tab-content" id="pills-tabContent">



    <div class="tab-pane fade show <?php echo ($search === '' || count($users_pending) > 0) ? 'active' : ''; ?>" id="pending-tab">



        <div class="card shadow-sm mb-4 border-left-warning">



            <div class="card-header py-3 d-flex justify-content-between align-items-center">



                <h6 class="m-0 fw-bold text-warning">নতুন ইউজার রিকোয়েস্ট</h6>



                <div class="d-flex gap-2">



                    <?php if(count($users_pending) > 0): ?>



                    <button onclick="downloadPendingPDF()" class="btn btn-sm btn-success fw-bold"><i class="bi bi-file-earmark-pdf-fill"></i> ডাউনলোড PDF</button>



                    <form method="post" onsubmit="return confirm('সব পেন্ডিং ইউজার ডিলিট করতে চান?');">



                        <?php csrf_field(); ?>



                        <button name="delete_all_pending" class="btn btn-sm btn-danger fw-bold">ডিলিট অল</button>



                    </form>



                    <?php endif; ?>



                </div>



            </div>



            <div class="card-body" id="pendingTableSection">



                <?php render_user_table($users_pending, true); ?>



            </div>



        </div>



    </div>







    <div class="tab-pane fade" id="active-tab">



        <div class="card shadow-sm mb-4 border-left-primary">



            <div class="card-body"><?php render_user_table($users_with_balance, false); ?></div>



        </div>



    </div>







    <div class="tab-pane fade" id="zero-tab">



        <div class="card shadow-sm mb-4 border-left-danger">



            <div class="card-body"><?php render_user_table($users_no_balance, false); ?></div>



        </div>



    </div>



</div>







<?php



function render_user_table($user_list, $is_pending = false) {



?>



    <div class="table-responsive">



        <table class="table table-bordered table-striped align-middle mb-0">



            <thead class="table-light">



                <tr>



                    <th>ID</th>



                    <th>নাম ও ইমেইল</th>



                    <th>মোবাইল নাম্বার</th> <th>ব্যালেন্স</th>



                    <th>স্ট্যাটাস</th>



                    <th class="text-center d-print-none">অ্যাকশন</th>



                </tr>



            </thead>



            <tbody>



                <?php if (empty($user_list)): ?>



                    <tr><td colspan="6" class="text-center p-4">কোনো ডাটা পাওয়া যায়নি।</td></tr>



                <?php else: foreach ($user_list as $u): ?>



                    <tr>



                        <td>#<?php echo $u['id']; ?></td>



                        <td>



                            <span class="fw-bold"><?php echo htmlspecialchars($u['name']); ?></span><br>



                            <small class="text-muted"><?php echo htmlspecialchars($u['email']); ?></small>



                        </td>



                        <td class="fw-bold text-primary">



                            <?php echo htmlspecialchars($u['phone'] ?? 'N/A'); ?> </td>



                        <td>৳ <?php echo number_format($u['balance'], 2); ?></td>



                        <td>



                            <?php if ($is_pending): ?>



                                <span class="badge bg-warning text-dark">Pending</span>



                            <?php elseif ($u['is_blocked']): ?>



                                <span class="badge bg-danger">Suspended</span>



                            <?php else: ?>



                                <span class="badge bg-success">Active</span>



                            <?php endif; ?>



                        </td>



                        <td class="text-center d-print-none">



                            <?php if ($is_pending): ?>



                                <form method="post" class="d-inline">



                                    <?php csrf_field(); ?>



                                    <input type="hidden" name="uid" value="<?php echo $u['id']; ?>">



                                    <button name="approve_user" class="btn btn-sm btn-primary fw-bold shadow-sm">Approve</button>



                                </form>



                            <?php else: ?>



                                <button type="button" class="btn btn-sm btn-info text-white" data-bs-toggle="modal" data-bs-target="#balanceModal_<?php echo $u['id']; ?>"><i class="bi bi-currency-dollar"></i></button>



                                <form method="post" class="d-inline">



                                    <?php csrf_field(); ?>



                                    <input type="hidden" name="uid" value="<?php echo $u['id']; ?>">



                                    <button name="toggle_block" class="btn btn-sm <?php echo $u['is_blocked'] ? 'btn-success' : 'btn-warning'; ?>"><i class="bi <?php echo $u['is_blocked'] ? 'bi-unlock-fill' : 'bi-lock-fill'; ?>"></i></button>



                                </form>



                            <?php endif; ?>



                            <form method="post" class="d-inline">



                                <?php csrf_field(); ?>



                                <input type="hidden" name="uid" value="<?php echo $u['id']; ?>">



                                <button name="delete_user" class="btn btn-sm btn-danger" onclick="return confirm('নিশ্চিত?')"><i class="bi bi-trash-fill"></i></button>



                            </form>



                        </td>



                    </tr>



                <?php endforeach; endif; ?>



            </tbody>



        </table>



    </div>



<?php



}







// মোডাল লুপ



$all_users = array_merge($users_pending, $users_with_balance, $users_no_balance);



foreach ($all_users as $u): ?>



<div class="modal fade" id="balanceModal_<?php echo $u['id']; ?>" tabindex="-1">



    <div class="modal-dialog modal-dialog-centered">



        <div class="modal-content">



            <div class="modal-header bg-dark text-white">



                <h5 class="modal-title">ব্যালেন্স আপডেট: <?php echo htmlspecialchars($u['name']); ?></h5>



                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>



            </div>



            <form method="post">



                <?php csrf_field(); ?>



                <input type="hidden" name="uid" value="<?php echo $u['id']; ?>">



                <div class="modal-body p-4">



                    <div class="text-center mb-3">



                        <small class="text-muted">বর্তমান ব্যালেন্স</small>



                        <h3 class="fw-bold">৳ <?php echo number_format($u['balance'], 2); ?></h3>



                    </div>



                    <div class="mb-3">



                        <label class="form-label fw-bold">টাকার পরিমাণ</label>



                        <input type="number" step="0.01" class="form-control form-control-lg" name="amount" required>



                    </div>



                    <div class="mb-3">



                        <label class="form-label fw-bold">অ্যাকশন</label>



                        <select class="form-select" name="action">



                            <option value="add">যোগ করুন (আনব্লক হবে)</option>



                            <option value="remove">কর্তন করুন</option>



                        </select>



                    </div>



                </div>



                <div class="modal-footer">



                    <button type="submit" name="update_balance" class="btn btn-primary w-100 py-2">কনফার্ম আপডেট</button>



                </div>



            </form>



        </div>



    </div>



</div>



<?php endforeach; ?>







<script>



function downloadPendingPDF() {



    var printContents = document.getElementById('pendingTableSection').innerHTML;



    var printWindow = window.open('', '', 'height=700,width=900');



    printWindow.document.write('<html><head><title>Pending Users</title>');



    printWindow.document.write('<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">');



    printWindow.document.write('<style>.d-print-none{display:none!important} table{width:100%;border-collapse:collapse} th,td{border:1px solid #ddd;padding:8px}</style>');



    printWindow.document.write('</head><body>');



    printWindow.document.write('<h2 class="text-center mb-4">পেন্ডিং ইউজার লিস্ট</h2>');



    printWindow.document.write(printContents);



    printWindow.document.write('</body></html>');



    printWindow.document.close();



    setTimeout(function() { printWindow.print(); printWindow.close(); }, 500);



}



</script>







<?php require_once 'footer.php'; ?>