<?php
// [root]/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;
    }

    try {
        // Begin transaction
        $pdo->beginTransaction();
        
        // 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);
        
        if (!$currentData) {
            throw new Exception('User not found');
        }

        // Get Demo group ID and passwords
        $stmt = $pdo->prepare("SELECT id, group_pass, group_pass_clear FROM wp_groups WHERE group_name = 'Demo'");
        $stmt->execute();
        $demoGroup = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$demoGroup) {
            throw new Exception('Demo group not found');
        }
        $demoGroupId = $demoGroup['id'];

        // Get Individuals group ID and passwords
        $stmt = $pdo->prepare("SELECT id, group_pass, group_pass_clear FROM wp_groups WHERE group_name = 'Individuals'");
        $stmt->execute();
        $indivGroup = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$indivGroup) {
            throw new Exception('Individuals group not found');
        }
        $individualsGroupId = $indivGroup['id'];

        $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);
                
                if (!$previousGroupData) {
                    throw new Exception('Previous group not found');
                }
                
                $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
                $updates[] = "group_id = :indiv_id";
                $updates[] = "user_pass = :new_pass";
                $updates[] = "user_pass_clear = :new_pass_clear";
                $params[':indiv_id'] = $individualsGroupId;
                $params[':new_pass'] = $indivGroup['group_pass'];
                $params[':new_pass_clear'] = $indivGroup['group_pass_clear'];
            }
        } else if ($currentData['user_type'] !== 'demo' && $newRole === 'demo') {
            // Any role --> Demo role
            // Store previous group if not already a demo user and not from Individuals
            if ($currentData['group_id'] != $individualsGroupId) {
                $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'] = $demoGroup['group_pass'];
            $params[':demo_pass_clear'] = $demoGroup['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) {
            throw new Exception('Failed to update user role: ' . implode(', ', $stmt->errorInfo()));
        }

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

        $pdo->commit();
        echo json_encode([
            'success' => true,
            'data' => $updatedData
        ]);
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
}