<?php
namespace App\Modules\Core\Controllers;

class HomeController extends \Core\Controller {

    public function index() {
        // ── 1. Time Context & Evening Mode ───────────────────────
        $hour = (int)date('H');
        $isEveningMode = ($hour >= 18);
        $timeContext = $isEveningMode ? 'وضع المراجعة المسائية' : (($hour >= 5 && $hour < 12) ? 'صباح الخير والتركيز' : 'استمر في تقدمك');

        // ── 2. Todo Summary (Today Focus) ─────────────────────────
        $todo = $this->model('Todo/Models/TodoModel');
        $tasksToday = $todo->getDashboardTasks($this->userId, date('Y-m-d'));
        
        $pendingTasks = [];
        $completedTasks = [];
        $overdueTasks = [];

        foreach($tasksToday as $t) {
            if ($t->status === 'done') {
                $completedTasks[] = $t;
            } else {
                $pendingTasks[] = $t;
                if (isset($t->is_overdue) && $t->is_overdue) {
                    $overdueTasks[] = $t;
                }
            }
        }

        $tasksTotal = count($tasksToday);
        $tasksDone = count($completedTasks);
        $pctTasks = $tasksTotal > 0 ? round(($tasksDone / $tasksTotal) * 100) : ($hour > 5 ? 0 : 100);

        // Find primary task: First undone high-priority task, or any undone task
        $primaryTask = null;
        if (!empty($pendingTasks)) {
            $highPri = array_filter($pendingTasks, fn($t) => $t->priority === 'high');
            $primaryTask = !empty($highPri) ? array_values($highPri)[0] : $pendingTasks[0];
        }

        // ── 3. Health Alerts & Fasts ──────────────────────────────
        $health = $this->model('Health/Models/HealthModel');
        $activeFast = $health->getActiveFast($this->userId);
        
        $healthAlerts = [];
        if ($activeFast) {
            $fastingHours = round((time() - strtotime($activeFast->start_time)) / 3600, 1);
            $healthAlerts[] = ['type' => 'info', 'text' => "صيام نشط منذ {$fastingHours} ساعة."];
        } else {
            $healthAlerts[] = ['type' => 'warning', 'text' => 'لا يوجد صيام نشط حالياً.'];
        }

        // Water tracker
        $waterToday = $health->getTodayWater($this->userId);

        // ── 4. Spiritual Status ───────────────────────────────────
        $spiritual = $this->model('Spiritual/Models/SpiritualModel');
        $spiritualData = $spiritual->getDailyData($this->userId, date('Y-m-d'));
        $pctSpiritual = $spiritualData['progress'] ?? 0;
        $spiritualState = $spiritualData['state'] ?? 'medium';
        $spiritualConsistency = $spiritualData['consistency'] ?? 50;
        
        // ── 5. DES: Behavior & Habits (Unified Discipline) ────────
        $biService = $this->service('BehaviorIntelligenceService');
        $disciplineScore = $biService->getUnifiedDisciplineScore($this->userId);
        $identityNarrative = $biService->getIdentityNarrative($disciplineScore);
        $momentumScore = $biService->getMomentumScore($this->userId);
        $streakRisks = $biService->detectStreakRisk($this->userId);

        $db = \Core\Database::getInstance();
        $failsToday = $db->query("SELECT COUNT(l.id) as c FROM behavior_logs l JOIN behavior_habits h ON h.id = l.habit_id WHERE h.user_id = ? AND l.date = CURDATE() AND l.status = 1", [$this->userId])->fetch()->c ?? 0;
        $pctBehavior = $failsToday > 0 ? max(0, 100 - ($failsToday * 20)) : 100; // legacy fallback

        // ── 6. Finance Status ─────────────────────────────────────
        $spentToday = $db->query("SELECT SUM(amount) as s FROM finance_expenses WHERE user_id = ? AND expense_date = CURDATE() AND deleted_at IS NULL", [$this->userId])->fetch()->s ?? 0;

        // ── 7. Daily Score Calculation ────────────────────────────
        $hasActivityToday = ($tasksTotal > 0) || ($spiritualData['progress'] ?? 0 > 0) || ($failsToday > 0) || ($waterToday > 0) || ($spentToday > 0);
        if (!$hasActivityToday && $tasksDone == 0) {
            $dailyScore = 0;
        } else {
            $dailyScore = round(($pctTasks + $pctSpiritual + $pctBehavior) / 3);
        }

        // ── 8. Smart Action Logic (Decision-Driven) ───────────────
        $smartAction = null;
        if ($primaryTask && !$isEveningMode) {
            if ($primaryTask->priority === 'high') {
                $smartAction = ['text' => "أولوية قصوى: ابدأ فوراً بالمهمة [ {$primaryTask->title} ]", 'type' => 'danger', 'icon' => 'fa-bolt'];
            } else {
                $smartAction = ['text' => "خطوتك القادمة: إنجاز [ {$primaryTask->title} ]", 'type' => 'primary', 'icon' => 'fa-arrow-right'];
            }
        } elseif ($spentToday > 500) {
            $smartAction = ['text' => "تنبيه: مصروفاتك اليوم بلغت {$spentToday} ج.م، راقب نفقاتك.", 'type' => 'warning', 'icon' => 'fa-wallet'];
        } elseif ($pctSpiritual < 50 && $hour > 15) {
            $smartAction = ['text' => "أنت متأخر في الجانب الروحي اليوم، تدارك الأمر الآن.", 'type' => 'warning', 'icon' => 'fa-moon'];
        } elseif ($isEveningMode && $tasksDone < $tasksTotal) {
            $smartAction = ['text' => "المساء يقترب وهناك مهام معلقة، حاول إنهاء ما تبقى أو إعادة جدولته.", 'type' => 'warning', 'icon' => 'fa-clock'];
        } elseif ($isEveningMode) {
            $smartAction = ['text' => "يوم جيد! قم بإنهاء اليوم بتسجيل تقييمك ومراجعة أحداثه.", 'type' => 'success', 'icon' => 'fa-check-double'];
        } else {
            $smartAction = ['text' => "كل شيء تحت السيطرة. استمر!", 'type' => 'success', 'icon' => 'fa-check-circle'];
        }

        // ── 9. Upcoming Events (Today only) ───────────────────────
        $calModel = $this->model('Calendar/Models/CalendarModel');
        $rawEvents = $calModel->getUpcomingEvents($this->userId, 5);
        $todayEvents = array_filter($rawEvents, fn($e) => $e->event_date === date('Y-m-d'));

        // ── 10. UserProfileEngine Intelligence (Decision Engine) ──────
        // DB-cached daily. Only re-runs on new day.
        require_once __DIR__ . '/../../../../core/Services/UserProfileEngine.php';
        $intelligence = \Core\Services\UserProfileEngine::getInstance()->getIntelligence($this->userId);
        $advisorInsights  = $intelligence['insights'];
        $systemDecisions  = $intelligence['decisions'];

        // Top 1-2 CRITICAL/WARNING insights for dashboard radar widget
        $radarInsight = null;
        foreach ($advisorInsights as $sig) {
            $sev = $sig['severity'] ?? ($sig['type'] ?? 'info');
            if (in_array(strtolower($sev), ['critical', 'warning'])) {
                $radarInsight = $sig;
                break;
            }
        }

        $this->view('Core/Views/home', [
            'title'          => 'مركز القيادة | OTIS Life System',
            'timeContext'    => $timeContext,
            'isEveningMode'  => $isEveningMode,
            'primaryTask'    => $primaryTask,
            'pendingTasks'   => $pendingTasks,
            'overdueTasks'   => $overdueTasks,
            'completedTasks' => $completedTasks,
            'tasksTotal'     => $tasksTotal,
            'tasksDone'      => $tasksDone,
            'pctTasks'       => $pctTasks,
            'healthAlerts'   => $healthAlerts,
            'waterToday'     => $waterToday,
            'pctSpiritual'   => $pctSpiritual,
            'spiritualState' => $spiritualState,
            'spiritualConsistency' => $spiritualConsistency,
            'pctBehavior'    => $pctBehavior,
            'failsToday'     => $failsToday,
            'spentToday'     => $spentToday,
            'dailyScore'     => $dailyScore,
            'disciplineScore'=> $disciplineScore,
            'identityNarrative' => $identityNarrative,
            'momentumScore'  => $momentumScore,
            'streakRisks'    => $streakRisks,
            'smartAction'    => $smartAction,
            'todayEvents'    => $todayEvents,
            'advisorInsights'=> $advisorInsights,
            'systemDecisions'=> $systemDecisions,
            'radarInsight'   => $radarInsight,
        ]);
    }

    public function menu() {
        // Build an array of system badges to pass to the menu view
        $unreadCount = \Core\Database::getInstance()->query("SELECT COUNT(*) as c FROM notifications WHERE user_id = ? AND is_read = 0", [$this->userId])->fetch()->c ?? 0;
        $calCount = count($this->model('Calendar/Models/CalendarModel')->getEventsByDate($this->userId, date('Y-m-d')));
        
        $this->view('Core/Views/menu', [
            'title' => 'القائمة | OTIS',
            'unreadCount' => $unreadCount,
            'calCount' => $calCount,
        ]);
    }

    // AJAX Endpoint
    public function dismissNudge() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            echo json_encode(['success' => true]);
            exit;
        }
    }
}
