Backend Process Test"; echo ""; try { $auth = new Auth(); if (!$auth->isLoggedIn()) { die("
❌ Please log in first
"); } $db = Database::getInstance(); echo "
✅ Database connected
"; // Test 1: Check if we can create analysis state echo "
"; echo "

Test 1: Analysis State Management

"; // Reset any existing state $db->query("UPDATE optimization_analysis_state SET is_running = 0, should_pause = 0 WHERE is_running = 1"); echo "
Reset any existing analysis state
"; // Check if we have directives to work with $directiveCount = $db->query("SELECT COUNT(*) as count FROM panel_directives WHERE llm_checked = 0")->fetch_assoc()['count']; echo "
Unprocessed directives available: " . number_format($directiveCount) . "
"; if ($directiveCount == 0) { echo "
⚠️ No unprocessed directives found. Generating test combinations...
"; // Generate a few test combinations $testResult = generateTestCombinations($db); if ($testResult['success']) { echo "
✅ Generated " . $testResult['count'] . " test combinations
"; $directiveCount = $testResult['count']; } else { echo "
❌ Failed to generate test combinations: " . $testResult['error'] . "
"; } } echo "
"; // Test 2: Test GPT Helper echo "
"; echo "

Test 2: GPT Helper Functionality

"; if (class_exists('GptHelper')) { echo "
✅ GptHelper class found
"; if (defined('OPENAI_API_KEY') && !empty(OPENAI_API_KEY)) { echo "
✅ OpenAI API key configured
"; try { require_once 'includes/GptHelper.php'; // Test a simple analysis echo "
Testing simple combination analysis...
"; $testMessages = [ [ 'role' => 'system', 'content' => 'You are a demographic analyst. Respond with "POSSIBLE" or "IMPOSSIBLE" followed by a brief reason.' ], [ 'role' => 'user', 'content' => 'Analyze: Gender=Male + Age=25-35 years. Is this combination possible?' ] ]; $testResponse = GptHelper::makeRequest($testMessages, 'gpt-4', 0.1); if ($testResponse['success']) { echo "
✅ GPT API test successful
"; echo "
Response: " . htmlspecialchars(substr($testResponse['response'], 0, 100)) . "...
"; } else { echo "
❌ GPT API test failed: " . htmlspecialchars($testResponse['error']) . "
"; } } catch (Exception $e) { echo "
❌ GPT test error: " . htmlspecialchars($e->getMessage()) . "
"; } } else { echo "
❌ OpenAI API key not configured
"; } } else { echo "
❌ GptHelper class not found
"; } echo "
"; // Test 3: Process a few combinations manually echo "
"; echo "

Test 3: Manual Processing Test

"; if ($directiveCount > 0) { echo "
Processing 2 combinations manually...
"; $testQuery = $db->query(" SELECT id, attribute1_id, attribute2_id, choice1, choice2, attribute1_name, attribute2_name FROM panel_directives WHERE llm_checked = 0 ORDER BY id ASC LIMIT 2 "); $processedCount = 0; $errorCount = 0; while ($combination = $testQuery->fetch_assoc()) { try { $result = processTestCombination($combination, $db); if ($result['success']) { $processedCount++; echo "
✅ Processed: {$combination['attribute1_name']}={$combination['choice1']} + {$combination['attribute2_name']}={$combination['choice2']} → " . ($result['is_impossible'] ? 'IMPOSSIBLE' : 'POSSIBLE') . "
"; } else { $errorCount++; echo "
❌ Failed: {$combination['attribute1_name']}={$combination['choice1']} + {$combination['attribute2_name']}={$combination['choice2']} → " . $result['error'] . "
"; } } catch (Exception $e) { $errorCount++; echo "
❌ Exception: " . htmlspecialchars($e->getMessage()) . "
"; } } echo "
Manual processing complete: $processedCount success, $errorCount errors
"; } else { echo "
⚠️ No combinations available for testing
"; } echo "
"; // Test 4: Background Process Capability echo "
"; echo "

Test 4: Background Process Capability

"; if (function_exists('exec')) { echo "
✅ PHP exec() function available
"; // Test if we can run a simple background command $testCommand = "php -v"; $output = []; $returnCode = 0; exec($testCommand, $output, $returnCode); if ($returnCode === 0 && !empty($output)) { echo "
✅ Background command execution works
"; echo "
PHP version: " . htmlspecialchars($output[0]) . "
"; } else { echo "
❌ Background command execution failed
"; } // Check if enhanced process file exists if (file_exists('enhanced_process_optimization.php')) { echo "
✅ Enhanced process file exists
"; } else { echo "
❌ Enhanced process file missing
"; } } else { echo "
❌ PHP exec() function not available
"; } echo "
"; // Summary echo "
"; echo "

Summary & Recommendations

"; if ($directiveCount > 0 && class_exists('GptHelper') && function_exists('exec')) { echo "
✅ Backend process should work correctly
"; echo "
✨ You can now try starting the analysis from the OptimAIze page
"; } else { echo "
⚠️ Some issues detected. Please fix the above errors first.
"; } echo "
Next Steps:
"; echo ""; echo "
"; } catch (Exception $e) { echo "
❌ Test failed: " . htmlspecialchars($e->getMessage()) . "
"; } function generateTestCombinations($db) { try { // Get a few attributes for testing $attributesQuery = $db->query("SELECT id, name, choices FROM attributes ORDER BY id LIMIT 2"); $attributes = []; while ($attr = $attributesQuery->fetch_assoc()) { $choices = json_decode($attr['choices'], true); if ($choices && is_array($choices)) { $attributes[] = [ 'id' => $attr['id'], 'name' => $attr['name'], 'choices' => array_slice($choices, 0, 2) // Only first 2 choices for testing ]; } } if (count($attributes) < 2) { return ['success' => false, 'error' => 'Need at least 2 attributes']; } $generatedCount = 0; $stmt = $db->prepare("INSERT IGNORE INTO panel_directives (attribute1_id, attribute2_id, choice1, choice2, attribute1_name, attribute2_name, status) VALUES (?, ?, ?, ?, ?, ?, 'pending')"); $attr1 = $attributes[0]; $attr2 = $attributes[1]; foreach ($attr1['choices'] as $choice1) { foreach ($attr2['choices'] as $choice2) { $stmt->bind_param('iissss', $attr1['id'], $attr2['id'], $choice1, $choice2, $attr1['name'], $attr2['name'] ); if ($stmt->execute()) { $generatedCount++; } } } return ['success' => true, 'count' => $generatedCount]; } catch (Exception $e) { return ['success' => false, 'error' => $e->getMessage()]; } } function processTestCombination($combination, $db) { try { require_once 'includes/GptHelper.php'; $prompt = sprintf( "Analyze this demographic combination:\n\n%s = %s\n%s = %s\n\nIs this combination logically possible in real-world demographics? Respond with 'POSSIBLE' or 'IMPOSSIBLE' followed by a brief reason.", $combination['attribute1_name'], $combination['choice1'], $combination['attribute2_name'], $combination['choice2'] ); $messages = [ [ 'role' => 'system', 'content' => 'You are an expert demographic analyst. Analyze if the given combination is logically possible.' ], [ 'role' => 'user', 'content' => $prompt ] ]; $response = GptHelper::makeRequest($messages, 'gpt-4', 0.1); if (!$response['success']) { throw new Exception("GPT request failed: " . $response['error']); } $content = trim($response['response']); $isImpossible = stripos($content, 'IMPOSSIBLE') === 0 ? 1 : 0; // Extract reasoning $reasoning = trim(str_ireplace(['POSSIBLE', 'IMPOSSIBLE'], '', $content)); if (empty($reasoning)) { $reasoning = $content; } // Update database $stmt = $db->prepare("UPDATE panel_directives SET llm_checked = 1, is_impossible = ?, llm_reasoning = ?, updated_at = NOW() WHERE id = ?"); $stmt->bind_param('isi', $isImpossible, $reasoning, $combination['id']); if (!$stmt->execute()) { throw new Exception("Database update failed"); } return [ 'success' => true, 'is_impossible' => $isImpossible, 'reasoning' => $reasoning ]; } catch (Exception $e) { return [ 'success' => false, 'error' => $e->getMessage() ]; } } ?>