<?php
// admin/api/update-user-role.php
include($_SERVER['DOCUMENT_ROOT'] . '/includes/include_all.inc.php');

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = $_POST['userId'] ?? null;
    $newRole = $_POST['newRole'] ?? null;

    if (!$userId || !$newRole) {
        echo json_encode(['success' => false, 'error' => 'Missing required parameters']);
        exit;
    }

    // Get current user data including previous_group
    $stmt = $pdo->prepare("SELECT user_type, group_id, previous_group FROM wp_users WHERE id = ?");
    $stmt->execute([$userId]);
    $currentData = $stmt->fetch(PDO::FETCH_ASSOC);

    // Get Demo group ID
    $stmt = $pdo->prepare("SELECT id FROM wp_groups WHERE group_name = 'Demo'");
    $stmt->execute();
    $demoGroupId = $stmt->fetchColumn();

    $updates = ["user_type = :new_role"];
    $params = [':new_role' => $newRole, ':user_id' => $userId];

    // Handle role transitions
    if ($currentData['user_type'] === 'demo' && $newRole !== 'demo') {
        // Demo role --> User role
        if ($currentData['previous_group']) {
            // If there's a previous group, switch back to it
            $stmt = $pdo->prepare("SELECT group_pass, group_pass_clear FROM wp_groups WHERE id = ?");
            $stmt->execute([$currentData['previous_group']]);
            $previousGroupData = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $updates[] = "group_id = :new_group";
            $updates[] = "user_pass = :new_pass";
            $updates[] = "user_pass_clear = :new_pass_clear";
            $updates[] = "previous_group = NULL"; // Clear previous_group
            $params[':new_group'] = $currentData['previous_group'];
            $params[':new_pass'] = $previousGroupData['group_pass'];
            $params[':new_pass_clear'] = $previousGroupData['group_pass_clear'];
        } else {
            // No previous group, switch to Individuals
            $stmt = $pdo->prepare("SELECT group_pass, group_pass_clear FROM wp_groups WHERE id = 1");
            $stmt->execute();
            $indivGroupData = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $updates[] = "group_id = 1";
            $updates[] = "user_pass = :new_pass";
            $updates[] = "user_pass_clear = :new_pass_clear";
            $params[':new_pass'] = $indivGroupData['group_pass'];
            $params[':new_pass_clear'] = $indivGroupData['group_pass_clear'];
        }
    }
    else if ($currentData['user_type'] !== 'demo' && $newRole === 'demo') {
        // Any role --> Demo role
        $stmt = $pdo->prepare("SELECT group_pass, group_pass_clear FROM wp_groups WHERE id = ?");
        $stmt->execute([$demoGroupId]);
        $demoGroupData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Store previous group if not from Individuals
        if ($currentData['group_id'] != 1) {
            $updates[] = "previous_group = :prev_group";
            $params[':prev_group'] = $currentData['group_id'];
        }
        
        $updates[] = "group_id = :demo_group";
        $updates[] = "user_pass = :demo_pass";
        $updates[] = "user_pass_clear = :demo_pass_clear";
        $params[':demo_group'] = $demoGroupId;
        $params[':demo_pass'] = $demoGroupData['group_pass'];
        $params[':demo_pass_clear'] = $demoGroupData['group_pass_clear'];
    }

    // Execute update
    $sql = "UPDATE wp_users SET " . implode(", ", $updates) . " WHERE id = :user_id";
    $stmt = $pdo->prepare($sql);
    $success = $stmt->execute($params);

    if ($success) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to update user role']);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
}