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

/**
 * OTIS AdvisorEngine 2.0 — Cross-Module Intelligence Engine
 * Analyzes ALL system modules and generates correlated, prioritized insights.
 * Generates BOTH individual module insights AND cross-module pattern detections.
 */
class AdvisorEngine {
    private $db;
    private $userId;
    private $signals = [];
    private $crossPatterns = [];

    // Insight categories
    const CAT_HEALTH     = 'health';
    const CAT_FINANCE    = 'finance';
    const CAT_BEHAVIOR   = 'behavior';
    const CAT_HABITS     = 'habits';
    const CAT_JOURNAL    = 'journal';
    const CAT_SPIRITUAL  = 'spiritual';
    const CAT_EDUCATION  = 'education';
    const CAT_CALENDAR   = 'calendar';
    const CAT_CROSS      = 'cross';

    // Severity levels
    const SEV_CRITICAL  = 'critical';   // Red
    const SEV_WARNING   = 'warning';    // Orange
    const SEV_INFO      = 'info';       // Blue
    const SEV_POSITIVE  = 'positive';   // Green

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

    /**
     * Main entry point: generate all insights for a user
     * Returns structured array grouped by category
     */
    public function generateInsights(int $userId): array {
        $this->userId = $userId;
        $this->signals = [];
        $this->crossPatterns = [];

        // 1. Individual module analyzers
        $this->analyzeHealth();
        $this->analyzeFinance();
        $this->analyzeBehavior();
        $this->analyzeHabits();
        $this->analyzeJournal();
        $this->analyzeSpiritual();
        $this->analyzeEducation();
        $this->analyzeCalendar();

        // 2. Cross-module correlation engine
        $this->detectCorrelations();

        // 3. Apply recency filter (prevent repetition)
        $filtered = $this->applyRecencyFilter();

        // 4. Sort by priority weight (desc)
        usort($filtered, fn($a, $b) => $b['weight'] <=> $a['weight']);

        // 5. Group by category
        $grouped = [];
        foreach ($filtered as $signal) {
            $cat = $signal['category'] ?? self::CAT_CROSS;
            $grouped[$cat][] = $signal;
        }

        // 6. Compute summary stats
        $criticalCount = count(array_filter($filtered, fn($s) => $s['severity'] === self::SEV_CRITICAL));
        $warningCount  = count(array_filter($filtered, fn($s) => $s['severity'] === self::SEV_WARNING));
        $positiveCount = count(array_filter($filtered, fn($s) => $s['severity'] === self::SEV_POSITIVE));

        // 7. Top 2 for the dashboard widget
        $topInsights = array_slice($filtered, 0, 2);

        // 8. Log shown insights
        foreach ($topInsights as $s) {
            $this->logInsight($s['code']);
        }

        return [
            'all'        => $filtered,
            'grouped'    => $grouped,
            'top'        => $topInsights,
            'stats'      => [
                'total'    => count($filtered),
                'critical' => $criticalCount,
                'warning'  => $warningCount,
                'positive' => $positiveCount,
            ],
            'generated_at' => date('Y-m-d H:i:s'),
        ];
    }

    // ===========================================================
    // HEALTH ANALYZER
    // ===========================================================
    private function analyzeHealth(): void {
        try {
            // 1. Fasting compliance (last 7 days)
            $completedFasts = $this->db->query(
                "SELECT COUNT(*) FROM health_fasts WHERE user_id=? AND status='completed' AND end_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)",
                [$this->userId]
            )->fetchColumn();

            if ($completedFasts == 0) {
                $this->add('health_no_fasting', self::CAT_HEALTH, self::SEV_WARNING, 5.0,
                    '🏳️ لقد أهملت الصيام المتقطع لأسبوع كامل. الصيام ليس فقط للجسد بل لانضباط الإرادة. ابدأ الآن.'
                );
            }

            // 2. Weight logging consistency
            $weightLogs = $this->db->query(
                "SELECT COUNT(*) FROM health_weight_logs WHERE user_id=? AND logged_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            if ($weightLogs == 0) {
                $this->add('health_no_weight_log', self::CAT_HEALTH, self::SEV_INFO, 2.0,
                    '📊 لم تسجل وزنك هذا الأسبوع. التتبع المنتظم هو الفرق بين التحسن والركود.'
                );
            }

            // 3. Water intake check
            $waterToday = $this->db->query(
                "SELECT cups FROM health_water_logs WHERE user_id=? AND log_date=CURDATE() AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            $waterGoal = $this->db->query(
                "SELECT water_goal FROM health_profile WHERE user_id=?",
                [$this->userId]
            )->fetchColumn() ?: 8;
            $cupsGoal = ceil($waterGoal / 250);
            if ($waterToday !== false && (int)$waterToday < ($cupsGoal / 2) && (int)date('H') >= 14) {
                $this->add('health_low_water', self::CAT_HEALTH, self::SEV_WARNING, 3.5,
                    "💧 شربت {$waterToday} أكواب فقط حتى الآن. هدفك {$cupsGoal} كوب. الجفاف يضعف التركيز والطاقة."
                );
            }

            // 4. Active medications missed
            $activeMeds = $this->db->query(
                "SELECT COUNT(*) FROM health_medications WHERE user_id=? AND is_active=1 AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            if ($activeMeds > 0) {
                $takenToday = $this->db->query(
                    "SELECT COUNT(*) FROM health_med_logs WHERE user_id=? AND DATE(taken_at)=CURDATE() AND deleted_at IS NULL",
                    [$this->userId]
                )->fetchColumn();
                if ($takenToday == 0 && (int)date('H') >= 14) {
                    $this->add('health_missed_meds', self::CAT_HEALTH, self::SEV_CRITICAL, 6.0,
                        '💊 تجاوزنا الساعة الثانية ظهراً ولم تسجل أي دواء! صحتك أولوية فوق كل شيء.'
                    );
                }
            }

            // 5. Blood sugar trend (last 7 days — rising average)
            $avgBs = $this->db->query(
                "SELECT AVG(level) FROM health_blood_sugar WHERE user_id=? AND date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            if ($avgBs !== null && $avgBs > 140) {
                $this->add('health_high_blood_sugar', self::CAT_HEALTH, self::SEV_CRITICAL, 7.0,
                    "🩸 متوسط سكر الدم خلال الأسبوع ({$avgBs}) يتجاوز الحد الطبيعي. راجع نظامك الغذائي وأدويتك فوراً."
                );
            }

            // 6. Abnormal lab results (last 14 days)
            $abnormalLab = $this->db->query(
                "SELECT test_name, result_value FROM health_labs WHERE user_id=? AND is_abnormal=1 AND test_date >= DATE_SUB(CURDATE(), INTERVAL 14 DAY) AND deleted_at IS NULL ORDER BY test_date DESC LIMIT 1",
                [$this->userId]
            )->fetch(PDO::FETCH_OBJ);
            if ($abnormalLab) {
                $this->add('health_lab_abnormal', self::CAT_HEALTH, self::SEV_CRITICAL, 8.0,
                    "🔬 تحذير طبي: نتائج '{$abnormalLab->test_name}' غير طبيعية ({$abnormalLab->result_value}). لا تتجاهل هذا."
                );
            }
        } catch (\Exception $e) {
            error_log('[AdvisorEngine] Health analysis error: ' . $e->getMessage());
        }
    }

    // ===========================================================
    // FINANCE ANALYZER
    // ===========================================================
    private function analyzeFinance(): void {
        try {
            // 1. Weekly spending spike (vs prior week)
            $thisWeek = $this->db->query(
                "SELECT COALESCE(SUM(amount),0) FROM finance_expenses WHERE user_id=? AND expense_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            $lastWeek = $this->db->query(
                "SELECT COALESCE(SUM(amount),0) FROM finance_expenses WHERE user_id=? AND expense_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 14 DAY) AND DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();

            if ($lastWeek > 0 && $thisWeek > $lastWeek * 1.3) {
                $pct = round((($thisWeek - $lastWeek) / $lastWeek) * 100);
                $this->add('finance_weekly_spike', self::CAT_FINANCE, self::SEV_WARNING, 4.5,
                    "📈 مصاريفك هذا الأسبوع زادت بنسبة {$pct}% عن الأسبوع الماضي. راجع بنود الإنفاق الآن قبل أن تتفاقم."
                );
            }

            // 2. No income logged this month
            $monthlyIncome = $this->db->query(
                "SELECT COALESCE(SUM(amount),0) FROM finance_incomes WHERE user_id=? AND MONTH(date_received)=MONTH(CURDATE()) AND YEAR(date_received)=YEAR(CURDATE()) AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            if ($monthlyIncome == 0 && (int)date('j') > 5) {
                $this->add('finance_no_income', self::CAT_FINANCE, self::SEV_INFO, 2.5,
                    '💰 لم تسجل أي دخل هذا الشهر. هل نسيت التسجيل؟ الرصد الدقيق يصنع الفرق.'
                );
            }

            // 3. Unessential spending dominance
            $essentialSpend = $this->db->query(
                "SELECT COALESCE(SUM(amount),0) FROM finance_expenses WHERE user_id=? AND type='essential' AND MONTH(expense_date)=MONTH(CURDATE()) AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            $unessentialSpend = $this->db->query(
                "SELECT COALESCE(SUM(amount),0) FROM finance_expenses WHERE user_id=? AND type='unessential' AND MONTH(expense_date)=MONTH(CURDATE()) AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            if ($unessentialSpend > 0 && $essentialSpend > 0 && $unessentialSpend > $essentialSpend * 0.5) {
                $this->add('finance_unessential_high', self::CAT_FINANCE, self::SEV_WARNING, 3.5,
                    '🛍️ نفقاتك الكمالية تجاوزت 50% من نفقاتك الأساسية هذا الشهر. الانضباط المالي يبدأ بالوعي.'
                );
            }

            // 4. Saving goal stagnation
            $staleSavings = $this->db->query(
                "SELECT COUNT(*) FROM finance_saving_goals WHERE user_id=? AND current_amount < target_amount AND expected_date < CURDATE() AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            if ($staleSavings > 0) {
                $this->add('finance_stale_goals', self::CAT_FINANCE, self::SEV_WARNING, 3.0,
                    "🎯 لديك {$staleSavings} هدف ادخاري منتهي الأجل ولم يكتمل. هل تحتاج لإعادة الجدولة؟"
                );
            }

            // 5. Positive: No unessential spending this week
            if ($unessentialSpend == 0) {
                $this->add('finance_frugal_week', self::CAT_FINANCE, self::SEV_POSITIVE, 1.5,
                    '✨ أسبوع ممتاز مالياً! لم تُسجل أي مصاريف كمالية. هذا انضباط مالي حقيقي.'
                );
            }
        } catch (\Exception $e) {
            error_log('[AdvisorEngine] Finance analysis error: ' . $e->getMessage());
        }
    }

    // ===========================================================
    // BEHAVIOR ANALYZER
    // ===========================================================
    private function analyzeBehavior(): void {
        try {
            // 1. Repeated bad behavior
            $badBehavior = $this->db->query(
                "SELECT h.name, h.severity, COUNT(l.id) as fails
                 FROM behavior_logs l
                 JOIN behavior_habits h ON h.id = l.habit_id
                 WHERE h.user_id=? AND l.status=1 AND l.date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
                 GROUP BY l.habit_id
                 ORDER BY (CASE WHEN h.severity='high' THEN 3 WHEN h.severity='medium' THEN 2 ELSE 1 END) DESC, fails DESC
                 LIMIT 1",
                [$this->userId]
            )->fetch(PDO::FETCH_OBJ);

            if ($badBehavior && $badBehavior->fails >= 3) {
                $sev = $badBehavior->severity === 'high' ? self::SEV_CRITICAL : self::SEV_WARNING;
                $w   = $badBehavior->severity === 'high' ? 7.0 : 4.5;
                $this->add('behavior_repeated', self::CAT_BEHAVIOR, $sev, $w,
                    "⚠️ وقعت في '{$badBehavior->name}' {$badBehavior->fails} مرات هذا الأسبوع. النمط يتجذر. غيّر بيئتك فوراً."
                );
            }

            // 2. Discipline improvement (less fails vs prior week)
            $thisWeekFails = $this->db->query(
                "SELECT COUNT(*) FROM behavior_logs l JOIN behavior_habits h ON h.id=l.habit_id WHERE h.user_id=? AND l.status=1 AND l.date>=DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
                [$this->userId]
            )->fetchColumn();
            $lastWeekFails = $this->db->query(
                "SELECT COUNT(*) FROM behavior_logs l JOIN behavior_habits h ON h.id=l.habit_id WHERE h.user_id=? AND l.status=1 AND l.date BETWEEN DATE_SUB(CURDATE(), INTERVAL 14 DAY) AND DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
                [$this->userId]
            )->fetchColumn();
            if ($lastWeekFails > 0 && $thisWeekFails < $lastWeekFails * 0.7) {
                $this->add('behavior_improving', self::CAT_BEHAVIOR, self::SEV_POSITIVE, 2.5,
                    '🔥 سلوكياتك تتحسن! ارتكبت أخطاء أقل بكثير هذا الأسبوع مقارنة بالأسبوع الماضي. استمر في هذا المسار.'
                );
            }
        } catch (\Exception $e) {
            error_log('[AdvisorEngine] Behavior analysis error: ' . $e->getMessage());
        }
    }

    // ===========================================================
    // HABITS ANALYZER
    // ===========================================================
    private function analyzeHabits(): void {
        try {
            // 1. Habit streak check
            $habits = $this->db->query(
                "SELECT h.id, h.name, h.color_hex FROM habits h WHERE h.user_id=? AND h.deleted_at IS NULL",
                [$this->userId]
            )->fetchAll(PDO::FETCH_OBJ);

            $brokenStreaks = [];
            $longStreaks = [];
            foreach ($habits as $habit) {
                $loggedToday = $this->db->query(
                    "SELECT COUNT(*) FROM habit_logs WHERE habit_id=? AND user_id=? AND log_date=CURDATE() AND deleted_at IS NULL",
                    [$habit->id, $this->userId]
                )->fetchColumn();

                $streak = $this->calculateStreak($habit->id);

                if (!$loggedToday && $streak > 3) {
                    $brokenStreaks[] = ['name' => $habit->name, 'streak' => $streak];
                }
                if ($streak >= 7) {
                    $longStreaks[] = ['name' => $habit->name, 'streak' => $streak];
                }
            }

            if (!empty($brokenStreaks)) {
                $topBreak = $brokenStreaks[0];
                $this->add('habits_streak_risk', self::CAT_HABITS, self::SEV_WARNING, 4.0,
                    "🔥 سلسلة {$topBreak['streak']} يوم من عادة '{$topBreak['name']}' معرضة للانكسار اليوم! هل أتممتها؟"
                );
            }

            if (!empty($longStreaks)) {
                $top = $longStreaks[0];
                $this->add('habits_strong_streak', self::CAT_HABITS, self::SEV_POSITIVE, 2.0,
                    "🌟 سلسلة '{$top['name']}' وصلت {$top['streak']} يوماً متواصلاً. هذا مستوى انضباط متميز!"
                );
            }

            // 2. Zero habits logged today (after noon)
            $loggedCount = $this->db->query(
                "SELECT COUNT(DISTINCT h.id) FROM habit_logs l JOIN habits h ON h.id=l.habit_id WHERE l.user_id=? AND l.log_date=CURDATE() AND l.deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            if ($loggedCount == 0 && count($habits) > 0 && (int)date('H') >= 16) {
                $this->add('habits_none_logged', self::CAT_HABITS, self::SEV_WARNING, 3.5,
                    '📋 لم تسجل أي عادة اليوم ويومك في نهايته. العادات هي الأساس اليومي للتطور.'
                );
            }
        } catch (\Exception $e) {
            error_log('[AdvisorEngine] Habits analysis error: ' . $e->getMessage());
        }
    }

    // ===========================================================
    // JOURNAL ANALYZER
    // ===========================================================
    private function analyzeJournal(): void {
        try {
            $row = $this->db->query(
                "SELECT AVG(mood) as avg_mood, AVG(energy_level) as avg_energy, COUNT(*) as cnt FROM daily_journal WHERE user_id=? AND date >= DATE_SUB(CURDATE(), INTERVAL 5 DAY)",
                [$this->userId]
            )->fetch(PDO::FETCH_OBJ);

            if (!$row || $row->cnt == 0) return;

            $mood   = (float)$row->avg_mood;
            $energy = (float)$row->avg_energy;

            if ($mood <= 1.5) {
                $this->add('journal_very_low_mood', self::CAT_JOURNAL, self::SEV_CRITICAL, 5.5,
                    '🆘 يومياتك تُظهر مستوى مزاج خطير ومتدنٍ للغاية. لا تبقَ وحدك مع هذا، تحدث مع شخص تثق به.'
                );
            } elseif ($mood <= 2.5) {
                $this->add('journal_low_mood', self::CAT_JOURNAL, self::SEV_WARNING, 4.0,
                    '😔 مزاجك منخفض بشكل ملحوظ في الأيام الأخيرة. خذ استراحة حقيقية وغيّر روتينك.'
                );
            }

            if ($energy <= 2.0) {
                $this->add('journal_low_energy', self::CAT_JOURNAL, self::SEV_WARNING, 3.5,
                    '⚡ طاقتك الجسدية في حضيضها. راجع نوم ليلتك، وتأكد من جودة تغذيتك.'
                );
            }

            if ($mood >= 4.5 && $energy >= 4.0) {
                $this->add('journal_peak_state', self::CAT_JOURNAL, self::SEV_POSITIVE, 2.5,
                    '🚀 أنت في قمة أدائك نفسياً وجسدياً. الآن هو الوقت المثالي لإنجاز أصعب مهامك.'
                );
            }
        } catch (\Exception $e) {
            error_log('[AdvisorEngine] Journal analysis error: ' . $e->getMessage());
        }
    }

    // ===========================================================
    // SPIRITUAL ANALYZER
    // ===========================================================
    private function analyzeSpiritual(): void {
        try {
            // Missed Fajr today
            $fajr = $this->db->query(
                "SELECT fajr FROM spiritual_prayers WHERE user_id=? AND date=CURDATE()",
                [$this->userId]
            )->fetchColumn();
            if ($fajr !== false && $fajr == 0 && (int)date('H') >= 9) {
                $this->add('spiritual_fajr_missed', self::CAT_SPIRITUAL, self::SEV_WARNING, 2.5,
                    '🌙 ضياع صلاة الفجر يبدأ يومك على وتيرة خاطئة. جدد نيتك ولا تفوّت الظهر.'
                );
            }

            // No Quran for 3+ days
            $quranRecent = $this->db->query(
                "SELECT COUNT(*) FROM spiritual_quran WHERE user_id=? AND DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 3 DAY)",
                [$this->userId]
            )->fetchColumn();
            if ($quranRecent == 0) {
                $this->add('spiritual_no_quran', self::CAT_SPIRITUAL, self::SEV_WARNING, 2.0,
                    '📖 انقطعت عن القرآن الكريم لأكثر من 3 أيام. وردك اليومي هو ركيزة السكينة والتوازن.'
                );
            }

            // All 5 prayers done → positive
            $prayerRow = $this->db->query(
                "SELECT fajr, dhuhr, asr, maghrib, isha FROM spiritual_prayers WHERE user_id=? AND date=CURDATE()",
                [$this->userId]
            )->fetch(PDO::FETCH_OBJ);
            if ($prayerRow && ($prayerRow->fajr + $prayerRow->dhuhr + $prayerRow->asr + $prayerRow->maghrib + $prayerRow->isha) == 5) {
                $this->add('spiritual_full_prayers', self::CAT_SPIRITUAL, self::SEV_POSITIVE, 3.0,
                    '✨ أتممت الصلوات الخمس اليوم! هذا أساس متين لانضباط روحاني حقيقي. بارك الله فيك.'
                );
            }
        } catch (\Exception $e) {
            error_log('[AdvisorEngine] Spiritual analysis error: ' . $e->getMessage());
        }
    }

    // ===========================================================
    // EDUCATION ANALYZER
    // ===========================================================
    private function analyzeEducation(): void {
        try {
            $activeCourses = $this->db->query(
                "SELECT COUNT(*) FROM edu_courses WHERE user_id=? AND status='learning' AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();

            if ($activeCourses > 0) {
                $recentUpdate = $this->db->query(
                    "SELECT COUNT(*) FROM edu_courses WHERE user_id=? AND status='learning' AND updated_at >= DATE_SUB(CURDATE(), INTERVAL 3 DAY) AND deleted_at IS NULL",
                    [$this->userId]
                )->fetchColumn();
                if ($recentUpdate == 0) {
                    $this->add('education_stagnant', self::CAT_EDUCATION, self::SEV_INFO, 1.5,
                        '📚 لديك دورات نشطة لم تلمسها منذ 3 أيام. التعلم يحتاج استمرارية يومية لا شعلات متقطعة.'
                    );
                }
            }

            $overdueCourses = $this->db->query(
                "SELECT COUNT(*) FROM edu_courses WHERE user_id=? AND status!='completed' AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            if ($overdueCourses > 3) {
                $this->add('education_overloaded', self::CAT_EDUCATION, self::SEV_WARNING, 2.0,
                    "📖 لديك {$overdueCourses} دورة غير مكتملة. ركّز على دورة واحدة حتى تنهيها بدل التشتت."
                );
            }
        } catch (\Exception $e) {
            error_log('[AdvisorEngine] Education analysis error: ' . $e->getMessage());
        }
    }

    // ===========================================================
    // CALENDAR ANALYZER
    // ===========================================================
    private function analyzeCalendar(): void {
        try {
            // Events today not completed
            $todayEvents = $this->db->query(
                "SELECT COUNT(*) FROM calendar_events WHERE user_id=? AND event_date=CURDATE() AND status='active' AND deleted_at IS NULL",
                [$this->userId]
            )->fetchColumn();
            if ($todayEvents > 0 && (int)date('H') >= 18) {
                $this->add('calendar_events_today', self::CAT_CALENDAR, self::SEV_INFO, 2.0,
                    "📅 لديك {$todayEvents} حدث في التقويم اليوم. هل أتممتها جميعها قبل نهاية اليوم؟"
                );
            }

            // Upcoming important event within 2 days
            $upcoming = $this->db->query(
                "SELECT title, event_date FROM calendar_events WHERE user_id=? AND event_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 2 DAY) AND status='active' AND deleted_at IS NULL ORDER BY event_date LIMIT 1",
                [$this->userId]
            )->fetch(PDO::FETCH_OBJ);
            if ($upcoming) {
                $this->add('calendar_upcoming', self::CAT_CALENDAR, self::SEV_INFO, 1.5,
                    "⏰ حدث قادم خلال يومين: '{$upcoming->title}'. ابدأ التحضير مبكراً."
                );
            }
        } catch (\Exception $e) {
            error_log('[AdvisorEngine] Calendar analysis error: ' . $e->getMessage());
        }
    }

    // ===========================================================
    // CROSS-MODULE CORRELATION ENGINE
    // ===========================================================
    private function detectCorrelations(): void {
        // Pattern 1: Missed meds + Abnormal labs = URGENT
        if ($this->hasSignal('health_missed_meds') && $this->hasSignal('health_lab_abnormal')) {
            $this->addCross('cross_health_crisis', self::SEV_CRITICAL, 10.0,
                '🚨 تحذير طارئ: نتائج مخبرية غير طبيعية + إهمال الأدوية اليوم = خطر صحي حقيقي. أوقف كل شيء والتزم بعلاجك الآن.'
            );
        }

        // Pattern 2: Low mood + No Quran + No habits = Spiritual + Mental slump
        if ($this->hasSignal('journal_low_mood') && $this->hasSignal('spiritual_no_quran')) {
            $this->addCross('cross_spiritual_mental_slump', self::SEV_WARNING, 6.5,
                '💫 الانقطاع الروحاني يغذي تدني المزاج. ربط يومياتك بوردك القرآني هو جسر الأزمة.'
            );
        }

        // Pattern 3: Finance spike + Low mood = Emotional spending trigger
        if ($this->hasSignal('finance_weekly_spike') && $this->hasSignal('journal_low_mood')) {
            $this->addCross('cross_emotional_spending', self::SEV_WARNING, 5.5,
                '🧠 المزاج المنخفض + ارتفاع الإنفاق = نمط الشراء العاطفي. لا تُعالج المشاعر بالمحفظة.'
            );
        }

        // Pattern 4: Good habits + Spiritual full + Peak state = Reinforce!
        if ($this->hasSignal('habits_strong_streak') && $this->hasSignal('spiritual_full_prayers') && $this->hasSignal('journal_peak_state')) {
            $this->addCross('cross_peak_performance', self::SEV_POSITIVE, 4.0,
                '🏆 أنت في وضع مثالي متعدد الأبعاد: عباداتك منتظمة، عاداتك راسخة، وطاقتك في أوجها. استغل هذا المستوى!'
            );
        }

        // Pattern 5: Behavior worsening + Habits broken = Identity threat
        if ($this->hasSignal('behavior_repeated') && $this->hasSignal('habits_none_logged')) {
            $this->addCross('cross_identity_threat', self::SEV_CRITICAL, 8.0,
                '⚡ تكرار السلوكيات السيئة + إهمال العادات = هجوم على هويتك ومنظومة انضباطك. أوقف هذا النزيف اليوم.'
            );
        }

        // Pattern 6: Old sleep pattern from behavior declined productivity
        if ($this->hasSignal('habits_none_logged') && $this->hasSignal('journal_low_energy')) {
            $this->addCross('cross_sleep_productivity', self::SEV_WARNING, 5.0,
                '😴 قلة الالتزام بالعادات اليومية تتزامن مع انخفاض طاقتك. النوم الجيد + العادات = إنتاجية حقيقية.'
            );
        }

        // Pattern 7: Finance stagnation + Education stagnation = Wasted investment
        if ($this->hasSignal('education_stagnant') && $this->hasSignal('finance_unessential_high')) {
            $this->addCross('cross_wasted_investment', self::SEV_WARNING, 4.0,
                '📉 تُنفق في الكماليات بينما تهمل تطوير مهاراتك. استثمر في نفسك بدلاً من الأشياء المؤقتة.'
            );
        }
    }

    // ===========================================================
    // RECENCY FILTER — Prevent showing same insight every day
    // ===========================================================
    private function applyRecencyFilter(): array {
        try {
            $memRows = $this->db->query(
                "SELECT advice_code, DATE(last_shown_at) as last_date, show_count FROM advisor_memory WHERE user_id=?",
                [$this->userId]
            )->fetchAll(PDO::FETCH_ASSOC);

            $memory = [];
            foreach ($memRows as $row) {
                $memory[$row['advice_code']] = $row;
            }

            $today = date('Y-m-d');
            $yesterday = date('Y-m-d', strtotime('-1 day'));
            $filtered = [];

            foreach ($this->signals as $sig) {
                $code = $sig['code'];
                $w = $sig['weight'];

                if (isset($memory[$code])) {
                    $m = $memory[$code];
                    // Hard stop: shown 5+ times in 7 days
                    if ($m['show_count'] >= 5 && $m['last_date'] > date('Y-m-d', strtotime('-7 day'))) {
                        continue; // Skip entirely
                    }
                    if ($m['last_date'] === $today) $w *= 0.05;
                    elseif ($m['last_date'] === $yesterday) $w *= 0.3;
                }

                if ($w > 0) {
                    $sig['weight'] = $w;
                    $filtered[] = $sig;
                }
            }

            if (empty($filtered)) {
                $filtered[] = $this->makeSignal('general_all_clear', self::CAT_CROSS, self::SEV_POSITIVE, 0.1,
                    '☀️ يومك هادئ بلا إشارات طارئة. استمتع بصحبة من تحب أو اقرأ كتاباً ينمي عقلك.'
                );
            }

            return $filtered;
        } catch (\Exception $e) {
            return array_values($this->signals);
        }
    }

    // ===========================================================
    // HELPERS
    // ===========================================================
    private function add(string $code, string $category, string $severity, float $weight, string $message): void {
        $this->signals[$code] = $this->makeSignal($code, $category, $severity, $weight, $message);
    }

    private function addCross(string $code, string $severity, float $weight, string $message): void {
        $this->signals[$code] = $this->makeSignal($code, self::CAT_CROSS, $severity, $weight, $message);
    }

    private function makeSignal(string $code, string $category, string $severity, float $weight, string $message): array {
        return [
            'code'     => $code,
            'category' => $category,
            'severity' => $severity,
            'weight'   => $weight,
            'message'  => $message,
            'icon'     => $this->getCategoryIcon($category),
            'color'    => $this->getSeverityColor($severity),
        ];
    }

    private function hasSignal(string $code): bool {
        return isset($this->signals[$code]);
    }

    private function calculateStreak(int $habitId): int {
        $streak = 0;
        $date = new \DateTime();
        for ($i = 0; $i < 365; $i++) {
            $dateStr = $date->format('Y-m-d');
            $logged = $this->db->query(
                "SELECT COUNT(*) FROM habit_logs WHERE habit_id=? AND user_id=? AND log_date=? AND deleted_at IS NULL",
                [$habitId, $this->userId, $dateStr]
            )->fetchColumn();
            if ($logged > 0) {
                $streak++;
                $date->modify('-1 day');
            } else {
                break;
            }
        }
        return $streak;
    }

    private function logInsight(string $code): void {
        if ($code === 'general_all_clear') return;
        try {
            $this->db->query(
                "INSERT INTO advisor_memory (user_id, advice_code, last_shown_at, show_count)
                 VALUES (?, ?, NOW(), 1)
                 ON DUPLICATE KEY UPDATE last_shown_at=NOW(), show_count=IF(DATE(last_shown_at)>DATE_SUB(CURDATE(),INTERVAL 7 DAY), show_count+1, 1)",
                [$this->userId, $code]
            );
        } catch (\Exception $e) { /* Non-critical */ }
    }

    private function getCategoryIcon(string $category): string {
        return match($category) {
            self::CAT_HEALTH    => 'fa-heart-pulse',
            self::CAT_FINANCE   => 'fa-wallet',
            self::CAT_BEHAVIOR  => 'fa-brain',
            self::CAT_HABITS    => 'fa-fire',
            self::CAT_JOURNAL   => 'fa-book-open',
            self::CAT_SPIRITUAL => 'fa-kaaba',
            self::CAT_EDUCATION => 'fa-graduation-cap',
            self::CAT_CALENDAR  => 'fa-calendar-days',
            self::CAT_CROSS     => 'fa-circle-nodes',
            default             => 'fa-lightbulb',
        };
    }

    private function getSeverityColor(string $severity): string {
        return match($severity) {
            self::SEV_CRITICAL => '#dc3545',
            self::SEV_WARNING  => '#fd7e14',
            self::SEV_POSITIVE => '#198754',
            self::SEV_INFO     => '#0d6efd',
            default            => '#6c757d',
        };
    }

    /**
     * Get AJAX-friendly quick insights (top 3, no recency filter)
     * Used by dashboard widget
     */
    public function getQuickInsights(int $userId): array {
        $this->userId = $userId;
        $this->signals = [];
        $this->analyzeHealth();
        $this->analyzeFinance();
        $this->analyzeBehavior();
        $this->analyzeHabits();
        $this->analyzeJournal();
        $this->detectCorrelations();

        $all = array_values($this->signals);
        usort($all, fn($a, $b) => $b['weight'] <=> $a['weight']);
        return array_slice($all, 0, 3);
    }
}
