<?php
namespace Core\Services;
use Core\Database;

class UserProfileEngine {
    private static $instance = null;
    private $db;

    private function __construct() {
        $this->db = Database::getInstance();
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new UserProfileEngine();
        }
        return self::$instance;
    }

    /**
     * Engine calculating behavior into dynamic decisions based on Advisor Signals.
     * Caches 1 time per day.
     */
    public function getIntelligence($userId) {
        $today = date('Y-m-d');
        
        // 1. Check cache
        $cache = $this->db->query("SELECT * FROM intelligence_cache WHERE user_id = ? AND date_cached = ?", [$userId, $today])->fetch();
        if ($cache) {
            return [
                'discipline_score' => (int)$cache->discipline_score,
                'insights' => json_decode($cache->insights_json, true) ?? [],
                'decisions' => json_decode($cache->decisions_json, true) ?? []
            ];
        }

        // 2. Fetch Deep Signals from Advisor Engine (Part 1 - Keep Current Analyzers)
        require_once __DIR__ . '/AdvisorEngine.php';
        $advisor = new \Core\Services\AdvisorEngine();
        $advisorData = $advisor->generateInsights($userId);
        
        $insights = $advisorData['all'];

        // 3. DECISION ENGINE LAYER (Part 2)
        $decisions = [
            'xp_multiplier' => 1.0,
            'recovery_mode' => false,
            'high_risk_finance' => false,
            'budget_lock_suggested' => false,
            'highlight_weak_habits' => false
        ];
        
        $disciplineScore = 100;

        foreach ($insights as $insight) {
            // Apply weight to discipline score
            if ($insight['severity'] === 'critical') $disciplineScore -= 20;
            if ($insight['severity'] === 'warning') $disciplineScore -= 10;
            if ($insight['severity'] === 'positive') $disciplineScore += 5;

            // Decision Triggers based on Specific Insights
            if ($insight['code'] === 'finance_weekly_spike' || $insight['code'] === 'finance_unessential_high') {
                $decisions['high_risk_finance'] = true;
                $decisions['budget_lock_suggested'] = true;
            }

            if ($insight['code'] === 'habits_streak_risk' || $insight['code'] === 'habits_none_logged') {
                $decisions['highlight_weak_habits'] = true;
            }
            
            if ($insight['code'] === 'habits_strong_streak') {
                $decisions['xp_multiplier'] += 0.2;
            }
        }

        // Finalize Discipline
        $disciplineScore = max(0, min(100, $disciplineScore));
        
        // System Actions based on Final Score
        if ($disciplineScore < 50) {
            $decisions['recovery_mode'] = true;
            // Inject emergency insight
            array_unshift($insights, [
                'type' => 'CRITICAL', 'severity' => 'critical', 'color' => '#dc3545', 'icon'=>'fa-triangle-exclamation',
                'msg' => 'النظام أعلن [حالة الطوارئ]. لقد تم تفعيل وضع التعافي! ركز على المهام المصيرية فقط.'
            ]);
        } elseif ($disciplineScore >= 90) {
            $decisions['xp_multiplier'] += 0.3; // Boost
            array_unshift($insights, [
                'type' => 'INFO', 'severity' => 'positive', 'color' => '#198754', 'icon'=>'fa-bolt',
                'msg' => 'تفعيل [Titan Mode]: انضباط فائق! مضاعف النقاط (Boost) يعمل بأقصى طاقته الآن.'
            ]);
        }

        // Clean arrays
        foreach($insights as &$i) {
            $i['msg'] = $i['message'] ?? $i['msg'];
        }

        // Cache the outcome
        $this->db->query("DELETE FROM intelligence_cache WHERE user_id = ?", [$userId]);
        $this->db->query("INSERT INTO intelligence_cache (user_id, date_cached, discipline_score, insights_json, decisions_json) VALUES (?, ?, ?, ?, ?)", [
            $userId, $today, $disciplineScore, json_encode($insights, JSON_UNESCAPED_UNICODE), json_encode($decisions, JSON_UNESCAPED_UNICODE)
        ]);

        return [
            'discipline_score' => (int)$disciplineScore,
            'insights' => $insights,
            'decisions' => $decisions
        ];
    }
}
