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

class EducationModel extends \Core\Model {
    protected $moduleName = 'Education';
    // Uses its own softDelete() with allowedTables check. Base Model::delete() not used.
    protected $useSoftDeletes = false;
    
    public function __construct() {
        parent::__construct();
        $this->ensureSchemaUpdated();
    }

    private function ensureSchemaUpdated() {
        try {
            $this->query("CREATE TABLE IF NOT EXISTS edu_paths (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT, name VARCHAR(255), goal VARCHAR(255), expected_roi DECIMAL(10,2) DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, deleted_at TIMESTAMP NULL DEFAULT NULL)");
            $this->query("ALTER TABLE edu_courses ADD COLUMN IF NOT EXISTS path_id INT DEFAULT NULL;");
            $this->query("ALTER TABLE edu_courses ADD COLUMN IF NOT EXISTS expected_roi DECIMAL(10,2) DEFAULT 0;");
            $this->query("ALTER TABLE edu_skills ADD COLUMN IF NOT EXISTS last_activity_date DATE DEFAULT NULL;");
            $this->query("ALTER TABLE edu_skills ADD COLUMN IF NOT EXISTS intelligence_status ENUM('strong', 'weak', 'needs_improvement') DEFAULT 'needs_improvement';");
        } catch (\Exception $e) {}
    }

    // --- LEARNING PATHS ---
    public function addPath($userId, $data) {
        $sql = "INSERT INTO edu_paths (user_id, name, goal, expected_roi) VALUES (?, ?, ?, ?)";
        return $this->query($sql, [$userId, $data['name'], $data['goal'], $data['expected_roi'] ?? 0]);
    }

    public function getPaths($userId) {
        return $this->query("SELECT * FROM edu_paths WHERE user_id = ? AND deleted_at IS NULL ORDER BY created_at DESC", [$userId])->fetchAll();
    }
    
    // --- SMART TASKS (Todo Sync) ---
    public function generateSmartTask($userId, $courseId, $title) {
        $db = \Core\Database::getInstance();
        $sql = "INSERT INTO todo_tasks (user_id, title, category, priority, status, target_date) VALUES (?, ?, ?, ?, ?, ?)";
        // 'Education' or 'تعليم' as category
        $res = $db->query($sql, [$userId, "جلسة تعلم: " . $title, "تعليم", "medium", "pending", date('Y-m-d')]);
        $this->logAction($userId, 'created', "خطوة ذكية للتعلم مضافة كمهام: {$title}");
        return $res;
    }

    // --- MOMENTUM SCORE ---
    public function getMomentumScore($userId) {
        $rows = $this->query("SELECT created_at as date, action FROM action_logs WHERE user_id = ? AND action IN ('achieved', 'completed', 'updated') AND description LIKE '%دورة%' AND created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)", [$userId])->fetchAll();
        $daysActive = [];
        foreach($rows as $r) {
            $daysActive[date('Y-m-d', strtotime($r->date))] = true;
        }
        $score = count($daysActive) * 15; 
        return min(100, max(0, $score));
    }
    
    // --- COURSES ---
    public function addCourse($userId, $data) {
        $sql = "INSERT INTO edu_courses (user_id, title, provider, skill_id, category, is_paid, cost, status, url, path_id, expected_roi) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $res = $this->query($sql, [
            $userId, 
            $data['title'], 
            $data['provider'] ?? null,
            (!empty($data['skill_id']) ? $data['skill_id'] : null), 
            $data['category'] ?? 'General', 
            (!empty($data['is_paid']) ? 1 : 0), 
            $data['cost'] ?? 0, 
            $data['status'] ?? 'planned', 
            $data['url'] ?? null,
            (!empty($data['path_id']) ? $data['path_id'] : null),
            $data['expected_roi'] ?? 0
        ]);
        
        // INTELLIGENCE: Finance Integration immediately treats paid courses as investments
        if (!empty($data['is_paid']) && $data['cost'] > 0) {
            $db = \Core\Database::getInstance();
            // find education category or fallback to 1 
            $catId = $db->query("SELECT id FROM finance_categories WHERE user_id = ? AND (type='expense' AND (name LIKE '%تعليم%' OR name LIKE '%تطوير%')) LIMIT 1", [$userId])->fetch()->id ?? null;
            if (!$catId) {
                $db->query("INSERT INTO finance_categories (user_id, name, type, color, icon) VALUES (?, 'تعليم وتطوير', 'expense', '#3b82f6', 'fa-book')", [$userId]);
                $catId = $db->lastInsertId();
            }
            $db->query("INSERT INTO finance_expenses (user_id, amount, category_id, type, expense_date, title, description) VALUES (?, ?, ?, 'expense', ?, ?, ?)", 
                [$userId, $data['cost'], $catId, date('Y-m-d'), "استثمار تعليمي: " . $data['title'], "عائد متوقع: " . ($data['expected_roi'] ?? 0)]
            );
        }

        $this->logAction($userId, 'created', "تسجيل دورة جديدة: {$data['title']}");
        return $res;
    }

    public function updateCourseProgress($id, $userId, $progress, $status) {
        // Fetch current course to see if we reached completion just now
        $current = $this->query("SELECT * FROM edu_courses WHERE id = ? AND user_id = ?", [$id, $userId])->fetch();
        
        $sql = "UPDATE edu_courses SET progress_percent = ?, status = ? WHERE id = ? AND user_id = ? AND deleted_at IS NULL";
        $res = $this->query($sql, [$progress, $status, $id, $userId]);
        
        // Smart Integration: Bump skill on active progress
        if ($current) {
            if (!empty($current->skill_id)) {
                // Automatically bump skill by slightly increasing it based on learning, up to a max if completed
                $increment = ($progress == 100) ? 25 : (($progress > $current->progress_percent) ? 5 : 0);
                if ($increment > 0) {
                    $this->automatedSkillProgress($current->skill_id, $userId, $increment);
                }
            }
        }

        if ($current && $current->status !== 'completed' && $status === 'completed') {
            $this->notifyUser($userId,
                '🎓 إتمام دورة تدريبية!',
                "ممتاز! أتممت دورة [{$current->title}] بنجاح. تم احتساب التقدم في مهاراتك.",
                'success'
            );
        }

        $this->logAction($userId, 'updated', "تحديث تقدم دورة رقم {$id} إلى {$progress}%");
        return $res;
    }

    public function getCourses($userId) {
        return $this->query("SELECT * FROM edu_courses WHERE user_id = ? AND deleted_at IS NULL ORDER BY status DESC, created_at DESC", [$userId])->fetchAll();
    }
    
    public function getCourseStats($userId) {
        $stats = new \stdClass();
        $stats->totalCost = $this->query("SELECT SUM(cost) as total FROM edu_courses WHERE user_id = ? AND deleted_at IS NULL", [$userId])->fetch()->total ?? 0;
        $stats->completed = $this->query("SELECT COUNT(id) as count FROM edu_courses WHERE user_id = ? AND status = 'completed' AND deleted_at IS NULL", [$userId])->fetch()->count ?? 0;
        $stats->learning = $this->query("SELECT COUNT(id) as count FROM edu_courses WHERE user_id = ? AND status = 'learning' AND deleted_at IS NULL", [$userId])->fetch()->count ?? 0;
        return $stats;
    }

    // --- SKILLS ---
    public function addSkill($userId, $data) {
        $sql = "INSERT INTO edu_skills (user_id, name, type, track_name, category, level, progress_percent, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $res = $this->query($sql, [
            $userId, 
            $data['name'], 
            $data['type'], 
            $data['track_name'] ?? null, 
            $data['category'] ?? 'General',
            $data['level'] ?? 1,
            $data['progress_percent'] ?? 0,
            $data['notes'] ?? null
        ]);
        $this->logAction($userId, 'created', "تسجيل مهارة جديدة: {$data['name']}");
        return $res;
    }

    public function automatedSkillProgress($skillId, $userId, $amount) {
        $skill = $this->query("SELECT * FROM edu_skills WHERE id = ? AND user_id = ?", [$skillId, $userId])->fetch();
        if (!$skill) return false;

        $newProgress = $skill->progress_percent + $amount;
        $newLevel = $skill->level;

        while ($newProgress >= 100) {
            $newProgress -= 100;
            $newLevel += 1;
        }
        
        if ($newLevel >= 10) {
            $newLevel = 10;
            $newProgress = 100;
        }

        // Updating Intelligence Status dynamically based on active progress
        $status = ($newLevel >= 7) ? 'strong' : (($newLevel >= 4) ? 'needs_improvement' : 'weak');

        $sql = "UPDATE edu_skills SET level = ?, progress_percent = ?, intelligence_status = ?, last_activity_date = CURDATE() WHERE id = ? AND user_id = ?";
        $res = $this->query($sql, [$newLevel, $newProgress, $status, $skillId, $userId]);
        
        if ($newLevel > $skill->level) {
            $this->logAction($userId, 'achieved', "ارتقاء مهارة {$skill->name} إلى المستوى {$newLevel}!");
            $this->notifyUser($userId, 
                '🏆 ارتقاء حقيقي في المهارة!', 
                "بفضل التعلم المستمر، مهارتك في [{$skill->name}] وصلت للمستوى {$newLevel}.",
                'success'
            );
        }

        return $res;
    }

    private function runSkillDecay($userId) {
        // Skill Decay System: If inactive for > 10 days, reduce progress by 5%
        $this->query("UPDATE edu_skills SET progress_percent = GREATEST(0, CAST(progress_percent AS SIGNED) - 5), intelligence_status = IF(level >= 7 AND CAST(progress_percent AS SIGNED) - 5 < 50, 'needs_improvement', intelligence_status), last_activity_date = CURDATE() WHERE user_id = ? AND deleted_at IS NULL AND last_activity_date IS NOT NULL AND DATEDIFF(CURDATE(), last_activity_date) > 10", [$userId]);
        // Also update items with NULL last_activity_date
        $this->query("UPDATE edu_skills SET last_activity_date = CURDATE() WHERE user_id = ? AND last_activity_date IS NULL", [$userId]);
    }

    public function getSkills($userId) {
        $this->runSkillDecay($userId);
        return $this->query("SELECT * FROM edu_skills WHERE user_id = ? AND deleted_at IS NULL ORDER BY level DESC, progress_percent DESC", [$userId])->fetchAll();
    }
    
    // Generic Item Operations
    public function getItem($table, $id, $userId) {
        if (!in_array($table, ['edu_courses', 'edu_skills', 'edu_programs'])) return false;
        return $this->query("SELECT * FROM {$table} WHERE id = ? AND user_id = ? AND deleted_at IS NULL", [$id, $userId])->fetch();
    }

    public function softDelete($table, $id, $userId) {
        if (!in_array($table, ['edu_courses', 'edu_skills', 'edu_programs'])) return false;
        $sql = "UPDATE {$table} SET deleted_at = CURRENT_TIMESTAMP WHERE id = ? AND user_id = ?";
        return $this->query($sql, [$id, $userId]);
    }

    // --- PROGRAMS ---
    public function addProgram($userId, $data) {
        $sql = "INSERT INTO edu_programs (user_id, degree, type, university, major, name, start_date, end_date, cost, status, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $res = $this->query($sql, [
            $userId, 
            $data['degree'] ?? null, 
            $data['type'] ?? 'bachelor',
            $data['university'] ?? null, 
            $data['major'] ?? null,
            $data['name'] ?? null,
            $data['start_date'] ?? null, 
            $data['end_date'] ?? null, 
            $data['cost'] ?? 0,
            $data['status'] ?? 'ongoing', 
            $data['notes'] ?? null
        ]);
        $this->logAction($userId, 'created', "تسجيل برنامج أكاديمي: " . ($data['name'] ?? $data['degree']));
        return $res;
    }

    public function updateProgramProgress($id, $userId, $status) {
        $sql = "UPDATE edu_programs SET status = ? WHERE id = ? AND user_id = ?";
        return $this->query($sql, [$status, $id, $userId]);
    }

    public function getPrograms($userId) {
        return $this->query("SELECT * FROM edu_programs WHERE user_id = ? AND deleted_at IS NULL ORDER BY start_date DESC", [$userId])->fetchAll();
    }
}
