isLoggedIn()) { throw new Exception('Unauthorized'); } $db = Database::getInstance(); // Check if analysis is already running $stateQuery = $db->query("SELECT * FROM optimization_analysis_state ORDER BY id DESC LIMIT 1"); $state = $stateQuery ? $stateQuery->fetch_assoc() : null; if ($state && $state['is_running']) { throw new Exception('Analysis is already running'); } // Get all attributes and their choices $attributesQuery = $db->query("SELECT id, name, choices FROM attributes ORDER BY id ASC"); $attributes = []; while ($attr = $attributesQuery->fetch_assoc()) { $attributes[] = [ 'id' => $attr['id'], 'name' => $attr['name'], 'choices' => json_decode($attr['choices'], true) ]; } if (count($attributes) < 2) { throw new Exception('Need at least 2 attributes to perform analysis'); } // Calculate total combinations needed $totalCombinations = 0; for ($i = 0; $i < count($attributes); $i++) { for ($j = $i + 1; $j < count($attributes); $j++) { $attr1_choices = count($attributes[$i]['choices']); $attr2_choices = count($attributes[$j]['choices']); $totalCombinations += $attr1_choices * $attr2_choices; } } // Clear existing directives to start fresh $db->query("DELETE FROM panel_directives"); // Generate all possible combinations and insert into database $insertedCount = 0; 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 = $db->prepare(" INSERT INTO panel_directives (attribute1_id, attribute2_id, choice1, choice2, attribute1_name, attribute2_name, status, llm_checked, is_impossible) VALUES (?, ?, ?, ?, ?, ?, 'pending', 0, 0) "); $stmt->bind_param('iissss', $attr1['id'], $attr2['id'], $choice1, $choice2, $attr1['name'], $attr2['name'] ); $stmt->execute(); $insertedCount++; } } } } // Update analysis state $db->query("DELETE FROM optimization_analysis_state"); $stmt = $db->prepare(" INSERT INTO optimization_analysis_state (total_combinations, processed_combinations, is_running, started_at) VALUES (?, 0, 1, NOW()) "); $stmt->bind_param('i', $totalCombinations); $stmt->execute(); // Start background processing $command = "php " . __DIR__ . "/process_optimization_analysis.php > /dev/null 2>&1 &"; exec($command); echo json_encode([ 'success' => true, 'total_combinations' => $totalCombinations, 'message' => "Started analysis for {$totalCombinations} combinations" ]); } catch (Exception $e) { http_response_code(500); echo json_encode([ 'success' => false, 'error' => $e->getMessage() ]); } ?>