PDO::ERRMODE_EXCEPTION]); class BrainCore { private $pdo; private $aiEndpoint = 'http://localhost:5821/api/ai-failsafe.php'; public function __construct($pdo) { $this->pdo = $pdo; } // ============================================ // AI CALL WITH FALLBACK CHAIN // ============================================ private function askAI($prompt, $system = '', $priority = 'normal') { // First try: AI Failsafe (11 providers) $result = $this->callFailsafe($prompt, $system, $priority); if ($result['success']) { return $result; } // Second try: Direct Ollama (local) $result = $this->callOllamaDirectly($prompt, $system); if ($result['success']) { return $result; } // Third try: Rule-based response (no AI needed) return $this->getRuleBasedResponse($prompt); } private function callFailsafe($prompt, $system, $priority) { $ch = curl_init($this->aiEndpoint); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_TIMEOUT => 60, CURLOPT_POSTFIELDS => http_build_query([ 'action' => 'call', 'prompt' => $prompt, 'system' => $system, 'priority' => $priority ]) ]); $response = curl_exec($ch); curl_close($ch); return json_decode($response, true) ?: ['success' => false]; } private function callOllamaDirectly($prompt, $system) { $ch = curl_init('http://localhost:11434/api/chat'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_TIMEOUT => 120, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_POSTFIELDS => json_encode([ 'model' => 'llama3', 'messages' => [ ['role' => 'system', 'content' => $system ?: 'You are a helpful assistant.'], ['role' => 'user', 'content' => $prompt] ], 'stream' => false ]) ]); $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($code === 200) { $data = json_decode($response, true); if (!empty($data['message']['content'])) { return ['success' => true, 'response' => $data['message']['content'], 'provider' => 'Ollama-Direct']; } } return ['success' => false]; } private function getRuleBasedResponse($prompt) { // Fallback: Use knowledge base rules $promptLower = strtolower($prompt); $rules = [ 'subject' => 'Here are 5 subject lines: 1. Quick update for you 2. Your request is ready 3. Following up on our chat 4. Something you might like 5. A moment of your time', 'from name' => 'Here are 5 sender names: 1. Sarah Johnson 2. Mike Williams 3. Lisa Chen 4. David Brown 5. Emma Davis', 'gmail' => 'For Gmail: Use engagement-based sending, 45-day warmup, List-Unsubscribe required, max 500/hour initially.', 'outlook' => 'For Outlook: SmartScreen filter, SCL must be <1, 30-day warmup, List-Unsubscribe-Post required.', 'warmup' => 'Standard warmup: Start 50/day, increase 20% daily, prioritize engaged recipients first.', 'spam' => 'Avoid: free, click here, act now, winner, urgent, ALL CAPS, excessive punctuation.', ]; foreach ($rules as $keyword => $response) { if (strpos($promptLower, $keyword) !== false) { return ['success' => true, 'response' => $response, 'provider' => 'RuleEngine']; } } return [ 'success' => true, 'response' => 'I apologize, but I could not process your request with AI. Please try again or rephrase your question.', 'provider' => 'Fallback' ]; } // ============================================ // BRAIN TASKS // ============================================ public function generateSubjects($offer, $isp, $count = 5) { $system = "You are an email marketing expert. Generate compelling subject lines that avoid spam triggers."; $prompt = "Generate $count email subject lines for: $offer\nTarget ISP: $isp\nRequirements: Under 50 chars, no spam words, personal tone.\nReturn only the subject lines, numbered 1-$count."; $result = $this->askAI($prompt, $system, 'high'); return ['success' => $result['success'], 'subjects' => $result['response'] ?? '', 'provider' => $result['provider'] ?? 'unknown']; } public function generateFromNames($vertical, $count = 5) { $system = "You are an email marketing expert. Generate trustworthy sender names."; $prompt = "Generate $count professional sender names for $vertical vertical.\nMix male and female names.\nReturn only the names, numbered 1-$count."; $result = $this->askAI($prompt, $system, 'normal'); return ['success' => $result['success'], 'names' => $result['response'] ?? '', 'provider' => $result['provider'] ?? 'unknown']; } public function analyzeContent($content, $isp) { $system = "You are a deliverability expert. Analyze email content for spam triggers."; $prompt = "Analyze this email content for $isp:\n\n$content\n\nProvide:\n1. Spam score (0-100, lower is better)\n2. Issues found\n3. Recommendations"; return $this->askAI($prompt, $system, 'high'); } public function optimizeCampaign($params) { $system = "You are an email campaign optimization expert."; $prompt = "Optimize campaign:\n- ISP: {$params['isp']}\n- Volume: {$params['volume']}\n- Offer: {$params['offer']}\n\nProvide:\n1. Best send method\n2. Optimal timing\n3. Segmentation strategy\n4. Risk assessment"; return $this->askAI($prompt, $system, 'high'); } public function suggestOffer($segment, $geos) { $system = "You are an affiliate marketing expert."; $prompt = "Suggest best offer types for:\n- Segment: $segment\n- Geos: " . implode(', ', (array)$geos) . "\n\nProvide: Top 3 verticals with reasoning."; return $this->askAI($prompt, $system, 'normal'); } public function troubleshoot($issue) { $system = "You are an email deliverability troubleshooting expert."; $prompt = "Troubleshoot this issue:\n$issue\n\nProvide:\n1. Likely causes\n2. Diagnostic steps\n3. Solutions"; return $this->askAI($prompt, $system, 'critical'); } // ============================================ // QUICK DECISIONS (NO AI NEEDED) // ============================================ public function getBestISP($vertical) { // Use database knowledge $isp = $this->pdo->query("SELECT isp_name, success_rate FROM admin.brain_isp_profiles WHERE success_rate > 0 ORDER BY success_rate DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC); if ($isp) { return ['isp' => $isp['isp_name'], 'success_rate' => $isp['success_rate'], 'source' => 'database']; } // Default recommendations by vertical $defaults = [ 'finance' => 'Videotron', 'health' => 'GMX', 'ecommerce' => 'Gmail', 'general' => 'Videotron' ]; return ['isp' => $defaults[$vertical] ?? 'Videotron', 'success_rate' => 70, 'source' => 'default']; } public function getBestMethod($isp, $volume) { // Use database knowledge $method = $this->pdo->query("SELECT method_name, success_rate FROM admin.brain_send_methods WHERE best_for_isps LIKE '%$isp%' OR best_for_isps = 'All' ORDER BY success_rate DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC); if ($method) { return $method; } // Default based on volume if ($volume > 50000) { return ['method_name' => 'PMTA_Direct', 'success_rate' => 70]; } elseif ($volume > 10000) { return ['method_name' => 'Hybrid_Rotation', 'success_rate' => 75]; } else { return ['method_name' => 'O365_Relay', 'success_rate' => 80]; } } public function getHealthStatus() { // Check AI system health $aiHealth = json_decode(file_get_contents($this->aiEndpoint . '?action=health'), true); return [ 'brain_status' => 'operational', 'ai_status' => $aiHealth['overall'] ?? 'unknown', 'ai_providers_healthy' => $aiHealth['healthy_providers'] ?? 0, 'ai_capacity' => $aiHealth['total_capacity_remaining'] ?? 0, 'fallback_available' => true ]; } } $brain = new BrainCore($pdo); $action = $_POST['action'] ?? $_GET['action'] ?? ''; switch ($action) { case 'subjects': echo json_encode($brain->generateSubjects($_POST['offer'] ?? '', $_POST['isp'] ?? 'Gmail', $_POST['count'] ?? 5)); break; case 'from_names': echo json_encode($brain->generateFromNames($_POST['vertical'] ?? 'general', $_POST['count'] ?? 5)); break; case 'analyze': echo json_encode($brain->analyzeContent($_POST['content'], $_POST['isp'] ?? 'Gmail')); break; case 'optimize': echo json_encode($brain->optimizeCampaign($_POST)); break; case 'suggest_offer': echo json_encode($brain->suggestOffer($_POST['segment'], $_POST['geos'] ?? [])); break; case 'troubleshoot': echo json_encode($brain->troubleshoot($_POST['issue'])); break; case 'best_isp': echo json_encode($brain->getBestISP($_GET['vertical'] ?? 'general')); break; case 'best_method': echo json_encode($brain->getBestMethod($_GET['isp'] ?? 'Gmail', $_GET['volume'] ?? 10000)); break; case 'health': echo json_encode($brain->getHealthStatus()); break; default: echo json_encode([ 'name' => 'Brain Core', 'description' => 'Central Intelligence with 11-provider AI failover + rule-based fallback', 'actions' => ['subjects','from_names','analyze','optimize','suggest_offer','troubleshoot','best_isp','best_method','health'] ]); }