<div class="container-fluid mb-5">
    <div class="row align-items-center mb-4">
        <div class="col-md-6">
            <h2 class="fw-bold mb-0 text-primary"><i class="fa-solid fa-compass me-2 text-warning"></i> الإدارة الاستراتيجية</h2>
            <p class="text-muted mb-0">مركز توجيه المسار والسيطرة طويلة الأمد</p>
        </div>
        <div class="col-md-6 text-md-end mt-3 mt-md-0 d-flex justify-content-md-end gap-2 align-items-center">
            <button onclick="carryOverGoals()" class="btn btn-outline-info btn-sm fw-bold shadow-sm" title="استيراد الأهداف غير المكتملة من الشهر الماضي"><i class="fa-solid fa-box-archive"></i> ترحيل السابق</button>
            <a href="?m=<?= date('Y-m', strtotime($currentMonth . '-01 -1 month')) ?>" class="btn btn-outline-secondary btn-sm"><i class="fa-solid fa-chevron-right"></i></a>
            <h5 class="fw-bold mb-0 mx-3"><?= date('F Y', strtotime($currentMonth . '-01')) ?></h5>
            <a href="?m=<?= date('Y-m', strtotime($currentMonth . '-01 +1 month')) ?>" class="btn btn-outline-secondary btn-sm"><i class="fa-solid fa-chevron-left"></i></a>
        </div>
    </div>

    <!-- 1. Strategic Action Box (Insights) -->
    <?php if (!empty($insights)): ?>
    <div class="row mb-4">
        <div class="col-12">
            <?php foreach($insights as $in): ?>
            <div class="alert alert-<?= $in['type'] ?> border-0 shadow-sm rounded-4 d-flex align-items-start px-4 py-3 mb-2" style="border-right: 6px solid var(--bs-<?= $in['type'] ?>);">
                <div class="fs-3 me-3 mt-1"><i class="fa-solid fa-brain"></i></div>
                <div>
                    <h6 class="fw-bold mb-1 opacity-75"><?= $in['title'] ?></h6>
                    <div class="mb-0 fs-5 fw-bold"><?= $in['message'] ?></div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- 2. The One Goal (Primary Focus) -->
    <?php
        $primaryGoal = null;
        $otherGoals = [];
        foreach($goals as $g) {
            if ($g->is_primary == 1) $primaryGoal = $g;
            else $otherGoals[] = $g;
        }
    ?>
    <?php if ($primaryGoal): ?>
        <?php
            $target = $primaryGoal->target_value > 0 ? $primaryGoal->target_value : 1;
            $pct = min(100, round(($primaryGoal->current_progress / $target) * 100));
        ?>
        <div class="card border-warning shadow-lg rounded-4 mb-4 position-relative overflow-hidden" style="background-color: #fffff8;">
            <div class="position-absolute" style="top: -20px; right: -20px; font-size: 8rem; opacity: 0.05;">
                <i class="fa-solid fa-star"></i>
            </div>
            <div class="card-body p-5">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <span class="badge bg-warning text-dark mb-2 position-relative z-1 px-3 py-2 rounded-pill"><i class="fa-solid fa-star me-1"></i> هدف الشهر الأعظم</span>
                        <h2 class="fw-bold text-dark mb-3 position-relative z-1"><?= htmlspecialchars($primaryGoal->title) ?></h2>
                        <div class="d-flex gap-3 text-secondary fw-bold position-relative z-1 mb-3">
                            <span><i class="fa-solid <?= $primaryGoal->cat_icon ?>"></i> <?= htmlspecialchars($primaryGoal->cat_name) ?></span>
                            <span><i class="fa-solid fa-dumbbell"></i> <?= $primaryGoal->difficulty === 'hard' ? 'صعب' : ($primaryGoal->difficulty === 'easy' ? 'سهل' : 'متوسط') ?></span>
                        </div>
                    </div>
                    <div class="col-md-4 text-center">
                        <div class="display-4 fw-bold text-<?= $pct >= 100 ? 'success' : 'warning' ?> mb-2"><?= $pct ?>%</div>
                        <div class="progress rounded-pill mb-2" style="height: 12px;">
                            <div class="progress-bar bg-<?= $pct >= 100 ? 'success' : 'warning' ?> rounded-pill" style="width: <?= $pct ?>%;"></div>
                        </div>
                        <small class="fw-bold text-muted"><?= $primaryGoal->current_progress ?> / <?= $primaryGoal->target_value ?></small>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- 3. Monthly Score & Overview -->
    <div class="row g-4 mb-4">
        <div class="col-md-4">
            <div class="card card-saas border-0 shadow-sm text-center h-100 bg-white p-3">
                <div class="card-body">
                    <h6 class="text-secondary fw-bold mb-3">التقييم الاستراتيجي</h6>
                    <div class="display-5 fw-bold text-dark mb-2"><?= $monthlyScore['label'] ?> (<?= $monthlyScore['score'] ?>%)</div>
                </div>
            </div>
        </div>
        <div class="col-md-8">
            <div class="card card-saas border-0 shadow-sm h-100 bg-white p-3">
                <div class="card-body d-flex justify-content-around align-items-center text-center">
                    <div>
                        <div class="display-6 fw-bold text-primary mb-1"><?= $monthlyScore['completion'] ?>%</div>
                        <small class="text-muted fw-bold">نسبة الإنجاز</small>
                    </div>
                    <div style="border-left: 2px solid #eee; height: 50px;"></div>
                    <div>
                        <div class="display-6 fw-bold text-success mb-1"><?= $monthlyScore['consistency'] ?>%</div>
                        <small class="text-muted fw-bold">معدل الاستمرارية (البدء)</small>
                    </div>
                    <div style="border-left: 2px solid #eee; height: 50px;"></div>
                    <div>
                        <div class="display-6 fw-bold text-info mb-1"><?= $monthlyScore['balance'] ?>%</div>
                        <small class="text-muted fw-bold">التوازن الإداري</small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Actions -->
    <div class="d-flex justify-content-between mb-3 align-items-center">
        <h4 class="fw-bold text-dark mb-0"><i class="fa-solid fa-list-check me-2 text-primary"></i> المحفظة الاستراتيجية</h4>
        <div class="gap-2 d-flex">
            <button class="btn btn-outline-secondary fw-bold shadow-sm rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#categoriesModal">
                <i class="fa-solid fa-tags me-1"></i> الأقسام
            </button>
            <button class="btn btn-primary fw-bold shadow-sm rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#addGoalModal">
                <i class="fa-solid fa-plus me-1"></i> إضافة مقياس
            </button>
        </div>
    </div>

    <!-- Goal Cards Grouped by Category -->
    <style>
        .goal-card { transition: all 0.2s ease; cursor: default; }
        .goal-card:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(0,0,0,0.1) !important; }
        .goal-card.is-done { opacity: 0.7; background: #f8fff8 !important; }
        .done-toggle { width: 40px; height: 40px; border-radius: 50%; border: 2.5px solid #dee2e6; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; flex-shrink: 0; }
        .done-toggle:hover { border-color: #198754; background: #d1fae5; }
        .done-toggle.checked { background: #198754; border-color: #198754; color: white; }
        .cat-section-title { display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0; border-bottom: 2px solid #f0f0f0; margin-bottom: 1rem; margin-top: 2rem; }
        .cat-section-title:first-child { margin-top: 0; }
    </style>
    <?php
        $goalsByCat = [];
        foreach($goals as $g) {
            $cId = $g->category_id ?? 0;
            $goalsByCat[$cId][] = $g;
        }
    ?>

    <?php if(empty($goals)): ?>
        <div class="card border-0 shadow-sm rounded-4 bg-white mb-5">
            <div class="text-center py-5">
                <i class="fa-solid fa-map text-muted fa-3x mb-3 opacity-25"></i>
                <h5 class="text-muted">الاستراتيجية فارغة.</h5>
                <p class="text-muted small">ضع أهدافاً قابلة للقياس وانطلق.</p>
            </div>
        </div>
    <?php else: ?>
        <?php foreach($categories as $cat): ?>
            <?php 
                if (empty($goalsByCat[$cat->id])) continue; 
                $catGoals = $goalsByCat[$cat->id];
                $color = htmlspecialchars($cat->color_theme);
                $icon  = htmlspecialchars($cat->icon);
                $catName = htmlspecialchars($cat->name);
                $catCompleted = count(array_filter($catGoals, fn($g) => $g->status === 'completed' || $g->current_progress >= $g->target_value));
                $catTotal = count($catGoals);
            ?>

            <!-- Category Header -->
            <div class="cat-section-title">
                <div class="rounded-3 d-flex align-items-center justify-content-center text-<?= $color ?> bg-<?= $color ?> bg-opacity-10" style="width:42px;height:42px;flex-shrink:0;">
                    <i class="fa-solid <?= $icon ?> fs-5"></i>
                </div>
                <div class="flex-grow-1">
                    <h5 class="fw-bold text-<?= $color ?> mb-0"><?= $catName ?></h5>
                </div>
                <span class="badge bg-light text-dark border fw-bold px-3 py-2">
                    <?= $catCompleted ?> / <?= $catTotal ?> مكتمل
                </span>
            </div>

            <!-- Cards Grid -->
            <div class="row g-3 mb-2">
                <?php foreach($catGoals as $goal): ?>
                    <?php
                        $isDone = ($goal->status === 'completed' || ($goal->target_value > 0 && $goal->current_progress >= $goal->target_value));
                        $pct    = $goal->target_value > 0 ? min(100, round(($goal->current_progress / $goal->target_value) * 100)) : 0;
                        $diffColor = $goal->difficulty === 'hard' ? 'danger' : ($goal->difficulty === 'easy' ? 'success' : 'warning');
                        $diffLabel = $goal->difficulty === 'hard' ? 'صعب 🔴' : ($goal->difficulty === 'easy' ? 'سهل 🟢' : 'متوسط 🟡');
                        $barColor  = $isDone ? 'success' : ($pct >= 60 ? 'primary' : ($pct >= 30 ? 'warning' : 'danger'));
                    ?>
                    <div class="col-md-6 col-lg-4">
                        <div class="card goal-card border-0 shadow-sm rounded-4 h-100 <?= $isDone ? 'is-done' : '' ?> position-relative overflow-hidden">
                            <!-- Color Accent Strip -->
                            <div style="height: 4px; background: var(--bs-<?= $color ?>);"></div>
                            <div class="card-body p-4">
                                <!-- Header Row -->
                                <div class="d-flex justify-content-between align-items-start mb-3">
                                    <div class="flex-grow-1 me-2">
                                        <h6 class="fw-bold text-dark mb-1 lh-sm <?= $isDone ? 'text-decoration-line-through text-muted' : '' ?>">
                                            <?= htmlspecialchars($goal->title) ?>
                                        </h6>
                                        <div class="d-flex gap-2 flex-wrap">
                                            <span class="badge bg-<?= $diffColor ?> bg-opacity-10 text-<?= $diffColor ?> border border-<?= $diffColor ?>" style="font-size:0.65rem;"><?= $diffLabel ?></span>
                                            <?php if ($goal->integration_type !== 'manual'): ?>
                                                <span class="badge bg-info bg-opacity-10 text-info border border-info" style="font-size:0.65rem;"><i class="fa-solid fa-code-merge me-1"></i>ذكي</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="d-flex flex-column gap-1 align-items-end">
                                        <!-- Star (Primary Goal) -->
                                        <button onclick="togglePrimary(<?= $goal->id ?>)" class="btn btn-link p-0 lh-1 link-<?= $goal->is_primary ? 'warning' : 'secondary opacity-25' ?>" title="تمييز كهدف أعظم">
                                            <i class="fa-solid fa-star"></i>
                                        </button>
                                        <!-- Delete -->
                                        <button onclick="deleteGoal(<?= $goal->id ?>)" class="btn btn-link p-0 lh-1 link-danger opacity-25 hover-opacity-100" title="حذف">
                                            <i class="fa-solid fa-trash fs-7"></i>
                                        </button>
                                    </div>
                                </div>

                                <!-- Progress Bar -->
                                <div class="mb-2">
                                    <div class="d-flex justify-content-between small fw-bold mb-1">
                                        <span class="text-muted">التقدم</span>
                                        <span class="text-<?= $barColor ?>"><?= $pct ?>%</span>
                                    </div>
                                    <div class="progress rounded-pill" style="height: 8px;">
                                        <div class="progress-bar bg-<?= $barColor ?> rounded-pill" style="width: <?= $pct ?>%;"></div>
                                    </div>
                                </div>

                                <!-- Footer: Toggle Button -->
                                <?php if ($goal->integration_type === 'manual'): ?>
                                <div class="mt-3 pt-2 border-top d-flex justify-content-between align-items-center">
                                    <?php if ($isDone): ?>
                                        <span class="text-success fw-bold small"><i class="fa-solid fa-circle-check me-1"></i> مكتمل</span>
                                        <button onclick="toggleDone(<?= $goal->id ?>, <?= $goal->target_value ?>, false)" class="btn btn-sm btn-outline-secondary rounded-pill px-3 fw-bold" style="font-size:0.75rem;">
                                            <i class="fa-solid fa-arrow-rotate-left me-1"></i> إعادة فتح
                                        </button>
                                    <?php else: ?>
                                        <span class="text-muted small fw-bold"><i class="fa-regular fa-circle me-1"></i> قيد التنفيذ</span>
                                        <button onclick="toggleDone(<?= $goal->id ?>, <?= $goal->target_value ?>, true)" class="btn btn-sm btn-success rounded-pill px-3 fw-bold text-white" style="font-size:0.75rem;">
                                            <i class="fa-solid fa-check me-1"></i> تم الإنجاز
                                        </button>
                                    <?php endif; ?>
                                </div>
                                <?php else: ?>
                                <div class="mt-3 pt-2 border-top">
                                    <small class="text-muted fw-bold"><i class="fa-solid fa-robot me-1"></i> يتحدث تلقائياً من <?= $goal->integration_type ?></small>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>



    <!-- End of Month Reflection -->
    <?php if (date('d') >= 25 || count(array_filter($goals, fn($g)=>$g->status==='completed')) > 0): ?>
    <div class="card border-0 shadow-sm rounded-4 bg-dark text-white mb-5 p-4">
        <h4 class="fw-bold mb-4 text-warning"><i class="fa-solid fa-quote-right me-2"></i> التأمل الاستراتيجي (Reflection)</h4>
        <form id="reflectionForm">
            <input type="hidden" name="plan_id" value="<?= $plan->id ?>">
            <div class="row g-4">
                <div class="col-md-4">
                    <label class="fw-bold text-success mb-2"><i class="fa-solid fa-check-circle me-1"></i> ماذا نجح هذا الشهر؟</label>
                    <textarea name="worked" class="form-control bg-dark text-white border-secondary" rows="3"><?= htmlspecialchars($plan->reflection_worked ?? '') ?></textarea>
                </div>
                <div class="col-md-4">
                    <label class="fw-bold text-danger mb-2"><i class="fa-solid fa-circle-xmark me-1"></i> ما الذي أخفق؟</label>
                    <textarea name="failed" class="form-control bg-dark text-white border-secondary" rows="3"><?= htmlspecialchars($plan->reflection_failed ?? '') ?></textarea>
                </div>
                <div class="col-md-4">
                    <label class="fw-bold text-info mb-2"><i class="fa-solid fa-lightbulb me-1"></i> لماذا؟ (الدروس المستفادة)</label>
                    <textarea name="why" class="form-control bg-dark text-white border-secondary" rows="3"><?= htmlspecialchars($plan->reflection_why ?? '') ?></textarea>
                </div>
            </div>
            <div class="mt-4 text-end">
                <button type="submit" class="btn btn-warning fw-bold px-5 text-dark rounded-pill">حفظ التأمل</button>
            </div>
        </form>
    </div>
    <?php endif; ?>
</div>

<!-- Add Goal Modal -->
<div class="modal fade" id="addGoalModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form id="addGoalForm" class="modal-content border-0 shadow" data-no-pjax="true">
            <div class="modal-header bg-light border-0">
                <h5 class="modal-title fw-bold">إضافة مقياس استراتيجي</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                
                <!-- Smart Generators -->
                <div class="mb-4 p-3 bg-primary bg-opacity-10 rounded-4 border border-primary border-opacity-25">
                    <h6 class="fw-bold text-primary mb-3"><i class="fa-solid fa-wand-magic-sparkles me-2"></i> مولد الأهداف السريع</h6>
                    <div class="d-flex flex-wrap gap-2">
                        <button type="button" class="btn btn-sm btn-white border shadow-sm fw-bold" onclick="prefillGoal('الالتزام بـ 20 تمرين', ' health_workouts', 20, 'hard')">🏃 20 تمرين</button>
                        <button type="button" class="btn btn-sm btn-white border shadow-sm fw-bold" onclick="prefillGoal('إنجاز 100 مهمة مركزة', 'tasks_done', 100, 'medium')">✅ 100 مهمة</button>
                        <button type="button" class="btn btn-sm btn-white border shadow-sm fw-bold" onclick="prefillGoal('تجنب الإخفاقات السلوكية', 'behavior_fails', 5, 'hard')">🧠 مناعة سلوكية (5)</button>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">اسم الهدف</label>
                    <input type="text" name="title" id="formTitle" class="form-control form-control-lg" placeholder="مثال: إكمال مشروع التخرج" required>
                </div>
                <div class="row mb-3 g-3">
                    <div class="col-md-4">
                        <label class="form-label fw-bold">القسم</label>
                        <select name="category_id" id="formCat" class="form-select text-dark fw-bold" required>
                            <?php foreach($categories as $c): ?>
                                <option value="<?= $c->id ?>"><?= htmlspecialchars($c->name) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-bold">الرقم المستهدف</label>
                        <input type="number" name="target_value" id="formTarget" class="form-control text-primary fw-bold" value="1" min="1" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-bold">صعوبة التنفيذ (العبء)</label>
                        <select name="difficulty" id="formDiff" class="form-select fw-bold">
                            <option value="easy">سهل 🟢</option>
                            <option value="medium" selected>متوسط 🟡</option>
                            <option value="hard">صعب 🔴</option>
                        </select>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">التتبع والربط الآلي للمقاييس</label>
                    <select name="integration_type" id="formInt" class="form-select fw-bold bg-light" onchange="document.getElementById('integrationHelp').innerText = this.options[this.selectedIndex].dataset.help;">
                        <option value="manual" data-help="سوف تقوم بتحديث الرقم يدوياً.">تحديث يدوي (Manual)</option>
                        <option value="tasks_done" data-help="يجمع المهام المنجزة خلال الشهر تلقائياً.">📌 المزامنة مع قائمة المهام المنجزة</option>
                        <option value="education_courses" data-help="يحسب الدورات المكتملة في الاستيديو.">🎓 المزامنة مع الدورات المكتملة</option>
                        <option value="finance_income" data-help="إجمالي الدخل الوارد خلال الشهر.">💸 المزامنة مع إجمالي الدخل</option>
                        <option value="finance_spent" data-help="تتبع الحد الأقصى للمصروفات.">📉 المزامنة مع الإنفاق</option>
                        <option value="health_workouts" data-help="احتساب عدد التمارين المسجلة في الصحية.">🏃 المزامنة مع الرياضة والتمارين</option>
                        <option value="behavior_fails" data-help="الأفضل إعطاؤه مقياس مقلوب (مثلاً أقصى حد 5 إخفاقات للحفاظ على المكتسبات).">🧠 تتبع انتهاكات السلوكيات الإدمانية</option>
                    </select>
                    <small id="integrationHelp" class="text-muted d-block mt-2">سوف تقوم بتحديث الرقم يدوياً.</small>
                </div>
            </div>
            <div class="modal-footer border-0 bg-light">
                <button type="submit" class="btn btn-primary px-5 rounded-pill fw-bold">بدء التتبع</button>
            </div>
        </form>
    </div>
</div>

<!-- Categories Manager Modal -->
<div class="modal fade" id="categoriesModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-light border-0">
                <h5 class="modal-title fw-bold">إدارة البنية الاستراتيجية (الأقسام) <i class="fa-solid fa-list text-primary"></i></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <ul class="list-group list-group-flush mb-4" id="catList">
                    <?php foreach($categories as $c): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center py-3">
                        <span class="fw-bold text-dark"><i class="fa-solid <?= htmlspecialchars($c->icon) ?> text-<?= htmlspecialchars($c->color_theme) ?> me-2"></i> <?= htmlspecialchars($c->name) ?></span>
                        <button class="btn btn-sm text-danger opacity-50 hover-opacity-100" onclick="deleteCategory(<?= $c->id ?>, this)"><i class="fa-solid fa-trash"></i></button>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <form id="addCategoryForm" class="bg-light p-3 rounded-4" data-no-pjax="true">
                    <h6 class="fw-bold mb-3">إضافة قسم جديد</h6>
                    <div class="mb-2">
                        <label class="small text-muted mb-1">اسم القسم</label>
                        <input type="text" name="name" class="form-control bg-white" required>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="small text-muted mb-1">اللون</label>
                            <select name="color_theme" class="form-select bg-white">
                                <option value="primary">أزرق</option><option value="success">أخضر</option><option value="danger">أحمر</option><option value="warning">أصفر</option>
                            </select>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-sm btn-dark w-100 mt-2 fw-bold rounded-pill">إضافة قسم</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
let hasCatChanges = false;
document.addEventListener('DOMContentLoaded', function() {
    if (localStorage.getItem('reopenCatModal') === 'true') {
        localStorage.removeItem('reopenCatModal');
        new bootstrap.Modal(document.getElementById('categoriesModal')).show();
    }
    document.getElementById('categoriesModal').addEventListener('hidden.bs.modal', function() { if(hasCatChanges) window.location.reload(); });
});

function prefillGoal(title, intType, target, diff) {
    document.getElementById('formTitle').value = title;
    document.getElementById('formInt').value = intType;
    document.getElementById('formTarget').value = target;
    document.getElementById('formDiff').value = diff;
}

document.getElementById('addGoalForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(this));
    data.month = '<?= $currentMonth ?>';
    fetch('<?= BASE_URL ?>/monthlyplan/addGoal', {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data)
    }).then(res => res.json()).then(res => { if (res.success) window.location.reload(); });
});

function deleteGoal(id) {
    if(!confirm('تأكيد حذف الهدف الاستراتيجي؟')) return;
    fetch('<?= BASE_URL ?>/monthlyplan/deleteGoal', {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({id: id})
    }).then(() => window.location.reload());
}

function toggleDone(id, targetValue, isDone) {
    const progress = isDone ? targetValue : 0;
    const status   = isDone ? 'completed' : 'active';
    fetch('<?= BASE_URL ?>/monthlyplan/updateProgress', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: id, progress: progress })
    }).then(() => window.location.reload());
}

function togglePrimary(id) {
    fetch('<?= BASE_URL ?>/monthlyplan/togglePrimaryGoal', {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({id: id})
    }).then(() => window.location.reload());
}

function carryOverGoals() {
    if(!confirm('هل تود جلب أهداف الشهر الماضي غير المنجزة إلى هذا الشهر؟')) return;
    fetch('<?= BASE_URL ?>/monthlyplan/carryOverGoals', {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({month: '<?= $currentMonth ?>'})
    }).then(() => window.location.reload());
}

document.getElementById('addCategoryForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(this));
    fetch('<?= BASE_URL ?>/monthlyplan/addCategory', {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data)
    }).then(res => res.json()).then(res => {
        if (res.success) {
            hasCatChanges = true;
            window.location.reload();
        }
    });
});

document.getElementById('reflectionForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(this));
    fetch('<?= BASE_URL ?>/monthlyplan/saveReflection', {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data)
    }).then(() => {
        alert('تم حفظ تقييمك الاستراتيجي بنجاح.');
    });
});

function deleteCategory(id, btnElement = null) {
    if(!confirm('تأكيد حذف القسم؟ سيتم إزالة أهدافه الفرعية أيضًا.')) return;
    fetch('<?= BASE_URL ?>/monthlyplan/deleteCategory', {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({id: id})
    }).then(() => {
        hasCatChanges = true;
        if (btnElement) btnElement.closest('li').remove();
        else window.location.reload();
    });
}
</script>
