<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require_once 'db.php';

// ✅ Hakikisha admin ame-login
if (!isset($_SESSION['user_id'])) {
    die("Access denied");
}

// ================== HANDLE UPDATE ==================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_user'])) {
    $id       = intval($_POST['id']);
    $phone    = $_POST['phone'] ?? '';
    $balance  = floatval($_POST['balance']);
    $password = $_POST['password'] ?? '';

    if ($password !== '') {
        // Hash new password
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $conn->prepare("UPDATE users SET phone=?, balance=?, password=? WHERE id=?");
        $stmt->bind_param("sdsi", $phone, $balance, $hashed, $id);
    } else {
        // Bila password
        $stmt = $conn->prepare("UPDATE users SET phone=?, balance=? WHERE id=?");
        $stmt->bind_param("sdi", $phone, $balance, $id);
    }

    if ($stmt->execute()) {
        echo "<script>alert('User updated successfully'); window.location='admin_users.php';</script>";
        exit;
    } else {
        echo "<script>alert('Update failed');</script>";
    }
}

// ================== HANDLE EDIT MODE ==================
$editUser = null;
if (isset($_GET['edit'])) {
    $editId = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT id, phone, balance, referred_by, invite_code, referral_earnings, income FROM users WHERE id = ?");
    $stmt->bind_param("i", $editId);
    $stmt->execute();
    $editUser = $stmt->get_result()->fetch_assoc();
}

// ================== HANDLE LOGIN AS USER ==================
if (isset($_GET['login_as'])) {
    $target_id = intval($_GET['login_as']);
    $stmt = $conn->prepare("SELECT id, phone FROM users WHERE id=?");
    $stmt->bind_param("i", $target_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        // Hifadhi admin original
        $_SESSION['impersonate_admin'] = $_SESSION['user_id'];
        $_SESSION['user_id'] = $row['id'];
        $_SESSION['phone']   = $row['phone']; // ✅ weka pia phone

        header("Location: me.php"); 
        exit;
    } else {
        echo "<script>alert('User not found');</script>";
    }
}

// ================== HANDLE STOP IMPERSONATE ==================
if (isset($_GET['stop_impersonate'])) {
    if (isset($_SESSION['impersonate_admin'])) {
        // Rudisha admin original
        $admin_id = $_SESSION['impersonate_admin'];
        unset($_SESSION['impersonate_admin']);

        // Pata tena phone ya admin
        $stmt = $conn->prepare("SELECT phone FROM users WHERE id=?");
        $stmt->bind_param("i", $admin_id);
        $stmt->execute();
        $stmt->bind_result($admin_phone);
        $stmt->fetch();
        $stmt->close();

        $_SESSION['user_id'] = $admin_id;
        $_SESSION['phone']   = $admin_phone;
    }
    header("Location: admin_users.php");
    exit;
}

// ================== HANDLE BLOCK USER ==================
if (isset($_GET['block'])) {
    $blockId = intval($_GET['block']);
    $stmt = $conn->prepare("UPDATE users SET status='blocked' WHERE id=?");
    $stmt->bind_param("i", $blockId);
    $stmt->execute();
    header("Location: admin_users.php");
    exit;
}

// ================== HANDLE UNBLOCK USER ==================
if (isset($_GET['unblock'])) {
    $unblockId = intval($_GET['unblock']);
    $stmt = $conn->prepare("UPDATE users SET status='active' WHERE id=?");
    $stmt->bind_param("i", $unblockId);
    $stmt->execute();
    header("Location: admin_users.php");
    exit;
}

// ================== GET ALL USERS ==================
$results = $conn->query("SELECT id, phone, balance, referred_by, invite_code, referral_earnings, income, created_at, status FROM users ORDER BY id DESC");
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Admin - Manage Users</title>
  <style>
    body { font-family: Arial, sans-serif; padding:20px; background:#f7f7f7; }
    h2 { text-align:center; margin-bottom:20px; }
    table { width:100%; border-collapse:collapse; background:#fff; }
    th, td { padding:10px; border:1px solid #ddd; text-align:left; font-size:14px; vertical-align:top; }
    th { background:#f0f0f0; }
    .btn {
      padding:6px 10px;
      border-radius:4px;
      text-decoration:none;
      font-size:13px;
      color:#fff;
      display:inline-block;
    }
    .edit { background:#007bff; }
    .login { background:#28a745; }
    .back { background:#6c757d; }
    .block { background:#dc3545; }
    .unblock { background:#17a2b8; }
    .btn-group {
      display:flex;
      flex-wrap:wrap;
      gap:6px;
    }
    form { background:#fff; padding:20px; border-radius:8px; max-width:500px; margin:0 auto 20px auto; box-shadow:0 2px 6px rgba(0,0,0,0.1); }
    label { display:block; margin-top:12px; font-weight:bold; }
    input { width:100%; padding:8px; margin-top:4px; border:1px solid #ccc; border-radius:6px; }
    button { margin-top:16px; padding:10px 14px; border:none; border-radius:6px; cursor:pointer; background:#28a745; color:#fff; font-size:15px; }
  </style>
</head>
<body>

<h2>Admin Panel - Manage Users</h2>

<?php if (isset($_SESSION['impersonate_admin'])): ?>
  <p style="text-align:center;">
    <a href="admin_users.php?stop_impersonate=1" class="btn back">Return to Admin</a>
  </p>
<?php endif; ?>

<?php if ($editUser): ?>
  <form method="post">
    <h3>Edit User #<?= $editUser['id'] ?></h3>
    <input type="hidden" name="id" value="<?= $editUser['id'] ?>">

    <label>Phone</label>
    <input type="text" name="phone" value="<?= htmlspecialchars($editUser['phone']) ?>">

    <label>Balance</label>
    <input type="number" step="0.01" name="balance" value="<?= $editUser['balance'] ?>">

    <label>New Password (leave blank to keep current)</label>
    <input type="password" name="password">

    <button type="submit" name="update_user">Save Changes</button>
    <br><br>
    <a href="admin_users.php" class="btn back">Back</a>
  </form>
<?php else: ?>
  <table>
    <tr>
      <th>ID</th>
      <th>Phone</th>
      <th>Balance</th>
      <th>Referred By</th>
      <th>Invite Code</th>
      <th>Referral Earnings</th>
      <th>Income</th>
      <th>Created</th>
      <th>Status</th>
      <th>Action</th>
    </tr>
    <?php while ($row = $results->fetch_assoc()): ?>
      <tr>
        <td><?= $row['id'] ?></td>
        <td><?= htmlspecialchars($row['phone']) ?></td>
        <td><?= number_format($row['balance'],2) ?></td>
        <td><?= htmlspecialchars($row['referred_by']) ?></td>
        <td><?= htmlspecialchars($row['invite_code']) ?></td>
        <td><?= number_format($row['referral_earnings'],2) ?></td>
        <td><?= number_format($row['income'],2) ?></td>
        <td><?= $row['created_at'] ?></td>
        <td><?= $row['status'] ?></td>
        <td>
          <div class="btn-group">
            <a href="admin_users.php?edit=<?= $row['id'] ?>" class="btn edit">Edit</a>
            <a href="admin_users.php?login_as=<?= $row['id'] ?>" class="btn login">Login As</a>
            <?php if ($row['status'] === 'active'): ?>
              <a href="admin_users.php?block=<?= $row['id'] ?>" class="btn block">Block</a>
            <?php else: ?>
              <a href="admin_users.php?unblock=<?= $row['id'] ?>" class="btn unblock">Unblock</a>
            <?php endif; ?>
          </div>
        </td>
      </tr>
    <?php endwhile; ?>
  </table>
<?php endif; ?>

</body>
</html>
