<?php
// =====================================================
// GET  /users.php?limit=20&page=1  → list users (paginated)
// POST /users.php                  → edit/update user
// =====================================================
require_once 'config.php';

$conn = getConnection();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // ---- Paginated user list ----
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
    $page  = isset($_GET['page'])  ? (int)$_GET['page']  : 1;
    if ($page < 1) $page = 1;
    $offset = ($page - 1) * $limit;

    $stmt = $conn->prepare("SELECT id, recharge_id, user_id, username, name, address, phone FROM users ORDER BY id DESC LIMIT ? OFFSET ?");
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
    $result = $stmt->get_result();

    $users = [];
    while ($row = $result->fetch_assoc()) {
        $users[] = [
            "id"          => (string)$row['id'],
            "recharge_id" => $row['recharge_id'],
            "user_id"     => $row['user_id'],
            "username"    => $row['username'],
            "name"        => $row['name'],
            "address"     => $row['address'],
            "phone"       => $row['phone']
        ];
    }

    echo json_encode($users);
    $stmt->close();
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // ---- Update user ----
    $id          = $_POST['id']          ?? '';
    $recharge_id = $_POST['recharge_id'] ?? '';
    $user_id     = $_POST['user_id']     ?? '';
    $username    = $_POST['username']    ?? '';
    $name        = $_POST['name']        ?? '';
    $address     = $_POST['address']     ?? '';
    $phone       = $_POST['phone']       ?? '';

    $stmt = $conn->prepare("UPDATE users SET recharge_id=?, user_id=?, username=?, name=?, address=?, phone=? WHERE id=?");
    $stmt->bind_param("ssssssi", $recharge_id, $user_id, $username, $name, $address, $phone, $id);

    if ($stmt->execute()) {
        echo "User updated successfully!";
    } else {
        echo "Failed to update user";
    }
    $stmt->close();
}

$conn->close();
