<?php
// Standardized admin page setup
require_once __DIR__ . '/config.php';
require_admin_login();

// --- POST ACTIONS ---
if (is_post()) {
    verify_csrf();

    // --- নতুন ফিচার: সব ইউজারের ব্যালেন্স এক ক্লিকে জিরো করা ---
    if (isset($_POST['reset_all_balances'])) {
        $stmt = $pdo->prepare("UPDATE users SET balance = 0 WHERE balance > 0");
        $stmt->execute();
        $resetCount = $stmt->rowCount();
        set_flash("Successfully reset balance to 0 for $resetCount users.", "success");
        redirect('users.php');
    }

    // --- নতুন ফিচার: সব ইউজারকে এক ক্লিকে আনব্লক করা ---
    if (isset($_POST['unblock_all'])) {
        $stmt = $pdo->prepare("UPDATE users SET is_blocked = 0 WHERE is_blocked = 1");
        $stmt->execute();
        $unblockedCount = $stmt->rowCount();
        set_flash("Successfully unblocked $unblockedCount users.", "success");
        redirect('users.php');
    }

    // Block/Unblock user
    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("User status has been changed.", "success");
        redirect('users.php');
    }

    // Delete single user
    if (isset($_POST['delete_user'])) {
        $uid = (int)($_POST['uid'] ?? 0);
        if ($uid) {
            $stmt = $pdo->prepare("DELETE FROM users WHERE id=?");
            $stmt->execute([$uid]);
            set_flash("User has been deleted.", "success");
            redirect('users.php');
        }
    }

    // --- DELETE ALL ZERO BALANCE USERS ---
    if (isset($_POST['delete_all_zero'])) {
        $stmt = $pdo->prepare("DELETE FROM users WHERE balance <= 0");
        $stmt->execute();
        $deletedCount = $stmt->rowCount();
        set_flash("Successfully deleted $deletedCount users with zero balance.", "success");
        redirect('users.php');
    }

    // --- ADD/REMOVE BALANCE ---
    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 + ? WHERE id = ?");
                $stmt->execute([$amount, $uid]);
                set_flash("Successfully added " . h($amount) . " to the user's balance.", "success");
            } elseif ($action === 'remove') {
                $stmt = $pdo->prepare("UPDATE users SET balance = GREATEST(0, balance - ?) WHERE id = ?");
                $stmt->execute([$amount, $uid]);
                set_flash("Successfully removed " . h($amount) . " from the user's balance.", "success");
            }
        } else {
            set_flash("Invalid amount or user ID.", "danger");
        }
        redirect('users.php');
    }
}

// --- FETCH DATA FOR DASHBOARD ---
$total_balance_stmt = $pdo->query("SELECT SUM(balance) as grand_total FROM users");
$total_balance_data = $total_balance_stmt->fetch();
$grand_total_balance = $total_balance_data['grand_total'] ?? 0;

// ব্লকড ইউজারের সংখ্যা চেক
$blocked_users_stmt = $pdo->query("SELECT COUNT(*) FROM users WHERE is_blocked = 1");
$blocked_count = $blocked_users_stmt->fetchColumn();

// --- FETCH USERS ---
$search = trim($_GET['search'] ?? '');
$params = [];
$search_sql = "";
if ($search !== '') {
    $search_sql = " AND (name LIKE ? OR email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

// System 1: যাদের ব্যালেন্স আছে
$stmt1 = $pdo->prepare("SELECT * FROM users WHERE balance > 0 $search_sql ORDER BY id ASC");
$stmt1->execute($params);
$users_with_balance = $stmt1->fetchAll();

// System 2: যাদের ব্যালেন্স নেই
$stmt2 = $pdo->prepare("SELECT * FROM users WHERE balance <= 0 $search_sql ORDER BY id ASC");
$stmt2->execute($params);
$users_no_balance = $stmt2->fetchAll();

require_once 'header.php';
?>

<style>
    /* কাস্টম কালার থিম */
    :root {
        --theme-color: #230133;
        --theme-hover: #3b0354;
        --theme-light: #f4eef7;
    }

    .text-theme { color: var(--theme-color) !important; }
    .bg-theme { background-color: var(--theme-color) !important; color: white; }
    
    .btn-theme {
        background-color: var(--theme-color);
        color: white;
        border: none;
    }
    .btn-theme:hover {
        background-color: var(--theme-hover);
        color: white;
    }

    .nav-pills .nav-link.active {
        background-color: var(--theme-color) !important;
    }
    .nav-pills .nav-link {
        color: var(--theme-color);
    }

    .card-header {
        background-color: white;
        border-bottom: 2px solid var(--theme-color);
    }

    .table thead th {
        background-color: var(--theme-color);
        color: white;
        border: none;
    }

    .border-left-theme {
        border-left: 0.25rem solid var(--theme-color) !important;
    }

    .modal-header {
        background-color: var(--theme-color);
        color: white;
    }
</style>

<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <div>
        <h1 class="h3 mb-0 text-theme fw-bold">User Management</h1>
        
        <div class="mt-2 d-flex gap-2">
            <?php if($blocked_count > 0): ?>
                <form method="post" onsubmit="return confirm('Are you sure you want to unblock ALL blocked users?');">
                    <?php csrf_field(); ?>
                    <button name="unblock_all" class="btn btn-sm btn-success fw-bold shadow-sm">
                        <i class="bi bi-unlock-fill me-1"></i> Unblock All (<?php echo $blocked_count; ?>)
                    </button>
                </form>
            <?php endif; ?>

            <?php if($grand_total_balance > 0): ?>
                <form method="post" onsubmit="return confirm('WARNING: This will reset ALL users\' balances to ৳ 0.00! Are you absolutely sure?');">
                    <?php csrf_field(); ?>
                    <button name="reset_all_balances" class="btn btn-sm btn-danger fw-bold shadow-sm">
                        <i class="bi bi-arrow-counterclockwise me-1"></i> Reset All Balances
                    </button>
                </form>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="card border-left-theme shadow h-100 py-2 px-3 bg-white mt-3 mt-sm-0">
        <div class="card-body p-0">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-theme text-uppercase mb-1">Total System Balance</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">৳ <?php echo number_format($grand_total_balance, 2); ?></div>
                </div>
                <div class="col-auto">
                    <i class="bi bi-wallet2 fs-2 text-theme opacity-25"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<?php show_flash(); ?>

<ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
  <li class="nav-item">
    <button class="nav-link active fw-bold" id="active-bal-tab" data-bs-toggle="pill" data-bs-target="#active-bal" type="button">
        <i class="bi bi-cash-stack me-1"></i> Balance Active (<?php echo count($users_with_balance); ?>)
    </button>
  </li>
  <li class="nav-item">
    <button class="nav-link fw-bold" id="zero-bal-tab" data-bs-toggle="pill" data-bs-target="#zero-bal" type="button">
        <i class="bi bi-person-x me-1"></i> Zero Balance (<?php echo count($users_no_balance); ?>)
    </button>
  </li>
</ul>

<div class="tab-content" id="pills-tabContent">
    <div class="tab-pane fade show active" id="active-bal">
        <div class="card shadow-sm mb-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                <h6 class="m-0 fw-bold text-theme"><i class="bi bi-people-fill me-2"></i>Active Balance Users</h6>
                <form method="get" class="d-flex" style="width: 100%; max-width: 300px;">
                    <input type="text" name="search" class="form-control form-control-sm me-2" placeholder="Search..." value="<?php echo h($search); ?>">
                    <button class="btn btn-sm btn-theme px-3" type="submit">Search</button>
                </form>
            </div>
            <div class="card-body">
                <?php render_user_table($users_with_balance); ?>
            </div>
        </div>
    </div>

    <div class="tab-pane fade" id="zero-bal">
        <div class="card shadow-sm mb-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                <div>
                    <h6 class="m-0 fw-bold text-danger d-inline me-3"><i class="bi bi-people-fill me-2"></i>Zero Balance Users</h6>
                    <?php if(!empty($users_no_balance)): ?>
                    <form method="post" class="d-inline" onsubmit="return confirm('Attention! This will delete ALL users with ৳ 0.00 balance. Are you sure?');">
                        <?php csrf_field(); ?>
                        <button name="delete_all_zero" class="btn btn-sm btn-danger fw-bold shadow-sm">
                            <i class="bi bi-trash3-fill me-1"></i> Delete All Zero Accounts
                        </button>
                    </form>
                    <?php endif; ?>
                </div>
                <form method="get" class="d-flex" style="width: 100%; max-width: 300px;">
                    <input type="text" name="search" class="form-control form-control-sm me-2" placeholder="Search..." value="<?php echo h($search); ?>">
                    <button class="btn btn-sm btn-outline-danger" type="submit">Search</button>
                </form>
            </div>
            <div class="card-body">
                <?php render_user_table($users_no_balance); ?>
            </div>
        </div>
    </div>
</div>

<?php
function render_user_table($user_list) {
?>
    <div class="table-responsive">
        <table class="table table-bordered table-striped table-hover align-middle mb-0">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Balance</th>
                    <th>Status</th>
                    <th class="text-center">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($user_list)): ?>
                    <tr><td colspan="6" class="text-center text-muted p-4">No users found in this list.</td></tr>
                <?php else: foreach ($user_list as $u): ?>
                    <tr>
                        <td>#<?php echo $u['id']; ?></td>
                        <td><?php echo h($u['name']); ?></td>
                        <td><strong><?php echo h($u['email']); ?></strong></td>
                        <td class="fw-bold text-theme">৳ <?php echo number_format($u['balance'], 2); ?></td>
                        <td>
                            <?php if ($u['is_blocked']): ?><span class="badge bg-danger">Blocked</span><?php else: ?><span class="badge bg-success">Active</span><?php endif; ?>
                        </td>
                        <td class="text-center">
                            <button type="button" class="btn btn-sm btn-theme text-white shadow-sm" data-bs-toggle="modal" data-bs-target="#balanceModal_<?php echo $u['id']; ?>">
                                <i class="bi bi-currency-dollar me-1"></i> Balance
                            </button>
                            
                            <form method="post" class="d-inline">
                                <?php csrf_field(); ?>
                                <input type="hidden" name="uid" value="<?php echo $u['id']; ?>">
                                <?php if ($u['is_blocked']): ?>
                                    <button name="toggle_block" class="btn btn-sm btn-success shadow-sm" title="Unblock"><i class="bi bi-check-circle-fill"></i></button>
                                <?php else: ?>
                                    <button name="toggle_block" class="btn btn-sm btn-warning shadow-sm" title="Block"><i class="bi bi-slash-circle-fill"></i></button>
                                <?php endif; ?>
                            </form>

                            <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 shadow-sm" onclick="return confirm('Delete this user?')">
                                    <i class="bi bi-trash-fill"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
<?php
}
?>

<?php 
$all_displayed_users = array_merge($users_with_balance, $users_no_balance);
foreach ($all_displayed_users as $u): ?>
<div class="modal fade" id="balanceModal_<?php echo $u['id']; ?>" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Balance Control: <?php echo h($u['name']); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post">
                <?php csrf_field(); ?>
                <input type="hidden" name="uid" value="<?php echo $u['id']; ?>">
                <div class="modal-body p-4 text-center">
                    <p class="mb-1 text-muted small">Current Balance</p>
                    <h2 class="fw-bold text-theme">৳ <?php echo number_format($u['balance'], 2); ?></h2>
                    <hr>
                    <div class="mb-3 text-start">
                        <label class="form-label fw-bold small">Enter Amount</label>
                        <input type="number" step="0.01" class="form-control form-control-lg" name="amount" placeholder="0.00" required>
                    </div>
                    <div class="mb-3 text-start">
                        <label class="form-label fw-bold small">Select Action</label>
                        <select class="form-select" name="action">
                            <option value="add" selected>Add Balance (+)</option>
                            <option value="remove">Remove Balance (-)</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" name="update_balance" class="btn btn-theme px-4 shadow-sm">Confirm Update</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endforeach; ?>

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