<?php
include('../includes/session.php');
include('../includes/config.php');
if (!checkAdmin($udata['type'])) {
    echo '<script>window.location="index.php";</script>';
    die();
}

// ===== SELF-HEAL: Ensure wallet-related tables + columns exist (like trick_buy_common pattern) =====
function _v2EnsureWalletSchema($conn) {
    if (!$conn) return;
    static $done = null;
    if ($done === true) return;
    @mysqli_report(MYSQLI_REPORT_OFF);

    // 1) wallet table
    @mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `wallet` (
      `id` INT NOT NULL AUTO_INCREMENT,
      `phone` VARCHAR(255) NULL,
      `amount` VARCHAR(255) NULL,
      `txn_id` VARCHAR(255) NULL,
      `date` VARCHAR(255) NULL,
      `txn_date` DATETIME NULL DEFAULT CURRENT_TIMESTAMP(),
      `email` VARCHAR(255) NULL,
      `PAYMENTMODE` VARCHAR(255) NULL,
      `RESPMSG` VARCHAR(255) NULL,
      `BANKTXNID` VARCHAR(255) NULL,
      `status` ENUM('pending','success','rejected') NOT NULL DEFAULT 'pending',
      PRIMARY KEY (`id`), KEY `idx_wallet_txn` (`txn_id`), KEY `idx_wallet_phone` (`phone`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $cols = [];
    $r = @mysqli_query($conn, "SHOW COLUMNS FROM wallet");
    if ($r) while ($row = mysqli_fetch_assoc($r)) $cols[] = $row['Field'];
    $add = function($n, $d) use ($conn, $cols) { if (!in_array($n, $cols, true)) @mysqli_query($conn, "ALTER TABLE wallet ADD COLUMN {$n} {$d}"); };
    $add('txn_date', "DATETIME NULL DEFAULT CURRENT_TIMESTAMP()");
    $add('PAYMENTMODE', "VARCHAR(255) NULL");
    $add('BANKTXNID', "VARCHAR(255) NULL");
    $add('RESPMSG', "VARCHAR(255) NULL");
    $add('email', "VARCHAR(255) NULL");
    $add('status', "ENUM('pending','success','rejected') NOT NULL DEFAULT 'pending'");

    // 2) wallet_transactions table (goodprintportal_good.sql standard)
    @mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `wallet_transactions` (
      `id` INT NOT NULL AUTO_INCREMENT,
      `order_id` VARCHAR(64) NOT NULL,
      `session_id` VARCHAR(128) NULL,
      `phone` VARCHAR(255) NULL,
      `email` VARCHAR(255) NULL,
      `amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00,
      `txn_status` VARCHAR(32) NOT NULL DEFAULT 'PENDING',
      `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP(),
      PRIMARY KEY (`id`), KEY `idx_wt_order` (`order_id`), KEY `idx_wt_phone` (`phone`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $cols2 = [];
    $r2 = @mysqli_query($conn, "SHOW COLUMNS FROM wallet_transactions");
    if ($r2) while ($row = mysqli_fetch_assoc($r2)) $cols2[] = $row['Field'];
    $add2 = function($n, $d) use ($conn, $cols2) { if (!in_array($n, $cols2, true)) @mysqli_query($conn, "ALTER TABLE wallet_transactions ADD COLUMN {$n} {$d}"); };
    $add2('session_id', "VARCHAR(128) NULL");
    $add2('email', "VARCHAR(255) NULL");

    // 3) wallethistory table (older deployments log all debits here)
    @mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `wallethistory` (
      `id` INT NOT NULL AUTO_INCREMENT,
      `userid` VARCHAR(255) NULL,
      `amount` VARCHAR(255) NULL,
      `balance` VARCHAR(255) NULL,
      `purpose` VARCHAR(255) NULL,
      `status` VARCHAR(255) NULL,
      `type` VARCHAR(255) NULL,
      `date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP(),
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    // 4) transactions table (older deployments — optional, no fail if missing)
    @mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `transactions` (
      `id` INT NOT NULL AUTO_INCREMENT,
      `uid` INT NULL,
      `amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00,
      `description` TEXT NULL,
      `txn_ref` VARCHAR(128) NULL,
      `date` DATETIME NULL,
      `status` VARCHAR(32) NULL DEFAULT 'success',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $done = true;
}
_v2EnsureWalletSchema($ahk_conn);

// ====== ACTION HANDLERS ======
$actionMsg = '';
$actionType = '';

// 1. Delete User
if (isset($_GET['deleteuser']) && $_GET['deleteuser'] == 1 && !empty($_GET['id'])) {
    $id = (int)base64_decode(getSafe($_GET['id']));
    if (ahkQuery("DELETE FROM users WHERE id='$id'")) {
        $actionMsg = 'User Deleted Successfully';
        $actionType = 'success';
    } else {
        $actionMsg = 'User Delete Failed: ' . mysqli_error($ahk_conn);
        $actionType = 'error';
    }
}

// 2. Ban / Block User (status=0)
if (isset($_GET['banid']) && !empty($_GET['banid']) && isset($_GET['ban']) && $_GET['ban'] == '1') {
    $banid = (int)base64_decode(getSafe($_GET['banid']));
    if (ahkQuery("UPDATE users SET status='0' WHERE id='$banid'")) {
        $actionMsg = 'User Banned/Blocked Successfully';
        $actionType = 'success';
    } else {
        $actionMsg = 'Ban Failed';
        $actionType = 'error';
    }
}

// 3. Activate / Unblock User (status=1)
if (isset($_GET['apid']) && !empty($_GET['apid']) && isset($_GET['approve']) && $_GET['approve'] == '1') {
    $apid = (int)base64_decode(getSafe($_GET['apid']));
    if (ahkQuery("UPDATE users SET status='1' WHERE id='$apid'")) {
        $actionMsg = 'User Activated/Unblocked Successfully';
        $actionType = 'success';
    } else {
        $actionMsg = 'Activation Failed';
        $actionType = 'error';
    }
}

// 4. Reset Password
if (isset($_GET['reset']) && $_GET['reset'] == 1 && !empty($_GET['id'])) {
    $id = (int)base64_decode(getSafe($_GET['id']));
    $vpass = rand(0, 999999);
    $vpassStr = str_pad($vpass, 6, '0', STR_PAD_LEFT);
    $pass = password_hash($vpassStr, PASSWORD_DEFAULT);
    if (ahkQuery("UPDATE users SET password='$pass' WHERE id='$id'")) {
        $actionMsg = 'Password Reset Done. New Password: ' . $vpassStr . ' (Save it!)';
        $actionType = 'success';
    } else {
        $actionMsg = 'Password Reset Failed';
        $actionType = 'error';
    }
}

// 5. Login As User
if (isset($_GET['login']) && $_GET['login'] == 1 && !empty($_GET['phone'])) {
    $phone = base64_decode(getSafe($_GET['phone']));
    $_SESSION['adminasuser'] = true;
    $_SESSION['adminusername'] = $_SESSION['phone'];
    $_SESSION['phone'] = $phone;
    echo '<script>window.location="../index.php";</script>';
    die();
}

// 6. POST: Credit / Debit wallet balance
if (isset($_POST['bd_action']) && !empty($_POST['user_id']) && !empty($_POST['bd_amount'])) {
    try {
        $user_id = (int)getSafe($_POST['user_id']);
        $amount = (float)getSafe($_POST['bd_amount']);
        $note = getSafe($_POST['bd_note'] ?? 'Admin manual');
        $bd_action = getSafe($_POST['bd_action']); // credit/debit

        if ($amount <= 0) {
            $actionMsg = 'Amount must be greater than 0';
            $actionType = 'error';
        } else {
            $user = fetchRow("SELECT id, phone, balance, name, type, email FROM users WHERE id='$user_id'");
            if (!$user) {
                $actionMsg = 'User not found';
                $actionType = 'error';
            } else {
                $phone = $user['phone'];
                $uName = $user['name'];
                $curBal = (float)$user['balance'];
                $ok = true;
                if (function_exists('mysqli_begin_transaction')) {
                    mysqli_begin_transaction($ahk_conn);
                } else {
                    ahkQuery("START TRANSACTION");
                }

                $deltaAbs = abs($amount);
                $txnType = 'Admin Credit';
                $deltaTxn = $deltaAbs;
                if ($bd_action === 'credit') {
                    $ok = $ok && ahkQuery("UPDATE users SET balance = balance + $deltaAbs WHERE id='$user_id'");
                    $newBal = $curBal + $deltaAbs;
                } else {
                    if ($curBal < $deltaAbs) {
                        if (function_exists('mysqli_rollback')) @mysqli_rollback($ahk_conn); else ahkQuery("ROLLBACK");
                        $actionMsg = 'Debit FAILED: Insufficient wallet balance. User has Rs.' . number_format($curBal,2) . ' but requested Rs.' . number_format($deltaAbs,2);
                        $actionType = 'error';
                        $ok = false;
                    } else {
                        $ok = $ok && ahkQuery("UPDATE users SET balance = balance - $deltaAbs WHERE id='$user_id'");
                        $txnType = 'Admin Debit';
                        $deltaTxn = -1 * abs($deltaAbs);
                        $newBal = $curBal - $deltaAbs;
                    }
                }
                $txnRef = 'ADMIN-' . strtoupper(substr(md5(uniqid((string)mt_rand() . $user_id, true)), 0, 10));
                $desc = $txnType . ' Rs.' . number_format($deltaAbs, 2) . ' | By: ' . $udata['name'] . ' | Note: ' . $note . ' | User: ' . $uName . ' (' . $phone . ')';

                // TRY to log in transactions -> wallet_transactions -> wallethistory. ANY success = $logged=true. Never fail op.
                if ($ok) {
                    $logged = false;
                    // 1) transactions (older deployments)
                    $st = @mysqli_prepare($ahk_conn, "INSERT INTO transactions (uid, amount, description, txn_ref, date, status) VALUES (?, ?, ?, ?, NOW(), 'success')");
                    if ($st) { @mysqli_stmt_bind_param($st, 'idss', $user_id, $deltaTxn, $desc, $txnRef); if (@mysqli_stmt_execute($st)) $logged = true; @mysqli_stmt_close($st); }
                    // 2) wallet_transactions (goodprintportal standard)
                    if (!$logged) {
                        $st2 = @mysqli_prepare($ahk_conn, "INSERT INTO wallet_transactions (order_id, session_id, phone, email, amount, txn_status, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
                        if ($st2) {
                            $sess = session_id() ?: ('adm_' . $txnRef);
                            $em = $user['email'] ?? '';
                            $stat = strtoupper(str_replace('Admin ', '', $txnType));
                            @mysqli_stmt_bind_param($st2, 'ssssds', $txnRef, $sess, $phone, $em, $deltaTxn, $stat);
                            if (@mysqli_stmt_execute($st2)) $logged = true;
                            @mysqli_stmt_close($st2);
                        }
                    }
                    // 3) wallethistory (legacy scripts read debits from here)
                    if (!$logged || true) {
                        $whType = ($bd_action === 'credit') ? 'Credit' : 'Debit';
                        $whAmt = number_format($deltaAbs, 2, '.', '');
                        $whBal = isset($newBal) ? number_format($newBal, 2, '.', '') : $curBal;
                        $whPurpose = $txnType . ' - ' . $note . ' (Ref: ' . $txnRef . ')';
                        $whStatus = '1';
                        $st3 = @mysqli_prepare($ahk_conn, "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type, date) VALUES (?, ?, ?, ?, ?, ?, NOW())");
                        if ($st3) {
                            $uidStr = (string)$user_id;
                            @mysqli_stmt_bind_param($st3, 'ssssss', $uidStr, $whAmt, $whBal, $whPurpose, $whStatus, $whType);
                            @mysqli_stmt_execute($st3);
                            @mysqli_stmt_close($st3);
                            $logged = true;
                        }
                    }
                }

                if ($ok) {
                    if (function_exists('mysqli_commit')) {
                        @mysqli_commit($ahk_conn);
                    } else {
                        ahkQuery("COMMIT");
                    }
                    $actionMsg = $txnType . ' of Rs.' . number_format($deltaAbs, 2) . ' done for user ' . htmlspecialchars($uName) . ' (' . htmlspecialchars($phone) . ')';
                    $actionType = 'success';
                } else {
                    if (function_exists('mysqli_rollback')) {
                        @mysqli_rollback($ahk_conn);
                    } else {
                        ahkQuery("ROLLBACK");
                    }
                    $dbErr = mysqli_error($ahk_conn);
                    $actionMsg = 'Wallet operation failed: ' . ($dbErr ? $dbErr : 'Unknown DB error');
                    $actionType = 'error';
                }
            }
        }
    } catch (Throwable $e) {
        $actionMsg = 'Server Error: ' . $e->getMessage() . ' (File: ' . basename($e->getFile()) . ':' . $e->getLine() . ')';
        $actionType = 'error';
    }
}

include('../template/ahkweb/header.php');
if ($actionMsg) {
    showAlert($actionMsg, '', $actionType);
}
?>
<style>
.bd-form { display:flex; gap:6px; align-items:center; justify-content:center; flex-wrap:wrap; }
.bd-form input, .bd-form select { padding:5px 8px; font-size:12px; border-radius:6px; border:1px solid #ddd; min-width:80px; }
.bd-form button { padding:5px 12px; font-size:12px; border-radius:6px; border:0; cursor:pointer; font-weight:600; }
.btn-credit { background:#28a745; color:#fff; }
.btn-debit { background:#dc3545; color:#fff; }
.act-wrap { display:flex; gap:10px; align-items:center; justify-content:center; flex-wrap:wrap; }
.act-wrap a, .act-wrap button { font-size:22px; padding:4px 8px; border-radius:8px; text-decoration:none; }
.badge-wallet { display:inline-block; padding:4px 10px; border-radius:10px; background:#e3f2fd; color:#1565c0; font-weight:700; }
.badge-status { padding:4px 10px; border-radius:10px; font-weight:700; }
.bs-active { background:#d4edda; color:#155724; }
.bs-block { background:#f8d7da; color:#721c24; }
</style>

<div class="page-wrapper">
    <div class="page-content">
        <div class="card radius-10">
            <div class="card-body">
                <div class="d-flex align-items-center justify-content-between flex-wrap">
                    <div>
                        <h5 class="mb-0">👥 All Users List (Admin v2)</h5>
                        <p class="text-muted mb-0">Credit / Debit balance, Block / Unblock, Delete users, Reset password, Login as user</p>
                    </div>
                    <a href="adduser.php" class="btn btn-primary btn-sm">+ Add New User</a>
                </div>
                <hr>
                <div class="table-responsive">
                    <table id="example2" class="table align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="text-center">SL</th>
                                <th class="text-center">Phone / Username</th>
                                <th class="text-center">Name</th>
                                <th class="text-center">Email</th>
                                <th class="text-center">Type</th>
                                <th class="text-center">Status</th>
                                <th class="text-center">Balance</th>
                                <th class="text-center">Credit / Debit</th>
                                <th class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php
                        $res = ahkQuery("SELECT id, phone, name, email, type, status, balance FROM users ORDER BY id DESC");
                        if (mysqli_num_rows($res) > 0) {
                            $x = 0;
                            while ($data = mysqli_fetch_assoc($res)) {
                                if (strtolower($data['type']) === 'admin') continue; // skip admin accounts
                                $x++;
                                $bal = (float)($data['balance'] ?? 0);
                                $active = ((string)$data['status'] === '1');
                        ?>
                            <tr>
                                <td class="text-center"><?= $x ?></td>
                                <td class="text-center"><strong><?= htmlspecialchars($data['phone']) ?></strong></td>
                                <td class="text-center"><?= htmlspecialchars($data['name']) ?></td>
                                <td class="text-center"><?= htmlspecialchars($data['email']) ?></td>
                                <td class="text-center"><span class="badge bg-info"><?= strtoupper(htmlspecialchars($data['type'])) ?></span></td>
                                <td class="text-center">
                                    <?php if ($active) { ?>
                                        <span class="badge-status bs-active">ACTIVE</span>
                                    <?php } else { ?>
                                        <span class="badge-status bs-block">BLOCKED</span>
                                    <?php } ?>
                                </td>
                                <td class="text-center"><span class="badge-wallet">₹<?= number_format($bal, 2) ?></span></td>
                                <td class="text-center">
                                    <form class="bd-form" method="POST">
                                        <input type="hidden" name="user_id" value="<?= (int)$data['id'] ?>">
                                        <input type="number" name="bd_amount" min="1" step="0.01" placeholder="Amount ₹" required>
                                        <input type="text" name="bd_note" placeholder="Note (optional)">
                                        <select name="bd_action" required>
                                            <option value="credit">Credit +</option>
                                            <option value="debit">Debit -</option>
                                        </select>
                                        <button type="submit" class="btn-credit" onclick="if(this.form.bd_action.value==='debit'){this.classList.remove('btn-credit');this.classList.add('btn-debit');}else{this.classList.add('btn-credit');this.classList.remove('btn-debit');}return true;">GO</button>
                                    </form>
                                </td>
                                <td class="text-center">
                                    <div class="act-wrap">
                                        <a class="bg-light-success text-success" title="Login as user" href="?phone=<?= base64_encode($data['phone']) ?>&login=1">👤</a>
                                        <a class="bg-light-success text-success" title="Reset password" href="?id=<?= base64_encode($data['id']) ?>&reset=1">🔄</a>
                                        <a class="bg-light-success text-success" title="Edit user" href="EditUser.php?id=<?= base64_encode($data['id']) ?>">✏️</a>
                                        <a class="bg-light-primary text-primary" title="Balance transfer to this user" href="BalanceTransfer.php?username=<?= urlencode($data['email']) ?>">💸</a>
                                        <?php if (!$active) { ?>
                                            <a class="bg-light-success text-success" title="Activate / Unblock" href="?apid=<?= base64_encode($data['id']) ?>&approve=1">✅</a>
                                        <?php } else { ?>
                                            <a class="bg-light-danger text-danger" title="Block / Ban user" href="?banid=<?= base64_encode($data['id']) ?>&ban=1">🚫</a>
                                        <?php } ?>
                                        <a class="bg-light-danger text-danger" title="Delete user permanently" href="?deleteuser=1&id=<?= base64_encode($data['id']) ?>" onclick="return confirm('Permanently DELETE user? This cannot be undone.');">🗑️</a>
                                    </div>
                                </td>
                            </tr>
                        <?php
                            }
                        }
                        ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
include('../template/ahkweb/footer.php');
?>
<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/js/jquery.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/dataTables.bootstrap5.min.js"></script>
<script>
$(document).ready(function() {
    var table = $('#example2').DataTable({ lengthChange: false, buttons: ['copy', 'excel', 'pdf', 'print'], pageLength: 25 });
    table.buttons().container().appendTo('#example2_wrapper .col-md-6:eq(0)');
});
</script>
</body>
</html>
