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

class EducationController extends \Core\Controller {
    


    public function index() {
        $model = $this->model('Education/Models/EducationModel');
        $advisorModel = $this->model('Advisor/Models/AdvisorModel');
        
        $analysis = $advisorModel->analyzeUserLearning($this->userId);

        // 1. Paths & Programs Processing
        $pathsList = $model->getPaths($this->userId);
        
        $programsList = $model->getPrograms($this->userId);
        $programs = [
            'summary' => ['Bachelor' => 0, 'Diploma' => 0, 'Master' => 0, 'PhD' => 0],
            'list' => $programsList
        ];
        foreach($programsList as $p) {
            if (stripos($p->degree, 'bachelor') !== false || stripos($p->degree, 'بكالوريوس') !== false) $programs['summary']['Bachelor']++;
            elseif (stripos($p->degree, 'diploma') !== false || stripos($p->degree, 'دبلوم') !== false) $programs['summary']['Diploma']++;
            elseif (stripos($p->degree, 'master') !== false || stripos($p->degree, 'ماجستير') !== false) $programs['summary']['Master']++;
            elseif (stripos($p->degree, 'phd') !== false || stripos($p->degree, 'دكتوراه') !== false) $programs['summary']['PhD']++;
        }
        
        $momentumScore = $model->getMomentumScore($this->userId);

        // 2. Courses & Paths Grouping
        $coursesList = $model->getCourses($this->userId);
        $paths = [];
        
        // Initialize paths with predefined ones
        foreach($pathsList as $pt) {
            $paths[$pt->id] = ['name' => $pt->name, 'goal' => $pt->goal, 'roi' => $pt->expected_roi, 'total' => 0, 'completed' => 0, 'in_progress' => 0, 'items' => []];
        }
        $paths['none'] = ['name' => 'دورات مستقلة (خارج المسارات)', 'goal' => 'استكشاف وتطوير عام', 'roi' => 0, 'total' => 0, 'completed' => 0, 'in_progress' => 0, 'items' => []];

        foreach($coursesList as $c) {
            $target = $c->path_id ? $c->path_id : 'none';
            if(!isset($paths[$target])) $paths['none']['items'][] = $c; // fallback
            else {
                $paths[$target]['total']++;
                if($c->status === 'completed') $paths[$target]['completed']++;
                elseif($c->status === 'learning') $paths[$target]['in_progress']++;
                
                $paths[$target]['items'][] = $c;
            }
        }

        // 3. Skills Processing
        $skillsList = $model->getSkills($this->userId);
        $skills = [
            'matrix' => [],      // Grouped by Category/Track
            'top' => [],         // Top 3 skills
            'weak' => []         // Weak 3 skills
        ];

        if(!empty($skillsList)) {
            $skills['top'] = array_slice($skillsList, 0, 3);
            
            // Calculate weak skills (sort by level asc)
            $weakSorted = $skillsList;
            usort($weakSorted, fn($a, $b) => ($a->level <=> $b->level) ?: ($a->progress_percent <=> $b->progress_percent));
            $skills['weak'] = array_slice($weakSorted, 0, 3);

            foreach($skillsList as $sk) {
                $group = ($sk->type === 'track_based' && $sk->track_name) ? $sk->track_name : ($sk->category ?: 'General');
                if(!isset($skills['matrix'][$group])) {
                    $skills['matrix'][$group] = ['items' => [], 'avg_level' => 0, 'total' => 0];
                }
                $skills['matrix'][$group]['items'][] = $sk;
                $skills['matrix'][$group]['total']++;
                $skills['matrix'][$group]['avg_level'] += $sk->level;
            }
            
            // Finalize averages
            foreach($skills['matrix'] as &$g) {
                $g['avg_level'] = round($g['avg_level'] / $g['total'], 1);
            }
        }

        $this->view('Education/Views/dashboard', [
            'title' => 'Edu & Skills',
            'programs' => $programs,
            'pathsList' => $pathsList,
            'coursesByPath' => $paths,
            'skills' => $skills,
            'rawSkills' => $skillsList, // useful for selects
            'analysis' => $analysis, // AI Advisor data
            'momentumScore' => $momentumScore
        ]);
    }

    // --- AJAX EXPERIENCES ---
    
    // Programs
    public function storeProgram() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token'] ?? '');
            $model = $this->model('Education/Models/EducationModel');
            
            $degree = get_secure_post('degree');
            $type = 'bachelor'; // default
            
            // Auto mapping for internal consistency
            if (stripos($degree, 'بكالوريوس') !== false || stripos($degree, 'bachelor') !== false) $type = 'bachelor';
            elseif (stripos($degree, 'دبلوم') !== false || stripos($degree, 'diploma') !== false) $type = 'diploma';
            elseif (stripos($degree, 'ماجستير') !== false || stripos($degree, 'master') !== false) $type = 'master';
            elseif (stripos($degree, 'دكتوراه') !== false || stripos($degree, 'phd') !== false) $type = 'phd';

            $data = [
                'name' => get_secure_post('name') ?: $degree,
                'degree' => $degree,
                'type' => $type,
                'university' => get_secure_post('university'),
                'major' => get_secure_post('major'),
                'start_date' => get_secure_post('start_date'),
                'end_date' => get_secure_post('end_date'),
                'cost' => get_secure_post('cost') ?: 0,
                'status' => get_secure_post('status') ?: 'ongoing',
                'notes' => get_secure_post('notes')
            ];
            
            $model->addProgram($this->userId, $data);
            echo json_encode(['success' => true, 'redirect' => BASE_URL . '/education?tab=programs']);
            exit;
        }
    }

    public function deleteItem() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            $id = $data['id'] ?? null;
            $type = $data['type'] ?? null;
            
            if($id && $type) {
                $model = $this->model('Education/Models/EducationModel');
                $tableMap = ['program' => 'edu_programs', 'course' => 'edu_courses', 'skill' => 'edu_skills'];
                $model->softDelete($tableMap[$type], $id, $this->userId);
                echo json_encode(['success' => true]);
                exit;
            }
            echo json_encode(['success' => false]);
            exit;
        }
    }

    // Courses
    public function storeCourse() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token'] ?? '');
            $model = $this->model('Education/Models/EducationModel');
            
            $data = [
                'title' => get_secure_post('title'),
                'provider' => get_secure_post('provider'),
                'skill_id' => get_secure_post('skill_id'),
                'category' => get_secure_post('category'),
                'is_paid' => get_secure_post('is_paid'),
                'cost' => get_secure_post('cost'),
                'path_id' => get_secure_post('path_id'),
                'expected_roi' => get_secure_post('expected_roi'),
                'status' => get_secure_post('status') ?: 'planned',
                'url' => get_secure_post('url')
            ];
            
            $model->addCourse($this->userId, $data);
            echo json_encode(['success' => true, 'redirect' => BASE_URL . '/education?tab=courses']);
            exit;
        }
    }

    public function storePath() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token'] ?? '');
            $model = $this->model('Education/Models/EducationModel');
            
            $data = [
                'name' => get_secure_post('name'),
                'goal' => get_secure_post('goal'),
                'expected_roi' => get_secure_post('roi')
            ];
            
            $model->addPath($this->userId, $data);
            echo json_encode(['success' => true, 'redirect' => BASE_URL . '/education?tab=courses']);
            exit;
        }
    }

    public function generateTask() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            $courseId = $data['id'] ?? null;
            $title = $data['title'] ?? null;
            if($courseId && $title) {
                $model = $this->model('Education/Models/EducationModel');
                $model->generateSmartTask($this->userId, $courseId, $title);
                echo json_encode(['success' => true]);
                exit;
            }
        }
        echo json_encode(['success' => false]);
    }

    public function updateCourseProgress() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            $id = $data['id'] ?? null;
            $progress = $data['progress'] ?? 0;
            $status = $data['status'] ?? 'learning';
            
            if($id) {
                $model = $this->model('Education/Models/EducationModel');
                // smart integration handled inside model
                $model->updateCourseProgress($id, $this->userId, $progress, $status);
                echo json_encode(['success' => true]);
                exit;
            }
            echo json_encode(['success' => false]);
            exit;
        }
    }

    // Skills
    public function storeSkill() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token'] ?? '');
            $model = $this->model('Education/Models/EducationModel');
            
            $data = [
                'name' => get_secure_post('name'),
                'type' => get_secure_post('type'), // track_based or standalone
                'category' => get_secure_post('category'),
                'track_name' => get_secure_post('track_name'),
                'level' => get_secure_post('level') ?: 1,
                'progress_percent' => 0
            ];
            
            $skillId = get_secure_post('skill_id');
            if ($skillId) {
                // We need an update method in model, or raw query for now
                $db = \Core\Database::getInstance();
                $db->query("UPDATE edu_skills SET name=?, type=?, category=?, track_name=?, level=? WHERE id=? AND user_id=?", 
                    [$data['name'], $data['type'], $data['category'], $data['track_name'], $data['level'], $skillId, $this->userId]);
            } else {
                $model->addSkill($this->userId, $data);
            }
            
            echo json_encode(['success' => true, 'redirect' => BASE_URL . '/education?tab=skills']);
            exit;
        }
    }


}
