<?php
// api/demo_role.php
function isDemoUser($userId = null) {
    global $pdo;
    
    if (!isset($_SESSION['front_user_id'])) {
        return false; // User not logged in
    }
    
    $userId = $userId ?? $_SESSION['front_user_id'];
    $query = "SELECT user_type, user_group FROM wp_users WHERE ID = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$userId]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Return true if either role is demo OR group is Demo
    return ($result && ($result['user_type'] === 'demo' || $result['user_group'] === 'Demo'));
}

function isFirstCase($caseId) {
    return $caseId == 1;
}

function isDemoAllowedCase($caseId) {
    return isFirstCase($caseId) && isDemoUser();
}

function upgradeFromDemo($userId) {
    global $pdo;
    // Only change the role if it's 'demo', and group if it's 'Demo'
    $stmt = $pdo->prepare("UPDATE wp_users SET 
        user_type = CASE WHEN user_type = 'demo' THEN 'user' ELSE user_type END,
        user_group = CASE WHEN user_group = 'Demo' THEN 'Individuals' ELSE user_group END
        WHERE id = ?");
    $result = $stmt->execute([$userId]);
    
    // clear demo status in localStorage when they upgrade
    if($result) {
        echo "<script>localStorage.removeItem('initial_demo_status');</script>";
    }
    return $result;
}

// Similar to applyProFeatures in pro_features.php
function applyDemoRestrictions() {
    if (isDemoUser()) {
        $GLOBALS['UserStr'] = "Demo";
    } else {
        $GLOBALS['UserStr'] = "User";
    }
}

// echo json_encode(['isDemo' => isDemoUser()]);
// exit;