<?php
require_once '../config.php';
require_once '../middleware.php';

### API Blueprint: /admin/users
# GET /admin/users?action=list
# Description: Lists all users.
# Headers:
#   - Authorization: Bearer <token>
# Parameters:
#   - action: string (required, value: list)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Users fetched",
#       "data": {
#         "users": [
#           {
#             "id": 1,
#             "email": "user@example.com",
#             "device_id": "device123",
#             "coins": 500,
#             "refercode": "user1234",
#             "referred_by": null,
#             "created_at": "2025-06-09 18:54:00",
#             "is_blocked": 0
#           }
#         ]
#       }
#     }
#   - 400: Invalid action
#   - 401: Unauthorized
#   - 500: Database connection failed

# POST /admin/users?action={block|unblock}
# Description: Blocks or unblocks a user.
# Headers:
#   - Authorization: Bearer <token>
# Parameters:
#   - action: string (required, one of: block, unblock)
# Request Body:
#   - user_id: integer (required)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "User blocked"
#     }
#   - 400: Invalid input
#   - 401: Unauthorized
#   - 500: Database connection failed

# POST /admin/users?action=edit
# Description: Edits user details (coins and email).
# Headers:
#   - Authorization: Bearer <token>
# Parameters:
#   - action: string (required, value: edit)
# Request Body:
#   - user_id: integer (required)
#   - coins: integer (optional)
#   - email: string (optional)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "User details updated successfully"
#     }
#   - 400: Invalid input
#   - 401: Unauthorized
#   - 500: Database connection failed

$token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
authenticateAdmin(str_replace('Bearer ', '', $token));

$action = $_GET['action'] ?? '';

$conn = getDbConnection();

if ($action === 'list') {
    $result = $conn->query("SELECT id, email, device_id, coins, refercode, referred_by, created_at, is_blocked FROM users ORDER BY created_at DESC");
    $users = [];
    while ($row = $result->fetch_assoc()) {
        $users[] = $row;
    }
    sendResponse(200, 'Users fetched', ['users' => $users]);
} elseif (in_array($action, ['block', 'unblock'])) {
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method === 'POST') {
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        $user_id = $data['user_id'];

        $is_blocked = ($action === 'block') ? 1 : 0;
        $stmt = $conn->prepare("UPDATE users SET is_blocked = ? WHERE id = ?");
        $stmt->bind_param("ii", $is_blocked, $user_id);
        $stmt->execute();

        sendResponse(200, 'User ' . $action . 'ed');
    } else {
        sendResponse(400, 'Invalid request method');
    }
} elseif ($action === 'edit') {
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method === 'POST') {
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        $user_id = $data['user_id'] ?? null;
        $coins = $data['coins'] ?? null;
        $email = $data['email'] ?? null;

        if (!$user_id) {
            sendResponse(400, 'User ID is required');
        }

        // Check if user exists
        $check_stmt = $conn->prepare("SELECT id FROM users WHERE id = ?");
        $check_stmt->bind_param("i", $user_id);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        
        if ($result->num_rows === 0) {
            sendResponse(400, 'User not found');
        }
        $check_stmt->close();

        // Build update query dynamically based on provided fields
        $update_fields = [];
        $types = '';
        $values = [];

        if ($coins !== null) {
            $update_fields[] = "coins = ?";
            $types .= 'i';
            $values[] = $coins;
        }

        if ($email !== null) {
            // Validate email format
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                sendResponse(400, 'Invalid email format');
            }
            
            // Check if email already exists for another user
            $email_check_stmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
            $email_check_stmt->bind_param("si", $email, $user_id);
            $email_check_stmt->execute();
            $email_result = $email_check_stmt->get_result();
            
            if ($email_result->num_rows > 0) {
                sendResponse(400, 'Email already exists');
            }
            $email_check_stmt->close();

            $update_fields[] = "email = ?";
            $types .= 's';
            $values[] = $email;
        }

        if (empty($update_fields)) {
            sendResponse(400, 'No fields to update. Please provide coins or email.');
        }

        // Add user_id to values array for WHERE clause
        $values[] = $user_id;
        $types .= 'i';

        $sql = "UPDATE users SET " . implode(', ', $update_fields) . " WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$values);
        
        if ($stmt->execute()) {
            sendResponse(200, 'User details updated successfully');
        } else {
            sendResponse(500, 'Failed to update user details');
        }
        
        $stmt->close();
    } else {
        sendResponse(400, 'Invalid request method');
    }
} else {
    sendResponse(400, 'Invalid action');
}

$conn->close();
?>