<?php
// Comprehensive test of all new Token Management functionality
require_once '../includes/db.php';

echo "🧪 Testing All New Token Management Functionality...\n\n";

$all_tests_passed = true;

try {
    // Test 1: API endpoints availability
    echo "📡 Testing API Endpoints...\n";
    
    $api_file = 'token_management_api.php';
    if (file_exists($api_file)) {
        echo "  ✓ token_management_api.php exists\n";
        
        // Check syntax
        $output = shell_exec("php -l $api_file 2>&1");
        if (strpos($output, 'No syntax errors') !== false) {
            echo "  ✓ API file has valid PHP syntax\n";
        } else {
            echo "  ❌ API file has syntax errors: " . trim($output) . "\n";
            $all_tests_passed = false;
        }
    } else {
        echo "  ❌ token_management_api.php not found\n";
        $all_tests_passed = false;
    }
    
    // Test 2: Database queries for new functionality
    echo "\n🔍 Testing Database Queries...\n";
    
    // Test group details query
    echo "  Testing Group Details query...\n";
    $group_stmt = $pdo->prepare("
        SELECT 
            g.*,
            COUNT(ugm.id) as member_count,
            GROUP_CONCAT(CONCAT(COALESCE(p.full_name, u.username), ' (', ugm.role_in_group, ')') SEPARATOR ', ') as members_list,
            b.balance as group_budget,
            b.total_spent as budget_spent,
            b.total_purchased as budget_purchased,
            b.id as budget_id,
            cb.username as created_by_name,
            cb.id as created_by_id
        FROM user_groups g
        LEFT JOIN user_group_memberships ugm ON g.id = ugm.group_id
        LEFT JOIN users u ON ugm.user_id = u.id
        LEFT JOIN user_profiles p ON u.id = p.user_id
        LEFT JOIN budgets b ON g.id = b.group_id AND b.is_active = 1
        LEFT JOIN users cb ON g.created_by = cb.id
        WHERE g.is_active = 1
        GROUP BY g.id
        LIMIT 1
    ");
    $group_stmt->execute();
    $group_result = $group_stmt->fetch();
    echo "    ✓ Group details query successful\n";
    
    // Test user transactions query
    echo "  Testing User Transactions query...\n";
    $user_trans_stmt = $pdo->prepare("
        SELECT 
            t.*,
            ta.action_name,
            b.group_id,
            ug.name as group_name,
            ug.color as group_color
        FROM token_transactions t
        LEFT JOIN token_actions ta ON t.action_id = ta.id
        LEFT JOIN budgets b ON t.budget_id = b.id
        LEFT JOIN user_groups ug ON b.group_id = ug.id
        ORDER BY t.created_at DESC
        LIMIT 5
    ");
    $user_trans_stmt->execute();
    $user_trans_result = $user_trans_stmt->fetchAll();
    echo "    ✓ User transactions query successful - found " . count($user_trans_result) . " transactions\n";
    
    // Test budget transactions query
    echo "  Testing Budget Transactions query...\n";
    $budget_trans_stmt = $pdo->prepare("
        SELECT 
            t.*,
            u.username,
            p.full_name,
            ta.action_name
        FROM token_transactions t
        LEFT JOIN users u ON t.user_id = u.id
        LEFT JOIN user_profiles p ON u.id = p.user_id
        LEFT JOIN token_actions ta ON t.action_id = ta.id
        WHERE t.budget_id IS NOT NULL
        ORDER BY t.created_at DESC
        LIMIT 5
    ");
    $budget_trans_stmt->execute();
    $budget_trans_result = $budget_trans_stmt->fetchAll();
    echo "    ✓ Budget transactions query successful - found " . count($budget_trans_result) . " transactions\n";
    
    // Test user budget access query
    echo "  Testing User Budget Access query...\n";
    $user_budget_stmt = $pdo->prepare("
        SELECT DISTINCT
            b.*,
            ug.name as group_name,
            ug.color as group_color,
            ugm.role_in_group
        FROM budgets b
        INNER JOIN user_groups ug ON b.group_id = ug.id
        INNER JOIN user_group_memberships ugm ON ug.id = ugm.group_id
        WHERE b.is_active = 1 AND ug.is_active = 1
        ORDER BY b.created_at DESC
        LIMIT 5
    ");
    $user_budget_stmt->execute();
    $user_budget_result = $user_budget_stmt->fetchAll();
    echo "    ✓ User budget access query successful - found " . count($user_budget_result) . " budget accesses\n";
    
    // Test 3: Check modals exist in main file
    echo "\n🪟 Testing Modal Availability...\n";
    
    $main_file_content = file_get_contents('token_management.php');
    $required_modals = [
        'groupDetailsModal',
        'groupMembersModal', 
        'manageGroupMembersModal',
        'budgetTransactionsModal',
        'userTransactionsModal',
        'userBudgetModal',
        'createBudgetModal'
    ];
    
    foreach ($required_modals as $modal) {
        if (strpos($main_file_content, $modal) !== false) {
            echo "  ✓ {$modal} found in main file\n";
        } else {
            echo "  ❌ {$modal} missing from main file\n";
            $all_tests_passed = false;
        }
    }
    
    // Test 4: Check JavaScript functions exist
    echo "\n⚡ Testing JavaScript Functions...\n";
    
    $required_functions = [
        'viewGroupDetails',
        'viewGroupMembers',
        'manageGroupMembers',
        'createGroupBudget',
        'viewUserTransactions',
        'viewUserBudget',
        'viewBudgetTransactions'
    ];
    
    foreach ($required_functions as $function) {
        if (strpos($main_file_content, "function {$function}(") !== false) {
            echo "  ✓ {$function}() found in JavaScript\n";
        } else {
            echo "  ❌ {$function}() missing from JavaScript\n";
            $all_tests_passed = false;
        }
    }
    
    // Test 5: Check clickable links added
    echo "\n🔗 Testing Clickable Links...\n";
    
    $clickable_features = [
        'onclick="viewUserBudget(' => 'User budget links',
        'onclick="viewUserTransactions(' => 'User transaction links',
        'onclick="viewBudgetTransactions(' => 'Budget transaction links',
        'onclick="viewGroupDetails(' => 'Group details links',
        'onclick="viewGroupMembers(' => 'Group member links',
        'onclick="manageGroupMembers(' => 'Manage member links'
    ];
    
    foreach ($clickable_features as $pattern => $description) {
        if (strpos($main_file_content, $pattern) !== false) {
            echo "  ✓ {$description} implemented\n";
        } else {
            echo "  ❌ {$description} missing\n";
            $all_tests_passed = false;
        }
    }
    
    // Test 6: API Action Coverage
    echo "\n🎯 Testing API Action Coverage...\n";
    
    $api_content = file_get_contents('token_management_api.php');
    $required_actions = [
        'get_group_details',
        'get_group_members', 
        'manage_group_members',
        'get_user_transactions',
        'get_user_budget',
        'get_budget_transactions',
        'create_budget',
        'add_group_member',
        'remove_group_member',
        'update_member_role'
    ];
    
    foreach ($required_actions as $action) {
        if (strpos($api_content, "case '{$action}':") !== false) {
            echo "  ✓ {$action} API endpoint implemented\n";
        } else {
            echo "  ❌ {$action} API endpoint missing\n";
            $all_tests_passed = false;
        }
    }
    
    echo "\n" . str_repeat("=", 60) . "\n";
    
    if ($all_tests_passed) {
        echo "🎉 SUCCESS! All Token Management enhancements are implemented!\n\n";
        echo "✅ Feature Summary:\n";
        echo "   • View detailed group information with budget and transaction history\n";
        echo "   • View and manage group members with role-based permissions\n";
        echo "   • Create budgets for groups directly from the interface\n";
        echo "   • View comprehensive transaction history for any budget\n";
        echo "   • View user-specific transaction history and budget access\n";
        echo "   • View user budget information across all accessible groups\n";
        echo "   • Clickable links throughout the interface for easy navigation\n\n";
        echo "🚀 Enhanced Token Management Features Available:\n";
        echo "   📊 Group Details: Comprehensive group information with statistics\n";
        echo "   👥 Member Management: Add, remove, and change member roles\n";
        echo "   💰 Budget Creation: Create budgets for groups with initial allocation\n";
        echo "   📈 Transaction Analysis: Detailed transaction history and filtering\n";
        echo "   👤 User Analytics: Individual user transaction and budget summaries\n";
        echo "   🔗 Interactive Navigation: Click any user/budget/group for details\n\n";
        echo "📍 Access all features at: /admin/token_management.php\n";
    } else {
        echo "❌ SOME FEATURES ARE MISSING! Please review the issues above.\n";
    }
    
} catch (Exception $e) {
    echo "\n❌ CRITICAL ERROR: " . $e->getMessage() . "\n";
    echo "Error trace: " . $e->getTraceAsString() . "\n";
    $all_tests_passed = false;
}

exit($all_tests_passed ? 0 : 1);
?>
