<?php
namespace App\Modules\MonthlyPlan\Models;

class MonthlyplanModel extends \Core\Model {
    // Uses hard DELETE with FK cascade. No soft delete pattern.
    protected $useSoftDeletes = false;
    protected $logActions = false;

    public function getOrCreatePlan($userId, $monthKey) {
        $plan = $this->db->query("SELECT * FROM monthly_plans WHERE user_id = ? AND month_key = ?", [$userId, $monthKey])->fetch(\PDO::FETCH_OBJ);
        if (!$plan) {
            $this->db->query("INSERT INTO monthly_plans (user_id, month_key) VALUES (?, ?)", [$userId, $monthKey]);
            return $this->db->query("SELECT * FROM monthly_plans WHERE id = ?", [$this->db->lastInsertId()])->fetch(\PDO::FETCH_OBJ);
        }
        return $plan;
    }

    public function getCategories($userId) {
        $cats = $this->db->query("SELECT * FROM monthly_plan_categories WHERE user_id = ? ORDER BY id", [$userId])->fetchAll(\PDO::FETCH_OBJ);
        return $cats;
    }

    private function ensureDefaultCategories($userId) {
        $defaults = [
            ['name' => 'المهام والانتاجية', 'icon' => 'fa-list-check', 'color_theme' => 'primary'],
            ['name' => 'الصحة والرياضة', 'icon' => 'fa-heart-pulse', 'color_theme' => 'danger'],
            ['name' => 'المالية والادخار', 'icon' => 'fa-wallet', 'color_theme' => 'success'],
            ['name' => 'التعلم والمهارات', 'icon' => 'fa-graduation-cap', 'color_theme' => 'info'],
            ['name' => 'سلوكيات وعادات', 'icon' => 'fa-brain', 'color_theme' => 'warning'],
            ['name' => 'مشاريع وأخرى', 'icon' => 'fa-star', 'color_theme' => 'secondary']
        ];
        foreach ($defaults as $d) {
            $this->db->query("INSERT IGNORE INTO monthly_plan_categories (user_id, name, icon, color_theme) VALUES (?, ?, ?, ?)", [$userId, $d['name'], $d['icon'], $d['color_theme']]);
        }
    }

    public function addCategory($userId, $data) {
        $sql = "INSERT INTO monthly_plan_categories (user_id, name, icon, color_theme) VALUES (?, ?, ?, ?)";
        $this->db->query($sql, [$userId, $data['name'], $data['icon'], $data['color_theme']]);
        return $this->db->lastInsertId();
    }

    public function deleteCategory($userId, $id) {
        // FK constraint ON DELETE SET NULL will handle the goals category_id.
        return $this->db->query("DELETE FROM monthly_plan_categories WHERE id = ? AND user_id = ?", [$id, $userId]);
    }

    public function getGoals($planId) {
        return $this->db->query("
            SELECT g.*, c.name as cat_name, c.icon as cat_icon, c.color_theme as cat_color 
            FROM monthly_goals g 
            LEFT JOIN monthly_plan_categories c ON c.id = g.category_id 
            WHERE g.plan_id = ? 
            ORDER BY g.is_primary DESC, c.id, g.id
        ", [$planId])->fetchAll(\PDO::FETCH_OBJ);
    }

    public function addGoal($planId, $data) {
        $difficulty = $data['difficulty'] ?? 'medium';
        $sql = "INSERT INTO monthly_goals (plan_id, category_id, title, target_value, integration_type, integration_ref, difficulty) VALUES (?, ?, ?, ?, ?, ?, ?)";
        return $this->db->query($sql, [
            $planId, 
            $data['category_id'], 
            $data['title'], 
            $data['target_value'] ?? 0, 
            $data['integration_type'] ?? 'manual',
            $data['integration_ref'] ?? null,
            $difficulty
        ]);
    }

    public function deleteGoal($goalId, $planId) {
        return $this->db->query("DELETE FROM monthly_goals WHERE id = ? AND plan_id = ?", [$goalId, $planId]);
    }

    public function updateManualProgress($goalId, $planId, $progress) {
        $sql = "UPDATE monthly_goals SET current_progress = ? WHERE id = ? AND plan_id = ? AND integration_type = 'manual'";
        return $this->db->query($sql, [$progress, $goalId, $planId]);
    }

    public function setPrimaryGoal($goalId, $planId) {
        $this->db->query("UPDATE monthly_goals SET is_primary = 0 WHERE plan_id = ?", [$planId]);
        return $this->db->query("UPDATE monthly_goals SET is_primary = 1 WHERE id = ? AND plan_id = ?", [$goalId, $planId]);
    }

    public function saveReflection($planId, $userId, $data) {
        $sql = "UPDATE monthly_plans SET reflection_worked = ?, reflection_failed = ?, reflection_why = ? WHERE id = ? AND user_id = ?";
        return $this->db->query($sql, [$data['worked'], $data['failed'], $data['why'], $planId, $userId]);
    }

    public function syncAutomatedGoals($userId, $planId, $monthKey) {
        $goals = $this->getGoals($planId);

        foreach ($goals as $goal) {
            if ($goal->integration_type === 'manual') continue;

            $progress = 0;

            switch ($goal->integration_type) {
                case 'tasks_done':
                    $progress = $this->db->query(
                        "SELECT COUNT(*) FROM todo_tasks WHERE user_id = ? AND status = 'done' AND DATE_FORMAT(target_date, '%Y-%m') = ?",
                        [$userId, $monthKey]
                    )->fetchColumn();
                    break;

                case 'finance_spent':
                    $progress = $this->db->query(
                        "SELECT SUM(amount) FROM finance_expenses WHERE user_id = ? AND DATE_FORMAT(expense_date, '%Y-%m') = ?",
                        [$userId, $monthKey]
                    )->fetchColumn() ?: 0;
                    break;
                
                case 'finance_income':
                    $progress = $this->db->query(
                        "SELECT SUM(amount) FROM finance_incomes WHERE user_id = ? AND DATE_FORMAT(date_received, '%Y-%m') = ?",
                        [$userId, $monthKey]
                    )->fetchColumn() ?: 0;
                    break;

                case 'health_workouts':
                    $progress = $this->db->query(
                        "SELECT COUNT(*) FROM health_activities WHERE user_id = ? AND DATE_FORMAT(log_date, '%Y-%m') = ?",
                        [$userId, $monthKey]
                    )->fetchColumn();
                    break;

                case 'education_courses':
                    // We assume courses completed during this month
                    $progress = $this->db->query(
                        "SELECT COUNT(*) FROM edu_courses WHERE user_id = ? AND status = 'completed' AND DATE_FORMAT(updated_at, '%Y-%m') = ?",
                        [$userId, $monthKey]
                    )->fetchColumn();
                    break;
                
                case 'behavior_fails':
                    $progress = $this->db->query(
                        "SELECT COUNT(l.id) FROM behavior_logs l JOIN behavior_habits h ON h.id = l.habit_id WHERE h.user_id = ? AND l.status = 1 AND DATE_FORMAT(l.date, '%Y-%m') = ?",
                        [$userId, $monthKey]
                    )->fetchColumn();
                    break;
            }

            // Status check
            $status = ($progress >= $goal->target_value && $goal->target_value > 0) ? 'completed' : 'active';
            
            if ($progress !== (int)$goal->current_progress || $status !== $goal->status) {
                $this->db->query(
                    "UPDATE monthly_goals SET current_progress = ?, status = ? WHERE id = ?",
                    [$progress, $status, $goal->id]
                );
            }
        }
    }

    public function getStrategicInsights($userId, $planId, $monthKey, $goals) {
        $insights = [];
        
        // 1. Conflict Detection: Too many hard goals
        $hardCount = count(array_filter($goals, fn($g) => $g->difficulty === 'hard'));
        if ($hardCount >= 3) {
            $insights[] = [
                'type' => 'danger',
                'title' => 'تنبيه: أهدافك الحالية قد تسبب ضغط عالي',
                'message' => 'لقد خططت لـ ' . $hardCount . ' أهداف صعبة. استنزاف طاقتك باكراً قد يؤدي للإحباط. فكر في تخفيف العبء أو تأجيل شيء للشهر القادم.'
            ];
        }

        // 2. Reality Check (Energy Integration from Journal)
        $avgEnergy = $this->db->query("SELECT AVG(energy_level) FROM daily_journal WHERE user_id = ? AND DATE_FORMAT(date, '%Y-%m') = ?", [$userId, $monthKey])->fetchColumn();
        if ($avgEnergy && $avgEnergy < 3 && count($goals) > 4) {
            $insights[] = [
                'type' => 'warning',
                'title' => 'سلوكك اليومي لا يدعم هدفك',
                'message' => 'متوسط طاقتك المسجلة في اليوميات منخفض (' . round($avgEnergy, 1) . '/5) بينما تطارد الكثير من الأهداف في نفس الوقت. قم بتبسيط استراتيجيتك.'
            ];
        }

        // 3. Pace reminder for end of month
        $dayOfMonth = (int)date('d');
        if ($dayOfMonth >= 25) {
            $incomplete = count(array_filter($goals, fn($g) => $g->status !== 'completed'));
            if ($incomplete > 0) {
                $insights[] = [
                    'type' => 'primary',
                    'title' => 'استراتيجية النهاية (Endgame)',
                    'message' => 'باقي أيام قليلة على نهاية الشهر وهناك ' . $incomplete . ' أهداف معلقة. ركز على هدفك الأساسي (النجمة ⭐) واترك الباقي للمشروع القادم.'
                ];
            }
        }

        return $insights;
    }

    public function getMonthlyScore($goals, $totalCategoriesCount = 5) {
        if (empty($goals)) return ['score' => 0, 'completion' => 0, 'consistency' => 0, 'balance' => 0, 'label' => 'لم يتم التخطيط بعد'];

        $totalGoals = count($goals);
        $completed = count(array_filter($goals, fn($g) => $g->status === 'completed' || ($g->target_value > 0 && $g->current_progress >= $g->target_value)));
        
        $completionPct = round(($completed / $totalGoals) * 100);

        // Consistency
        $startedGoals = count(array_filter($goals, fn($g) => $g->current_progress > 0));
        $consistency = round(($startedGoals / $totalGoals) * 100);

        // Balance
        $categoriesHit = [];
        foreach($goals as $g) { $categoriesHit[$g->category_id] = true; }
        $base = max(1, $totalCategoriesCount); // Prevent division by zero
        $balance = min(100, round((count($categoriesHit) / $base) * 100)); 

        $score = round(($completionPct + $consistency + $balance) / 3);

        if ($score >= 80) $label = 'ممتاز 🌟';
        elseif ($score >= 50) $label = 'جيد 👍';
        else $label = 'ضعيف ⚠️';

        return [
            'score' => $score,
            'completion' => $completionPct,
            'consistency' => $consistency,
            'balance' => $balance,
            'label' => $label
        ];
    }
}
