<?php
// admin/users.php

// -------------------- DEBUG --------------------
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
// Path check logic
if (file_exists("includes/config.php")) {
    require_once "includes/config.php";
} else {
    require_once "../includes/config.php";
}

// -------------------- AUTH CHECK --------------------
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}

// -------------------- ACTIONS (Block / Unblock / Login As) --------------------
if (isset($_GET['action'], $_GET['id'])) {
    $action = $_GET['action'];
    $user_id = (int)$_GET['id'];

    if ($user_id > 0) {
        // 1. LOGIN AS USER LOGIC
        if ($action === 'login_as') {
            date_default_timezone_set('Asia/Kolkata');
            $stmt = $conn->prepare("SELECT id FROM users WHERE id=?");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $res = $stmt->get_result();
            
            if ($user = $res->fetch_assoc()) {
                $token = bin2hex(random_bytes(32)); 
                $expires_at = date("Y-m-d H:i:s", strtotime("+10 minutes"));

                $stmt2 = $conn->prepare("INSERT INTO admin_login_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
                $stmt2->bind_param("iss", $user_id, $token, $expires_at);
                
                if($stmt2->execute()){
                    // 🔥 YAHAN DOUBLE SLASH (//) FIX KIYA GAYA HAI 🔥
                   $user_site_url = "https://jkm70x.long-term-application.com/user_login_handler";
                    header("Location: " . $user_site_url . "?token=" . $token); 
                    exit();
                } else {
                    echo "<script>alert('Error generating login token'); window.location.href='users.php';</script>";
                }
            }
        }

        // 2. BLOCK / UNBLOCK LOGIC
        elseif (in_array($action, ['block', 'unblock'])) {
            $stmt = $conn->prepare("SELECT mobile FROM users WHERE id=?");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $res = $stmt->get_result();
            $user = $res->fetch_assoc();
            $stmt->close();

            if ($user) {
                $newStatus = ($action === 'block') ? 'blocked' : 'active';
                $stmt = $conn->prepare("UPDATE users SET status=? WHERE id=?");
                $stmt->bind_param("si", $newStatus, $user_id);
                $stmt->execute();
                $stmt->close();

                if (isset($redis)) {
                    $cacheKey = "login_user_" . $user['mobile'];
                    $redis->del($cacheKey);
                }
            }
            header("Location: users.php");
            exit();
        }
    }
}

// -------------------- SEARCH LOGIC --------------------
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$searchQuery = "";

if (!empty($search)) {
    $safe_search = $conn->real_escape_string($search);
    // Searching by ID, Mobile, or IP Address
    $searchQuery = " WHERE id = '$safe_search' OR mobile LIKE '%$safe_search%' OR register_ip LIKE '%$safe_search%' ";
}

// -------------------- FETCH USERS --------------------
// Added register_ip and last_activity to the SELECT query
$sql = "SELECT id, mobile, income_balance, bonus_balance, deposit_balance, status, created_at, register_ip, last_activity 
        FROM users $searchQuery ORDER BY id DESC";
$result = $conn->query($sql);

if (!$result) {
    die("DB Error: " . $conn->error);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage Users</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
body{font-family:Segoe UI,Tahoma;background:#f4f6fb;margin:0}
.header{display:flex;justify-content:space-between;align-items:center;background:linear-gradient(90deg,#0047ab,#2196f3);color:#fff;padding:14px 20px}
.back-btn{background:#ff9800;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none;font-weight:bold}

/* Search Box Styles */
.search-container { width: 96%; margin: 20px auto 0 auto; display: flex; justify-content: flex-end; }
.search-input { padding: 10px; border: 1px solid #ccc; border-radius: 6px 0 0 6px; width: 300px; outline: none; font-size:14px;}
.search-btn { padding: 10px 15px; background: #0047ab; color: white; border: none; border-radius: 0 6px 6px 0; cursor: pointer; font-size:14px;}
.clear-btn { padding: 10px 15px; background: #e74c3c; color: white; text-decoration: none; border-radius: 6px; margin-left: 10px; font-weight:bold; font-size:14px;}

.table-container{width:96%;margin:20px auto;background:#fff;border-radius:14px;box-shadow:0 4px 16px rgba(0,0,0,.1);overflow-x:auto;}
table{width:100%;border-collapse:collapse;min-width: 900px;}
th,td{padding:14px;text-align:center; white-space: nowrap;}
th{background:#003366;color:#fff}
tr:nth-child(even){background:#f9fbff}
.badge{padding:6px 12px;border-radius:20px;font-weight:bold}
.badge.active{background:#d4edda;color:#155724}
.badge.blocked{background:#f8d7da;color:#721c24}

/* Online/Offline Styles */
.online{color:green;font-weight:bold;}
.offline{color:#777;font-weight:bold;}

/* Buttons */
.btn{padding:6px 12px;border-radius:6px;border:none;font-weight:bold;cursor:pointer; margin: 2px;}
.block{background:#e74c3c;color:#fff}
.unblock{background:#27ae60;color:#fff}
.edit{background:#2980b9;color:#fff}
.login-as{background:#8e44ad;color:#fff; box-shadow: 0 2px 5px rgba(142, 68, 173, 0.4);}
</style>
</head>

<body>

<div class="header">
  <a href="dashboard.php" class="back-btn"><i class="fa-solid fa-arrow-left"></i> Back</a>
  <h2><i class="fa-solid fa-users"></i> Manage Users</h2>
</div>

<div class="search-container">
    <form method="GET" action="users.php" style="display:flex;">
        <input type="text" name="search" class="search-input" placeholder="Search ID, Mobile, or IP Address..." value="<?= htmlspecialchars($search) ?>">
        <button type="submit" class="search-btn"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
        <?php if(!empty($search)): ?>
            <a href="users.php" class="clear-btn">Clear</a>
        <?php endif; ?>
    </form>
</div>

<div class="table-container">
<table>
<thead>
<tr>
  <th>ID</th>
  <th>Mobile</th>
  <th>IP Address</th> 
  <th>Total Balance</th>
  <th>Status</th>
  <th>Online</th> <th>Created</th>
  <th>Action</th>
</tr>
</thead>
<tbody>

<?php 
if($result->num_rows > 0):
    while($row = $result->fetch_assoc()): 
        // Logic: income + bonus + deposit
        $total = ($row['income_balance'] ?? 0) + ($row['bonus_balance'] ?? 0) + ($row['deposit_balance'] ?? 0);
        
        // Online/Offline Logic Check (Activity within last 120 seconds)
        $online = false;
        if(!empty($row['last_activity'])){
            $last = strtotime($row['last_activity']);
            if(time() - $last < 120){
                $online = true;
            }
        }
?>
<tr>
  <td><?= $row['id'] ?></td>
  <td><?= htmlspecialchars($row['mobile']) ?></td>
  <td><?= htmlspecialchars($row['register_ip'] ?? 'N/A') ?></td> 
  <td style="font-weight:bold; color:#0047ab;">₹<?= number_format($total, 2) ?></td>
  <td>
    <?php if($row['status']=='blocked'): ?>
        <span class="badge blocked">Blocked</span>
    <?php else: ?>
        <span class="badge active">Active</span>
    <?php endif; ?>
  </td>
  
  <td>
    <?php if($online): ?>
        <span class="online">🟢 Online</span>
    <?php else: ?>
        <span class="offline">⚫ Offline</span>
    <?php endif; ?>
  </td>
  
  <td><?= date("d M, Y", strtotime($row['created_at'])) ?></td>
  <td>
    <a href="user_edit.php?id=<?= $row['id'] ?>"><button class="btn edit"><i class="fa-solid fa-pen"></i></button></a>

    <a href="?action=login_as&id=<?= $row['id'] ?>" target="_blank" title="Login as User">
        <button class="btn login-as"><i class="fa-solid fa-right-to-bracket"></i> Login</button>
    </a>

    <?php if($row['status']=='blocked'): ?>
        <a href="?action=unblock&id=<?= $row['id'] ?>" onclick="return confirm('Unblock this user?')">
            <button class="btn unblock">Unblock</button>
        </a>
    <?php else: ?>
        <a href="?action=block&id=<?= $row['id'] ?>" onclick="return confirm('Block this user?')">
            <button class="btn block">Block</button>
        </a>
    <?php endif; ?>
  </td>
</tr>
<?php 
    endwhile; 
else: 
?>
<tr>
    <td colspan="8" style="color:red; font-weight:bold;">No users found.</td>
</tr>
<?php endif; ?>

</tbody>
</table>
</div>

</body>
</html>