<?php
/**
 * Edu & Skills - Premium Dashboard Array
 */
?>
<style>
@import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;900&display=swap');
body { font-family: 'Tajawal', sans-serif; background-color: #f8fafc; }

.header-gradient {
    background: linear-gradient(135deg, #4f46e5 0%, #3b82f6 100%);
    color: white;
    border-radius: 16px;
}

.stat-card {
    background: white;
    border-radius: 12px;
    border: none;
    box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);
    transition: transform 0.2s;
}
.stat-card:hover { transform: translateY(-3px); }

.nav-pills .nav-link {
    color: #475569;
    font-weight: 600;
    border-radius: 8px;
    padding: 10px 20px;
    margin-right: 5px;
}
.nav-pills .nav-link.active {
    background-color: #3b82f6;
    color: white;
    box-shadow: 0 4px 10px rgba(59, 130, 246, 0.3);
}

.item-card {
    background: white;
    border-radius: 12px;
    border: 1px solid #f1f5f9;
    box-shadow: 0 2px 4px rgba(0,0,0,0.02);
    transition: all 0.2s ease-in-out;
}
.item-card:hover { border-color: #cbd5e1; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.05); }

.progress-bar-premium { height: 8px; border-radius: 10px; }

.matrix-card { background: #ffffff; border-radius: 16px; border-left: 5px solid #10b981; }
.matrix-card-warning { border-left-color: #f59e0b; }
.matrix-card-danger { border-left-color: #ef4444; }

.level-badge {
    width: 35px; height: 35px;
    display: flex; align-items: center; justify-content: center;
    border-radius: 50%;
    font-weight: 900;
}
</style>

<div class="container-fluid py-2">
    <!-- Header -->
    <div class="header-gradient p-4 mb-4 shadow-sm position-relative overflow-hidden d-flex justify-content-between align-items-center">
        <div class="position-relative" style="z-index:2;">
            <h2 class="fw-bold mb-1"><i class="fa-solid fa-graduation-cap me-2 text-warning"></i> Learning Intelligence System</h2>
            <p class="mb-0 text-white text-opacity-75">Your system. Growing with every task, synced with your finance.</p>
        </div>
        <div class="position-relative text-end me-4" style="z-index:2;">
            <div class="bg-white bg-opacity-25 rounded-4 px-4 py-3 text-center border border-white border-opacity-25 backdrop-blur shadow-sm">
                <span class="d-block fw-bold text-white mb-1"><i class="fa-solid fa-fire text-warning me-1"></i> بناء الزخم</span>
                <span class="fs-3 fw-bold text-white"><?= $momentumScore ?>%</span>
                <div class="progress mt-2" style="height: 4px; width: 100px;">
                    <div class="progress-bar bg-warning" style="width: <?= $momentumScore ?>%;"></div>
                </div>
            </div>
        </div>
        <i class="fa-solid fa-brain position-absolute opacity-10" style="font-size: 10rem; top: -20px; right: -20px; z-index:1;"></i>
    </div>

    <!-- Navigation Tabs -->
    <ul class="nav nav-pills mb-4" id="eduTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" data-bs-toggle="pill" data-bs-target="#programs" type="button"><i class="fa-solid fa-university me-1"></i> البرامج الأكاديمية</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" data-bs-toggle="pill" data-bs-target="#courses" type="button"><i class="fa-solid fa-book-open me-1"></i> الدورات التدريبية</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" data-bs-toggle="pill" data-bs-target="#skills" type="button"><i class="fa-solid fa-layer-group me-1"></i> مصفوفة المهارات</button>
        </li>
        <li class="nav-item ms-auto" role="presentation">
            <button class="nav-link text-primary border border-primary bg-primary bg-opacity-10 fw-bold" data-bs-toggle="pill" data-bs-target="#advisor" type="button"><i class="fa-solid fa-bolt text-warning me-1"></i> المستشار الذكي</button>
        </li>
    </ul>

    <!-- Tab Content -->
    <div class="tab-content" id="eduTabsContent">
        
        <!-- ==================== ADVISOR ==================== -->
        <div class="tab-pane fade" id="advisor" role="tabpanel">
            <?php
            $strongSkills = $analysis['strong_skills'] ?? [];
            $weakSkills = $analysis['weak_skills'] ?? [];
            $stalledCourses = $analysis['stalled_courses'] ?? [];
            $recommendations = $analysis['recommendations'] ?? [];
            $lastAnalyzed = date('Y-m-d h:i a', strtotime($analysis['last_analyzed'] ?? 'now'));
            ?>
            <div class="row g-4 mb-4">
                <div class="col-12">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h4 class="fw-bold text-dark mb-1"><i class="fa-solid fa-thumbtack text-warning me-1"></i> توصيات المستشار المباشرة</h4>
                            <p class="text-secondary mb-0">تحليل مبني على خوارزميات الذكاء لسد فجوات مهاراتك الدقيقة (آخر تحديث: <?= $lastAnalyzed ?>)</p>
                        </div>
                        <a href="<?= BASE_URL ?>/education" class="btn btn-primary rounded-pill px-4 shadow-sm"><i class="fa-solid fa-arrows-rotate me-1"></i> فحص جديد</a>
                    </div>
                </div>
                
                <?php foreach($recommendations as $rec): ?>
                <div class="col-md-4">
                    <div class="card bg-white item-card h-100 p-0 border-0 shadow-sm" style="border-top: 4px solid var(--bs-<?= $rec['color'] ?>) !important;">
                        <div class="card-body p-4">
                            <div class="level-badge bg-<?= $rec['color'] ?> bg-opacity-10 text-<?= $rec['color'] ?> mb-3" style="width: 45px; height: 45px; font-size: 1.2rem;">
                                <i class="<?= $rec['icon'] ?>"></i>
                            </div>
                            <h6 class="fw-bold text-dark"><?= $rec['title'] ?></h6>
                            <p class="text-secondary mt-2 mb-4" style="font-size: 0.9rem; line-height: 1.6;">
                                <?= $rec['description'] ?>
                            </p>
                        </div>
                        <div class="card-footer bg-transparent border-top p-3 text-center">
                            <a href="<?= BASE_URL ?><?= $rec['action_url'] ?>" class="btn btn-sm btn-<?= $rec['color'] ?> w-100 fw-bold rounded-3 py-2">
                                <?= $rec['action_text'] ?> <i class="fa-solid fa-arrow-left ms-1 fs-8"></i>
                            </a>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            
            <div class="row g-4">
                <!-- Alerts -->
                <div class="col-md-6">
                    <h5 class="fw-bold text-dark mb-3">⚠️ المهارات المعرضة للخطر (أقل من 50%)</h5>
                    <div class="card border-0 shadow-sm rounded-4 h-100 p-4 bg-white">
                        <?php if(empty($weakSkills)): ?>
                            <div class="text-center py-4">
                                <i class="fa-solid fa-shield-check text-success fs-1 mb-2"></i>
                                <h6 class="fw-bold mt-2">لا يوجد مهارات ضعيفة! مجهود عظيم.</h6>
                            </div>
                        <?php endif; ?>
                        
                        <?php foreach($weakSkills as $ws): ?>
                            <div class="mb-3">
                                <div class="d-flex justify-content-between align-items-center mb-1">
                                    <span class="text-dark fw-bold fs-7"><?= htmlspecialchars($ws->name) ?></span>
                                    <span class="text-danger fw-bold fs-7"><?= $ws->progress_percent ?>%</span>
                                </div>
                                <div class="progress progress-bar-premium bg-danger bg-opacity-10">
                                    <div class="progress-bar bg-danger" role="progressbar" style="width: <?= $ws->progress_percent ?>%"></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <!-- Weekly Plan -->
                <div class="col-md-6">
                    <h5 class="fw-bold text-dark mb-3">🚀 خطتك الاستراتيجية المقترحة</h5>
                    <div class="card border-0 shadow-sm rounded-4 h-100 p-4 bg-white" style="border-right: 4px solid #3b82f6 !important;">
                        <ul class="list-unstyled mb-0 mt-2">
                            <li class="mb-4 d-flex align-items-start">
                                <i class="fa-solid fa-book-open text-primary mt-1 me-3 fs-5"></i> 
                                <div><b class="d-block mb-1 text-dark">تصفية المتأخرات:</b><span class="text-secondary" style="font-size:0.9rem;">خصص الإجازة الأسبوعية للانتهاء من الكورسات المعلقة.</span></div>
                            </li>
                            <li class="mb-4 d-flex align-items-start">
                                <i class="fa-solid fa-level-up-alt text-danger mt-1 me-3 fs-5"></i> 
                                <div><b class="d-block mb-1 text-dark">إنقاذ المهارات:</b><span class="text-secondary" style="font-size:0.9rem;">اعتمد على التطبيق العملي لرفع المهارات ذات نسب إتقان تحت 50%.</span></div>
                            </li>
                            <li class="mb-0 d-flex align-items-start">
                                <i class="fa-solid fa-play text-success mt-1 me-3 fs-5"></i> 
                                <div><b class="d-block mb-1 text-dark">الاستكشاف والانطلاق:</b><span class="text-secondary" style="font-size:0.9rem;">نهاية الأسبوع هي الأفضل للنظر في الدورات المستقبلية.</span></div>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <!-- ==================== PROGRAMS ==================== -->
        <div class="tab-pane fade show active" id="programs" role="tabpanel">
            <div class="row align-items-center mb-4">
                <div class="col-md-8">
                    <h4 class="fw-bold text-dark mb-0">البرامج الأكاديمية والمطولة</h4>
                </div>
                <div class="col-md-4 text-end">
                    <button class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#addProgramModal">
                        <i class="fa-solid fa-plus me-1"></i> تسجيل برنامج
                    </button>
                </div>
            </div>

            <!-- Summary Cards -->
            <div class="row g-3 mb-4">
                <div class="col-6 col-md-3">
                    <div class="card stat-card text-center p-3">
                        <i class="fa-solid fa-graduation-cap text-primary fs-3 mb-2"></i>
                        <h4 class="fw-bold text-dark mb-0"><?= $programs['summary']['Bachelor'] ?></h4>
                        <span class="text-muted fs-7">بكالوريوس</span>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="card stat-card text-center p-3">
                        <i class="fa-solid fa-certificate text-success fs-3 mb-2"></i>
                        <h4 class="fw-bold text-dark mb-0"><?= $programs['summary']['Diploma'] ?></h4>
                        <span class="text-muted fs-7">دبلوم</span>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="card stat-card text-center p-3">
                        <i class="fa-solid fa-scroll text-warning fs-3 mb-2"></i>
                        <h4 class="fw-bold text-dark mb-0"><?= $programs['summary']['Master'] ?></h4>
                        <span class="text-muted fs-7">ماجستير</span>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="card stat-card text-center p-3">
                        <i class="fa-solid fa-user-graduate text-danger fs-3 mb-2"></i>
                        <h4 class="fw-bold text-dark mb-0"><?= $programs['summary']['PhD'] ?></h4>
                        <span class="text-muted fs-7">دكتوراه</span>
                    </div>
                </div>
            </div>

            <div class="row g-4">
                <?php foreach($programs['list'] as $p): 
                    $color = ($p->status === 'completed') ? 'success' : (($p->status === 'ongoing') ? 'primary' : 'warning');
                ?>
                    <div class="col-md-6">
                        <div class="card item-card p-4">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <h5 class="fw-bold text-dark mb-0"><i class="fa-solid fa-university text-secondary me-2"></i> <?= htmlspecialchars($p->degree) ?> في <?= htmlspecialchars($p->major) ?></h5>
                                <button class="btn btn-sm text-danger p-0" onclick="deleteObj(<?= $p->id ?>, 'program')"><i class="fa-solid fa-trash"></i></button>
                            </div>
                            <h6 class="text-muted mb-4"><?= htmlspecialchars($p->university) ?></h6>
                            
                            <div class="row g-2 mb-3">
                                <div class="col-6">
                                    <div class="bg-light p-2 rounded-3 text-center">
                                        <small class="text-muted d-block mb-1">تاريخ البدء</small>
                                        <span class="fw-bold text-dark fs-7"><?= $p->start_date ?></span>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="bg-light p-2 rounded-3 text-center">
                                        <small class="text-muted d-block mb-1">تاريخ الانتهاء</small>
                                        <span class="fw-bold text-dark fs-7"><?= $p->end_date ?: 'غير محدد' ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="text-end border-top pt-2 mt-2">
                                <span class="badge bg-<?= $color ?> bg-opacity-10 text-<?= $color ?> border border-<?= $color ?> px-3 py-2 fs-6">
                                    <?= ($p->status === 'completed') ? 'مكتمل بنجاح' : (($p->status === 'ongoing') ? 'قيد الدراسة' : 'مؤجل') ?>
                                </span>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

        </div>

        <!-- ==================== COURSES ==================== -->
        <div class="tab-pane fade" id="courses" role="tabpanel">
            <div class="row align-items-center mb-4">
                <div class="col-md-8">
                    <h4 class="fw-bold text-dark mb-0">الدورات التدريبية</h4>
                </div>
                <div class="col-md-4 text-end">
                    <button class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#addCourseModal">
                        <i class="fa-solid fa-plus me-1"></i> إضافة دورة
                    </button>
                </div>
            </div>

            <?php if(empty($coursesByPath)): ?>
                <div class="text-center py-5 bg-white rounded-4 shadow-sm">
                    <i class="fa-solid fa-book-open fs-1 text-light mb-3"></i>
                    <h5 class="fw-bold">سجلك خالي من الدورات التدريبية</h5>
                    <p class="text-muted">أضف المسارات ثم الدورات لتحقيق الأهداف.</p>
                </div>
            <?php endif; ?>

            <?php foreach($coursesByPath as $pathId => $pathData): 
                if(empty($pathData['items']) && $pathId === 'none') continue; 
            ?>
                <div class="card stat-card mb-4" <?= ($pathId !== 'none') ? 'style="border-top: 4px solid #3b82f6;"' : '' ?>>
                    <div class="card-header bg-white border-bottom-0 pt-4 pb-0 d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="fw-bold text-dark mb-1"><i class="fa-solid <?= ($pathId === 'none') ? 'fa-folder-open text-secondary' : 'fa-route text-primary' ?> me-2"></i> <?= htmlspecialchars($pathData['name']) ?></h5>
                            <?php if($pathId !== 'none'): ?>
                                <p class="text-muted fs-7 mb-0 mt-1"><i class="fa-solid fa-bullseye text-danger me-1"></i> الهدف: <?= htmlspecialchars($pathData['goal']) ?></p>
                                <?php if($pathData['roi'] > 0): ?>
                                    <span class="badge bg-success bg-opacity-10 text-success mt-1 border border-success fs-8"><i class="fa-solid fa-chart-line me-1"></i> العائد المتوقع من المسار: <?= number_format($pathData['roi']) ?> ج</span>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                        <div>
                            <?php if($pathId === 'none'): ?>
                                <button class="btn btn-sm btn-outline-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addPathModal"><i class="fa-solid fa-plus"></i> إنشاء مسار جديد</button>
                            <?php endif; ?>
                            <span class="badge bg-light text-dark border me-1">الإجمالي: <?= $pathData['total'] ?></span>
                            <span class="badge bg-success text-white me-1">مكتمل: <?= $pathData['completed'] ?></span>
                            <span class="badge bg-primary text-white">قيد الدراسة: <?= $pathData['in_progress'] ?></span>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <?php foreach($pathData['items'] as $c): 
                                $isCompleted = ($c->status === 'completed');
                                $color = $isCompleted ? 'success' : ($c->status === 'learning' ? 'primary' : 'secondary');
                            ?>
                                <div class="col-md-6 col-lg-4">
                                    <div class="card item-card p-3 h-100 <?= $isCompleted ? 'bg-light bg-opacity-50' : '' ?>">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <h6 class="fw-bold text-dark mb-0 text-truncate w-75<?= $isCompleted ? ' text-decoration-line-through text-muted' : '' ?>" title="<?= htmlspecialchars($c->title) ?>"><?= htmlspecialchars($c->title) ?></h6>
                                            <button class="btn btn-sm text-danger p-0" onclick="deleteObj(<?= $c->id ?>, 'course')"><i class="fa-regular fa-trash-can"></i></button>
                                        </div>
                                        <small class="text-muted d-block mb-3"><i class="fa-solid fa-building-columns me-1"></i> <?= htmlspecialchars($c->provider ?: 'غير محدد') ?></small>
                                        
                                        <!-- Progress Slider AJAX -->
                                        <!-- Smart Task Form -->
                                        <?php if(!$isCompleted): ?>
                                            <div class="mt-3">
                                                <button class="btn btn-sm btn-outline-primary w-100 fw-bold" onclick="generateSmartTask(<?= $c->id ?>, '<?= htmlspecialchars($c->title) ?>')"><i class="fa-solid fa-thumbtack me-1"></i> إرسال إلى قائمة المهام (Todo)</button>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <?php if($c->skill_id): ?>
                                            <small class="text-success mt-2 d-block fw-bold fs-8"><i class="fa-solid fa-bolt text-warning me-1"></i> مرتبط بمهارة (يرتقي تلقائياً)</small>
                                        <?php endif; ?>
                                        <?php if($c->expected_roi > 0): ?>
                                            <small class="text-primary mt-1 d-block fw-bold fs-8"><i class="fa-solid fa-chart-line text-success me-1"></i> عائد استثمار متوقع: <?= number_format($c->expected_roi, 2) ?> ج</small>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- ==================== SKILLS MATRIX ==================== -->
        <div class="tab-pane fade" id="skills" role="tabpanel">
            <div class="row align-items-center mb-4">
                <div class="col-md-8">
                    <h4 class="fw-bold text-dark mb-0">مصفوفة المهارات الذكية</h4>
                    <p class="text-secondary mb-0">تتطور المهارات تلقائياً عند إنهاء المهام أو الدورات المرتبطة بها.</p>
                </div>
                <div class="col-md-4 text-end">
                    <button class="btn btn-outline-primary fw-bold" onclick="openAddSkillModal()">
                        <i class="fa-solid fa-plus me-1"></i> مهارة / مسار جديد
                    </button>
                </div>
            </div>

            <div class="row g-4 mb-5">
                <!-- Insights: Top Skills -->
                <div class="col-md-6">
                    <div class="card stat-card h-100 p-3" style="border-right: 4px solid #10b981;">
                        <h6 class="fw-bold text-success mb-3"><i class="fa-solid fa-arrow-trend-up me-1"></i> أقوى مهاراتك (Top Skills)</h6>
                        <?php if(empty($skills['top'])): ?>
                            <small class="text-muted">لا توجد مسارات مهارية حتى الآن.</small>
                        <?php else: ?>
                            <?php foreach($skills['top'] as $s): ?>
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="fw-bold text-dark"><?= htmlspecialchars($s->name) ?></span>
                                    <span class="badge bg-success bg-opacity-10 text-success border border-success">Level <?= $s->level ?></span>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
                <!-- Insights: Weak Skills -->
                <div class="col-md-6">
                    <div class="card stat-card h-100 p-3" style="border-right: 4px solid #ef4444;">
                        <h6 class="fw-bold text-danger mb-3"><i class="fa-solid fa-arrow-trend-down me-1"></i> مهارات تحتاج تركيز (Weak Skills)</h6>
                        <?php if(empty($skills['weak'])): ?>
                            <small class="text-muted">ممتاز! جميع مهاراتك في مستويات قوية.</small>
                        <?php else: ?>
                            <?php foreach($skills['weak'] as $s): ?>
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="fw-bold text-dark"><?= htmlspecialchars($s->name) ?></span>
                                    <span class="badge bg-danger bg-opacity-10 text-danger border border-danger">Level <?= $s->level ?></span>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <?php if(empty($skills['matrix'])): ?>
                <div class="text-center py-5 bg-white rounded-4 shadow-sm">
                    <i class="fa-solid fa-layer-group fs-1 text-light mb-3"></i>
                    <h5 class="fw-bold">مصفوفة المهارات فارغة</h5>
                    <p class="text-muted">أضف مهاراتك الأولى وابدأ في ربطها بالدورات لتتطور تلقائياً.</p>
                </div>
            <?php endif; ?>

            <?php foreach($skills['matrix'] as $trackName => $trackData): ?>
                <h5 class="fw-bold text-primary mt-4 mb-3 border-bottom pb-2">
                    <i class="fa-solid fa-folder-tree me-2"></i> المجموعة: <?= htmlspecialchars($trackName) ?>
                    <span class="badge bg-light text-secondary ms-2 fw-normal fs-7">متوسط المستوى: <?= $trackData['avg_level'] ?></span>
                </h5>
                <div class="row g-3">
                    <?php foreach($trackData['items'] as $s): 
                        $status = $s->intelligence_status ?? 'needs_improvement';
                        $borderColor = ($status === 'strong') ? 'matrix-card' : (($status === 'needs_improvement') ? 'matrix-card-warning' : 'matrix-card-danger');
                        $colorClass = ($status === 'strong') ? 'success' : (($status === 'needs_improvement') ? 'warning' : 'danger');
                    ?>
                        <div class="col-md-4">
                            <div class="card item-card <?= $borderColor ?> p-3 h-100 position-relative">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div>
                                        <h6 class="fw-bold text-dark mb-1"><?= htmlspecialchars($s->name) ?></h6>
                                        <small class="text-secondary"><?= htmlspecialchars($s->category) ?></small>
                                    </div>
                                    <div class="level-badge bg-<?= $colorClass ?> bg-opacity-10 text-<?= $colorClass ?> border border-<?= $colorClass ?>">
                                        L<?= $s->level ?>
                                    </div>
                                </div>
                                
                                <div class="mt-3">
                                    <div class="d-flex justify-content-between mb-1">
                                        <small class="text-muted fw-bold">التقدم للمستوى التالي</small>
                                        <small class="text-<?= $colorClass ?> fw-bold"><?= $s->progress_percent ?>%</small>
                                    </div>
                                    <div class="progress progress-bar-premium bg-light">
                                        <div class="progress-bar bg-<?= $colorClass ?>" role="progressbar" style="width: <?= $s->progress_percent ?>%"></div>
                                    </div>
                                </div>

                                <!-- Action Overlay -->
                                <div class="position-absolute top-0 start-0 m-1">
                                    <button class="btn btn-sm text-secondary bg-transparent border-0 px-1" onclick='editSkill(<?= json_encode($s) ?>)'><i class="fa-solid fa-pen"></i></button>
                                    <button class="btn btn-sm text-secondary bg-transparent border-0 px-1" onclick="deleteObj(<?= $s->id ?>, 'skill')"><i class="fa-solid fa-trash"></i></button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        </div>

    </div>
</div>

<!-- ================= MODALS ================= -->

<!-- Add Program Modal -->
<div class="modal fade" id="addProgramModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form id="addProgramForm" class="modal-content border-0 shadow-lg rounded-4">
            <div class="modal-header bg-light border-0 px-4">
                <h5 class="modal-title fw-bold"><i class="fa-solid fa-university me-2 text-primary"></i> تسجيل برنامج أكاديمي جديد</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="mb-3">
                    <label class="form-label fw-bold">الدرجة العلمية / نوع البرنامج</label>
                    <select id="p_degree" class="form-select bg-light border-0">
                        <option value="بكالوريوس">بكالوريوس (Bachelor)</option>
                        <option value="دبلوم">دبلوم (Diploma)</option>
                        <option value="ماجستير">ماجستير (Master)</option>
                        <option value="دكتوراه">دكتوراة (PhD)</option>
                    </select>
                </div>
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label fw-bold">التخصص (Major)</label>
                        <input type="text" id="p_major" class="form-control bg-light border-0" required>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-bold">الجامعة / المؤسسة</label>
                        <input type="text" id="p_university" class="form-control bg-light border-0" required>
                    </div>
                </div>
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label fw-bold">تاريخ البدء</label>
                        <input type="date" id="p_start_date" class="form-control bg-light border-0" required>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-bold">تاريخ الانتهاء المتوقع</label>
                        <input type="date" id="p_end_date" class="form-control bg-light border-0">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">التكلفة (إن وجدت)</label>
                    <input type="number" id="p_cost" class="form-control bg-light border-0" placeholder="0.00">
                </div>
            </div>
            <div class="modal-footer border-0 px-4 pb-4">
                <button type="button" class="btn btn-primary w-100 rounded-pill fw-bold py-2" onclick="submitProgram()">سجل البرنامج بحفظ الجهد</button>
            </div>
        </form>
    </div>
</div>

<!-- Add Course Modal -->
<div class="modal fade" id="addCourseModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form id="addCourseForm" class="modal-content border-0 shadow-lg rounded-4">
            <div class="modal-header bg-light border-0 px-4">
                <h5 class="modal-title fw-bold"><i class="fa-solid fa-book-open me-2 text-primary"></i> تسجيل دورة تدريبية جديدة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="mb-3">
                    <label class="form-label fw-bold">عنوان الدورة</label>
                    <input type="text" id="c_title" class="form-control form-control-lg bg-light border-0" required>
                </div>
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label fw-bold">التصنيف</label>
                        <input type="text" id="c_category" class="form-control bg-light border-0" required>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-bold">المنصة / المزود</label>
                        <input type="text" id="c_provider" class="form-control bg-light border-0">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold text-success"><i class="fa-solid fa-link"></i> ربط بمهارة للحصول على XP تلقائي عند الانتهاء</label>
                    <select id="c_skill_id" class="form-select border-success bg-white border-opacity-50">
                        <option value="">بدون ربط (مستقل)</option>
                        <?php foreach($rawSkills as $r): ?>
                            <option value="<?= $r->id ?>"><?= htmlspecialchars($r->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label fw-bold">التكلفة</label>
                        <input type="number" id="c_cost" class="form-control bg-light border-0" placeholder="0.00">
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-bold">مدفوع؟ <small class="text-muted">(يسجل بمالياتك)</small></label>
                        <select id="c_is_paid" class="form-select bg-light border-0">
                            <option value="0">مجاني</option>
                            <option value="1">مدفوع استثماري</option>
                        </select>
                    </div>
                </div>
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label fw-bold"><i class="fa-solid fa-route text-primary"></i> المسار التعلمي (إن وجد)</label>
                        <select id="c_path_id" class="form-select bg-light border-0">
                            <option value="">خارج المسارات (دورة مستقلة)</option>
                            <?php foreach($pathsList as $p): ?>
                                <option value="<?= $p->id ?>"><?= htmlspecialchars($p->name) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-bold text-success"><i class="fa-solid fa-chart-line"></i> العائد المتوقع (ROI)</label>
                        <input type="number" id="c_expected_roi" class="form-control border-success border-opacity-50" placeholder="0.00">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">رابط الدورة (URL)</label>
                    <input type="url" id="c_url" class="form-control bg-light border-0" placeholder="https://...">
                </div>
            </div>
            <div class="modal-footer border-0 px-4 pb-4">
                <button type="button" class="btn btn-primary w-100 rounded-pill fw-bold py-2" onclick="submitCourse()">سجل الدورة</button>
            </div>
        </form>
    </div>
</div>

<!-- Add Skill Modal -->
<div class="modal fade" id="addSkillModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form id="addSkillForm" class="modal-content border-0 shadow-lg rounded-4">
            <div class="modal-header bg-light border-0 px-4">
                <h5 class="modal-title fw-bold" id="skillModalTitle"><i class="fa-solid fa-plus me-2 text-primary"></i> مسار مهارة جديد</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <input type="hidden" id="sk_id" value="">
                <div class="mb-3">
                    <label class="form-label fw-bold">اسم المهارة</label>
                    <input type="text" id="sk_name" class="form-control form-control-lg bg-light border-0" required>
                </div>
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label fw-bold">النوع</label>
                        <select id="sk_type" class="form-select bg-light border-0">
                            <option value="track_based">داخل مسار (Track)</option>
                            <option value="standalone">مستقلة (Standalone)</option>
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-bold">المستوى الحالي</label>
                        <input type="number" id="sk_level" class="form-control bg-light border-0" value="1" min="1" max="10">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">اسم المسار / التصنيف</label>
                    <input type="text" id="sk_category" class="form-control bg-light border-0" placeholder="مثال: هندسة برمجيات">
                </div>
            </div>
            <div class="modal-footer border-0 px-4 pb-4">
                <button type="button" class="btn btn-primary w-100 rounded-pill fw-bold py-2" onclick="submitSkill()">حفظ النظام المرجعي</button>
            </div>
        </form>
    </div>
</div>

<!-- Add Path Modal -->
<div class="modal fade" id="addPathModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form id="addPathForm" class="modal-content border-0 shadow-lg rounded-4">
            <div class="modal-header bg-light border-0 px-4">
                <h5 class="modal-title fw-bold"><i class="fa-solid fa-route me-2 text-primary"></i> إنشاء مسار تعلم ذكي جديد</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="mb-3">
                    <label class="form-label fw-bold">اسم المسار</label>
                    <input type="text" id="pt_name" class="form-control form-control-lg bg-light border-0" required placeholder="مثال: هندسة البيانات المتقدمة">
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">الهدف الاستراتيجي من المسار</label>
                    <input type="text" id="pt_goal" class="form-control bg-light border-0" required placeholder="مثال: الحصول على وظيفة في شركة تقنية كبرى">
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold text-success"><i class="fa-solid fa-chart-line"></i> العائد المالي المتوقع (بالجنيه)</label>
                    <input type="number" id="pt_roi" class="form-control border-success border-opacity-50 bg-white" placeholder="0">
                    <small class="text-muted mt-1 d-block">سيساعدك النظام على قياس العائد المالي الفعلي من التعلم أمام المصاريف.</small>
                </div>
            </div>
            <div class="modal-footer border-0 px-4 pb-4">
                <button type="button" class="btn btn-primary w-100 rounded-pill fw-bold py-2" onclick="submitPath()">إنشاء المسار</button>
            </div>
        </form>
    </div>
</div>

<script>
// --- AJAX LAYER ---

function submitProgram() {
    let payload = {
        degree: document.getElementById('p_degree').value,
        major: document.getElementById('p_major').value,
        university: document.getElementById('p_university').value,
        start_date: document.getElementById('p_start_date').value,
        end_date: document.getElementById('p_end_date').value,
        cost: document.getElementById('p_cost').value,
        status: 'ongoing',
        notes: ''
    };
    if(!payload.major || !payload.university || !payload.start_date) return alert('التخصص والجامعة وتاريخ البدء مطلوبين');
    
    let form = new FormData();
    for ( let key in payload ) { form.append(key, payload[key]); }
    form.append('csrf_token', '<?= generate_csrf_token() ?>');
    
    fetch('<?= BASE_URL ?>/education/storeProgram', { method: 'POST', body: form })
    .then(r => r.json()).then(data => { if(data.success) window.location.reload(); });
}

function submitPath() {
    let payload = {
        name: document.getElementById('pt_name').value,
        goal: document.getElementById('pt_goal').value,
        roi: document.getElementById('pt_roi').value || 0
    };
    if(!payload.name) return alert('اسم المسار مطلوب');
    
    let form = new FormData();
    for ( let key in payload ) { form.append(key, payload[key]); }
    form.append('csrf_token', '<?= generate_csrf_token() ?>');
    
    // Using fetch with error handling properly
    fetch('<?= BASE_URL ?>/education/storePath', { method: 'POST', body: form })
    .then(r => r.json()).then(data => { if(data.success) window.location.reload(); })
    .catch(console.error);
}

function submitCourse() {
    let payload = {
        title: document.getElementById('c_title').value,
        category: document.getElementById('c_category').value,
        provider: document.getElementById('c_provider').value,
        skill_id: document.getElementById('c_skill_id').value,
        cost: document.getElementById('c_cost').value,
        is_paid: document.getElementById('c_is_paid').value,
        url: document.getElementById('c_url').value,
        path_id: document.getElementById('c_path_id').value,
        expected_roi: document.getElementById('c_expected_roi').value,
        status: 'planned'
    };
    if(!payload.title) return alert('العنوان مطلوب');
    
    let form = new FormData();
    for ( let key in payload ) { form.append(key, payload[key]); }
    form.append('csrf_token', '<?= generate_csrf_token() ?>');
    
    fetch('<?= BASE_URL ?>/education/storeCourse', { method: 'POST', body: form })
    .then(r => r.json()).then(data => { if(data.success) window.location.reload(); });
}

function submitSkill() {
    let payload = {
        skill_id: document.getElementById('sk_id').value,
        name: document.getElementById('sk_name').value,
        type: document.getElementById('sk_type').value,
        level: document.getElementById('sk_level').value,
        track_name: document.getElementById('sk_category').value,
        category: document.getElementById('sk_category').value
    };
    if(!payload.name) return alert('اسم المهارة مطلوب');
    
    let form = new FormData();
    for ( let key in payload ) { form.append(key, payload[key]); }
    form.append('csrf_token', '<?= generate_csrf_token() ?>');
    
    fetch('<?= BASE_URL ?>/education/storeSkill', { method: 'POST', body: form })
    .then(r => r.json()).then(data => { if(data.success) window.location.reload(); });
}

function editSkill(skill) {
    document.getElementById('sk_id').value = skill.id;
    document.getElementById('sk_name').value = skill.name;
    document.getElementById('sk_type').value = skill.type;
    document.getElementById('sk_level').value = skill.level;
    document.getElementById('sk_category').value = skill.track_name || skill.category;
    document.getElementById('skillModalTitle').innerHTML = '<i class="fa-solid fa-pen me-2 text-primary"></i> تعديل المهارة';
    new bootstrap.Modal(document.getElementById('addSkillModal')).show();
}

function openAddSkillModal() {
    document.getElementById('sk_id').value = '';
    document.getElementById('sk_name').value = '';
    document.getElementById('sk_level').value = '1';
    document.getElementById('sk_category').value = '';
    document.getElementById('skillModalTitle').innerHTML = '<i class="fa-solid fa-plus me-2 text-primary"></i> مسار مهارة جديد';
    new bootstrap.Modal(document.getElementById('addSkillModal')).show();
}

function updateCourseProgress(id, val) {
    document.getElementById('courseProgVal' + id).innerText = val + '%';
    let payload = { id: id, progress: parseInt(val), status: (val == 100 ? 'completed' : 'learning') };
    
    fetch('<?= BASE_URL ?>/education/updateCourseProgress', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    }).then(r => r.json()).then(data => {
        if(data.success && val == 100) {
            window.location.reload();
        }
    });
}

function generateSmartTask(id, title) {
    fetch('<?= BASE_URL ?>/education/generateTask', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: id, title: title })
    }).then(r => r.json()).then(data => {
        if(data.success) {
            alert('تم تكوين مهمة تعلم ذكية بنجاح في مركز الإنجاز اليومي.');
        }
    });
}

function deleteObj(id, type) {
    if(!confirm('تأكيد الحذف نهائياً؟')) return;
    
    fetch('<?= BASE_URL ?>/education/deleteItem', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: id, type: type })
    }).then(r => r.json()).then(data => {
        if(data.success) window.location.reload();
    });
}
</script>
