<?php
require_once '../config.php';
header('Content-Type: application/json');

$adminId = requireAdminAuth();

if (!hasPermission('admin')) {
    jsonResponse(['success' => false, 'message' => 'Insufficient permissions'], 403);
}

$pdo = getDBConnection();

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

try {
    switch ($action) {
        case 'add_user':
            $userName = sanitizeInput($_POST['name'] ?? '');
            $email = sanitizeInput($_POST['email'] ?? '');
            $password = $_POST['password'] ?? '';
            $userLevel = sanitizeInput($_POST['user_level'] ?? 'registered');
            
            if (empty($userName) || empty($email) || empty($password)) {
                jsonResponse(['success' => false, 'message' => 'All fields are required']);
            }
            
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                jsonResponse(['success' => false, 'message' => 'Invalid email format']);
            }
            
            // Validate user level
            $validLevels = ['guest', 'registered', 'pro', 'vip'];
            if (!in_array($userLevel, $validLevels)) {
                $userLevel = 'registered';
            }
            
            // Check if email exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND is_deleted = 0");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                jsonResponse(['success' => false, 'message' => 'Email already exists']);
            }
            
            // Check if username exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE user_name = ? AND is_deleted = 0");
            $stmt->execute([$userName]);
            if ($stmt->fetch()) {
                jsonResponse(['success' => false, 'message' => 'Username already exists']);
            }
            
            $passwordHash = password_hash($password, PASSWORD_DEFAULT);
            $profilePicture = "https://api.dicebear.com/7.x/fun-emoji/jpg?seed=" . urlencode($email);
            
            $stmt = $pdo->prepare("INSERT INTO users (user_name, email, password_hash, user_level, profile_picture, is_verified) VALUES (?, ?, ?, ?, ?, 1)");
            $stmt->execute([$userName, $email, $passwordHash, $userLevel, $profilePicture]);
            
            logAdminActivity($adminId, 'create_user', "Created user: $email");
            
            jsonResponse(['success' => true, 'message' => 'User created successfully']);
            break;
            
        case 'get_user':
            $userId = (int)($_POST['user_id'] ?? 0);
            
            $stmt = $pdo->prepare("SELECT id, user_name, email, user_level, is_verified FROM users WHERE id = ? AND is_deleted = 0");
            $stmt->execute([$userId]);
            $user = $stmt->fetch();
            
            if (!$user) {
                jsonResponse(['success' => false, 'message' => 'User not found']);
            }
            
            jsonResponse(['success' => true, 'user' => $user]);
            break;
            
        case 'update_user':
            $userId = (int)($_POST['user_id'] ?? 0);
            $userName = sanitizeInput($_POST['name'] ?? '');
            $email = sanitizeInput($_POST['email'] ?? '');
            $userLevel = sanitizeInput($_POST['user_level'] ?? 'registered');
            $isVerified = isset($_POST['email_verified']) && $_POST['email_verified'] === 'true' ? 1 : 0;
            
            if (empty($userName) || empty($email)) {
                jsonResponse(['success' => false, 'message' => 'Name and email are required']);
            }
            
            // Validate user level
            $validLevels = ['guest', 'registered', 'pro', 'vip'];
            if (!in_array($userLevel, $validLevels)) {
                jsonResponse(['success' => false, 'message' => 'Invalid user level. Must be: guest, registered, pro, or vip']);
            }
            
            // Check if email exists for other users
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ? AND is_deleted = 0");
            $stmt->execute([$email, $userId]);
            if ($stmt->fetch()) {
                jsonResponse(['success' => false, 'message' => 'Email already exists']);
            }
            
            // Check if username exists for other users
            $stmt = $pdo->prepare("SELECT id FROM users WHERE user_name = ? AND id != ? AND is_deleted = 0");
            $stmt->execute([$userName, $userId]);
            if ($stmt->fetch()) {
                jsonResponse(['success' => false, 'message' => 'Username already exists']);
            }
            
            $stmt = $pdo->prepare("UPDATE users SET user_name = ?, email = ?, user_level = ?, is_verified = ? WHERE id = ?");
            $stmt->execute([$userName, $email, $userLevel, $isVerified, $userId]);
            
            logAdminActivity($adminId, 'update_user', "Updated user ID: $userId");
            
            jsonResponse(['success' => true, 'message' => 'User updated successfully']);
            break;
            
        case 'delete_user':
            $userId = (int)($_POST['user_id'] ?? 0);
            
            $stmt = $pdo->prepare("UPDATE users SET is_deleted = 1, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$userId]);
            
            logAdminActivity($adminId, 'delete_user', "Deleted user ID: $userId");
            
            jsonResponse(['success' => true, 'message' => 'User deleted successfully']);
            break;
            
        default:
            jsonResponse(['success' => false, 'message' => 'Invalid action'], 400);
    }
} catch (Exception $e) {
    error_log("User API error: " . $e->getMessage());
    jsonResponse(['success' => false, 'message' => 'Operation failed: ' . $e->getMessage()], 500);
}
