🚀 Quick Start OptimAIze";
echo "";
try {
$auth = new Auth();
if (!$auth->isLoggedIn()) {
die("
❌ Please log in first
");
}
$db = Database::getInstance();
// Get action parameter
$action = $_GET['action'] ?? '';
if ($action) {
handleAction($action, $db);
} else {
showMainInterface($db);
}
} catch (Exception $e) {
echo "❌ Error: " . htmlspecialchars($e->getMessage()) . "
";
}
function showMainInterface($db) {
echo "";
echo "
🎯 OptimAIze Quick Setup
";
echo "
This will set up and test your enhanced OptimAIze system in one click.
";
// Show current status
$status = getCurrentStatus($db);
echo "
Current Status:
";
echo "
✅ Database: Connected
";
echo "
" .
($status['gpt_helper'] ? '✅' : '❌') . " GptHelper: " .
($status['gpt_helper'] ? 'Available' : 'Not Found') . "
";
echo "
📊 Combinations: " . number_format($status['total_combinations']) . " total, " .
number_format($status['processed_combinations']) . " processed
";
echo "
" .
($status['openai_key'] ? '✅' : '❌') . " OpenAI API: " .
($status['openai_key'] ? 'Configured' : 'Not Configured') . "
";
if ($status['is_running']) {
echo "
⚠️ Analysis is currently running
";
$progress = $status['total_combinations'] > 0 ?
($status['processed_combinations'] / $status['total_combinations']) * 100 : 0;
echo "
";
echo "
Progress: " . number_format($progress, 1) . "%
";
} else {
echo "
⏹ Analysis is stopped
";
}
echo "
";
// Action buttons
echo "";
// Quick stats
if ($status['processed_combinations'] > 0) {
echo "";
echo "
📊 Quick Results:
";
echo "
Possible Combinations: " . number_format($status['possible_combinations']) . "
";
echo "
Impossible Combinations: " . number_format($status['impossible_combinations']) . "
";
if ($status['impossible_combinations'] > 0) {
$impossibleRate = ($status['impossible_combinations'] / $status['processed_combinations']) * 100;
echo "
Impossible Rate: " . number_format($impossibleRate, 1) . "%
";
}
echo "
";
}
echo "";
}
function handleAction($action, $db) {
switch ($action) {
case 'setup_database':
setupDatabase($db);
break;
case 'generate_combinations':
generateCombinations($db);
break;
case 'test_gpt':
testGptConnection($db);
break;
case 'start_analysis':
startAnalysis($db);
break;
case 'stop_analysis':
stopAnalysis($db);
break;
case 'view_results':
viewResults($db);
break;
default:
echo "❌ Unknown action: $action
";
}
echo "
← Back to Main";
}
function getCurrentStatus($db) {
$status = [];
// Check GptHelper
try {
if (!class_exists('GptHelper')) {
require_once 'includes/GptHelper.php';
}
$status['gpt_helper'] = class_exists('GptHelper');
} catch (Exception $e) {
$status['gpt_helper'] = false;
}
// Check OpenAI API key
$status['openai_key'] = defined('OPENAI_API_KEY') && !empty(OPENAI_API_KEY);
// Check database columns
$columnCheck = $db->query("SHOW COLUMNS FROM optimization_analysis_state LIKE 'should_pause'");
$status['has_database_columns'] = $columnCheck && $columnCheck->num_rows > 0;
// Get combination counts
$totalQuery = $db->query("SELECT COUNT(*) as count FROM panel_directives");
$status['total_combinations'] = $totalQuery ? $totalQuery->fetch_assoc()['count'] : 0;
$processedQuery = $db->query("SELECT COUNT(*) as count FROM panel_directives WHERE llm_checked = 1");
$status['processed_combinations'] = $processedQuery ? $processedQuery->fetch_assoc()['count'] : 0;
$possibleQuery = $db->query("SELECT COUNT(*) as count FROM panel_directives WHERE llm_checked = 1 AND is_impossible = 0");
$status['possible_combinations'] = $possibleQuery ? $possibleQuery->fetch_assoc()['count'] : 0;
$impossibleQuery = $db->query("SELECT COUNT(*) as count FROM panel_directives WHERE llm_checked = 1 AND is_impossible = 1");
$status['impossible_combinations'] = $impossibleQuery ? $impossibleQuery->fetch_assoc()['count'] : 0;
// Check if analysis is running
$stateQuery = $db->query("SELECT is_running FROM optimization_analysis_state WHERE is_running = 1 LIMIT 1");
$status['is_running'] = $stateQuery && $stateQuery->num_rows > 0;
return $status;
}
function setupDatabase($db) {
echo "🛠 Setting Up Database
";
try {
// Add should_pause column if missing
$columnCheck = $db->query("SHOW COLUMNS FROM optimization_analysis_state LIKE 'should_pause'");
if (!$columnCheck || $columnCheck->num_rows == 0) {
$result = $db->query("ALTER TABLE optimization_analysis_state ADD COLUMN should_pause TINYINT(1) DEFAULT 0 AFTER is_running");
if ($result) {
echo "✅ Added 'should_pause' column
";
} else {
echo "❌ Failed to add 'should_pause' column
";
}
} else {
echo "✅ Database columns already exist
";
}
// Reset any stuck states
$db->query("UPDATE optimization_analysis_state SET is_running = 0, should_pause = 0 WHERE is_running = 1");
echo "✅ Reset any stuck analysis states
";
} catch (Exception $e) {
echo "❌ Database setup failed: " . htmlspecialchars($e->getMessage()) . "
";
}
}
function generateCombinations($db) {
echo "🔄 Generating Combinations
";
try {
// Get attributes
$attributesQuery = $db->query("SELECT id, name, choices FROM attributes ORDER BY id");
$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' => $choices
];
}
}
if (count($attributes) < 2) {
throw new Exception("Need at least 2 attributes to generate combinations");
}
echo "Found " . count($attributes) . " attributes
";
$generatedCount = 0;
$stmt = $db->prepare("INSERT IGNORE INTO panel_directives
(attribute1_id, attribute2_id, choice1, choice2, attribute1_name, attribute2_name, status)
VALUES (?, ?, ?, ?, ?, ?, 'pending')");
// Generate combinations
for ($i = 0; $i < count($attributes); $i++) {
for ($j = $i + 1; $j < count($attributes); $j++) {
$attr1 = $attributes[$i];
$attr2 = $attributes[$j];
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++;
}
}
}
}
}
echo "✅ Generated " . number_format($generatedCount) . " combinations
";
} catch (Exception $e) {
echo "❌ Generation failed: " . htmlspecialchars($e->getMessage()) . "
";
}
}
function testGptConnection($db) {
echo "🤖 Testing GPT Connection
";
try {
if (!class_exists('GptHelper')) {
require_once 'includes/GptHelper.php';
}
if (!class_exists('GptHelper')) {
throw new Exception("GptHelper class not found");
}
echo "✅ GptHelper class loaded
";
if (!defined('OPENAI_API_KEY') || empty(OPENAI_API_KEY)) {
throw new Exception("OpenAI API key not configured");
}
echo "✅ OpenAI API key configured
";
// Test basic request
$messages = [
[
'role' => 'user',
'content' => 'Respond with exactly: "TEST SUCCESSFUL"'
]
];
echo "🔄 Sending test request...
";
$response = GptHelper::makeRequest($messages, 'gpt-4', 0.1);
if ($response['success']) {
echo "✅ GPT API test successful!
";
echo "Response: " . htmlspecialchars($response['response']) . "
";
} else {
throw new Exception("GPT API test failed: " . $response['error']);
}
} catch (Exception $e) {
echo "❌ GPT test failed: " . htmlspecialchars($e->getMessage()) . "
";
}
}
function startAnalysis($db) {
echo "🚀 Starting Analysis
";
try {
// Check if already running
$stateQuery = $db->query("SELECT is_running FROM optimization_analysis_state WHERE is_running = 1 LIMIT 1");
if ($stateQuery && $stateQuery->num_rows > 0) {
echo "⚠️ Analysis is already running
";
return;
}
// Get total combinations
$totalQuery = $db->query("SELECT COUNT(*) as count FROM panel_directives");
$totalCombinations = $totalQuery->fetch_assoc()['count'];
if ($totalCombinations == 0) {
echo "❌ No combinations found. Generate combinations first.
";
return;
}
// Get processed count
$processedQuery = $db->query("SELECT COUNT(*) as count FROM panel_directives WHERE llm_checked = 1");
$processedCount = $processedQuery->fetch_assoc()['count'];
// Update or create analysis state
$existingState = $db->query("SELECT id FROM optimization_analysis_state ORDER BY id DESC LIMIT 1");
if ($existingState && $existingState->num_rows > 0) {
$stateId = $existingState->fetch_assoc()['id'];
$stmt = $db->prepare("UPDATE optimization_analysis_state SET
is_running = 1,
started_at = NOW(),
total_combinations = ?,
processed_combinations = ?,
should_pause = 0,
completed_at = NULL
WHERE id = ?");
$stmt->bind_param('iii', $totalCombinations, $processedCount, $stateId);
} else {
$stmt = $db->prepare("INSERT INTO optimization_analysis_state
(total_combinations, processed_combinations, is_running, started_at, should_pause)
VALUES (?, ?, 1, NOW(), 0)");
$stmt->bind_param('ii', $totalCombinations, $processedCount);
}
if (!$stmt->execute()) {
throw new Exception("Failed to update analysis state");
}
echo "✅ Analysis state updated
";
echo "📊 Total combinations: " . number_format($totalCombinations) . "
";
echo "📊 Already processed: " . number_format($processedCount) . "
";
echo "📊 Remaining: " . number_format($totalCombinations - $processedCount) . "
";
// Start background process
$processFile = file_exists('enhanced_process_optimization.php') ?
'enhanced_process_optimization.php' :
'process_optimization_analysis.php';
$command = "php " . __DIR__ . "/$processFile > /dev/null 2>&1 &";
exec($command);
echo "✅ Background process started using: $processFile
";
echo "💡 You can now monitor progress on the OptimAIze page
";
} catch (Exception $e) {
echo "❌ Failed to start analysis: " . htmlspecialchars($e->getMessage()) . "
";
}
}
function stopAnalysis($db) {
echo "⏹ Stopping Analysis
";
try {
$stmt = $db->prepare("UPDATE optimization_analysis_state SET
is_running = 0,
should_pause = 0,
completed_at = NOW()
WHERE is_running = 1");
if ($stmt->execute()) {
echo "✅ Analysis stopped successfully
";
} else {
echo "❌ Failed to stop analysis
";
}
} catch (Exception $e) {
echo "❌ Error stopping analysis: " . htmlspecialchars($e->getMessage()) . "
";
}
}
function viewResults($db) {
echo "📊 Analysis Results
";
try {
// Get recent possible combinations
$possibleQuery = $db->query("
SELECT attribute1_name, choice1, attribute2_name, choice2, updated_at
FROM panel_directives
WHERE llm_checked = 1 AND is_impossible = 0
ORDER BY updated_at DESC
LIMIT 5
");
echo "Recent Possible Combinations (Last 5):
";
if ($possibleQuery && $possibleQuery->num_rows > 0) {
echo "";
while ($row = $possibleQuery->fetch_assoc()) {
echo "- {$row['attribute1_name']}={$row['choice1']} + {$row['attribute2_name']}={$row['choice2']} (" . date('H:i:s', strtotime($row['updated_at'])) . ")
";
}
echo "
";
} else {
echo "No possible combinations analyzed yet
";
}
// Get impossible combinations
$impossibleQuery = $db->query("
SELECT attribute1_name, choice1, attribute2_name, choice2, llm_reasoning, updated_at
FROM panel_directives
WHERE llm_checked = 1 AND is_impossible = 1
ORDER BY updated_at DESC
LIMIT 10
");
echo "Impossible Combinations (Last 10):
";
if ($impossibleQuery && $impossibleQuery->num_rows > 0) {
echo "";
while ($row = $impossibleQuery->fetch_assoc()) {
echo "- {$row['attribute1_name']}={$row['choice1']} + {$row['attribute2_name']}={$row['choice2']}
";
echo "" . htmlspecialchars(substr($row['llm_reasoning'], 0, 100)) . "... (" . date('H:i:s', strtotime($row['updated_at'])) . ")
";
}
echo "
";
} else {
echo "No impossible combinations found yet
";
}
} catch (Exception $e) {
echo "❌ Error viewing results: " . htmlspecialchars($e->getMessage()) . "
";
}
}
?>