<?php
/**
 * TASK INTELLIGENCE ENGINE - Command Center Dashboard
 */
$prevDay = date('Y-m-d', strtotime($targetDate . ' -1 day'));
$nextDay = date('Y-m-d', strtotime($targetDate . ' +1 day'));
$today   = date('Y-m-d');
$isToday = ($targetDate === $today);

$priorityProps = [
    'high' => ['badge' => 'bg-danger', 'text' => 'text-danger', 'icon' => 'fa-fire', 'name'=>'أولوية قصوى'],
    'medium' => ['badge' => 'bg-warning text-dark', 'text' => 'text-warning', 'icon' => 'fa-bolt', 'name'=>'متوسطة'],
    'low' => ['badge' => 'bg-success', 'text' => 'text-success', 'icon' => 'fa-leaf', 'name'=>'عادية']
];

// Unified Categories Map
$catMap = [];
if (!empty($customCategories)) {
    foreach ($customCategories as $c) {
        $catKey = $c->system_key ?: 'cat_' . $c->id;
        $catMap[$catKey] = ['name' => $c->name, 'bg' => $c->bg_color, 'text' => $c->text_color, 'border' => $c->border_color];
    }
}
$catFallback = ['bg' => '#f3f4f6', 'text' => '#475569', 'border' => '#e2e8f0', 'name' => 'عام'];

?>
<style>
@import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap');
body { font-family: 'Tajawal', sans-serif; background-color: #f1f5f9; }

/* Dashboard Typography & Spacing */
.page-title { font-weight: 800; letter-spacing: -0.5px; color: #0f172a; }
.sub-title { font-size: 0.95rem; color: #64748b; font-weight: 500; }

/* Control Bar */
.control-bar { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 15px; margin-bottom: 30px; }
.nav-arrows { display: flex; align-items: center; background: #fff; padding: 6px; border-radius: 50px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); }
.nav-arrows a { width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; border-radius: 50%; color: #64748b; transition: 0.2s; }
.nav-arrows a:hover { background: #f8fafc; color: #3b82f6; }
.nav-arrows input { border: none; background: transparent; font-weight: 800; font-size: 1.1rem; color: #1e293b; width: 140px; text-align: center; }

/* Stats Widgets */
.stat-widget { background: #fff; border-radius: 20px; padding: 20px; box-shadow: 0 5px 25px rgba(0,0,0,0.02); height: 100%; border: 1px solid #f1f5f9; position: relative; overflow: hidden; }
.stat-value { font-size: 2.5rem; font-weight: 800; line-height: 1; margin: 10px 0; }
.stat-title { font-size: 0.9rem; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 1px; }

/* Momentum Visuals */
.momentum-high { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: #fff; }
.momentum-high .stat-title, .momentum-high .stat-value { color: #fff; }
.momentum-med { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: #fff; }
.momentum-med .stat-title, .momentum-med .stat-value { color: #fff; }
.progress-ring { width: 80px; height: 80px; }
.progress-ring circle { transition: stroke-dashoffset 0.5s ease-in-out; }

/* The Stage */
.stage-card { background: #fff; border-radius: 24px; padding: 25px; box-shadow: 0 10px 40px rgba(0,0,0,0.03); border: 1px solid rgba(255,255,255,0.8); margin-bottom: 25px; }

/* Focus Bucket */
.focus-bucket { border-radius: 16px; padding: 20px; }
.focus-bucket-active { background: #f0f9ff; border: 2px dashed #bae6fd; }

/* Task Cards */
.task-item { background: #ffffff; border-radius: 14px; padding: 15px 20px; margin-bottom: 12px; border: 1px solid #e2e8f0; transition: all 0.3s; position: relative; display: flex; align-items: flex-start; gap: 15px; }
.task-item:hover { box-shadow: 0 8px 25px rgba(0,0,0,0.06); transform: translateY(-2px); border-color: #cbd5e1; }
.task-item.completed { opacity: 0.6; filter: grayscale(0.5); }
.task-item.completed .task-title { text-decoration: line-through; color: #94a3b8; }

.task-checkbox-wrap { padding-top: 3px; }
.task-checkbox { width: 22px; height: 22px; cursor: pointer; accent-color: #3b82f6; }

.task-content { flex-grow: 1; }
.task-title { font-size: 1.05rem; font-weight: 700; color: #1e293b; margin-bottom: 8px; transition: 0.2s; }

/* Priority & Category Badges */
.meta-badges { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.badge-pill { padding: 4px 10px; border-radius: 50px; font-size: 0.75rem; font-weight: 700; display: inline-flex; align-items: center; gap: 5px; }

/* Overdue Alert Strip */
.overdue-strip { background: #fef2f2; border-right: 4px solid #ef4444; border-radius: 12px; padding: 15px; margin-bottom: 20px; display: flex; align-items: center; justify-content: space-between; }

/* Close Day Link */
.close-day-btn { background: #1e293b; color: white; border-radius: 50px; padding: 12px 25px; font-weight: 700; text-decoration: none; display: inline-flex; align-items: center; gap: 10px; border: none; transition: 0.3s; }
.close-day-btn:hover { background: #0f172a; transform: scale(1.05); color: white; }

</style>

<div class="container-fluid py-2">

    <!-- OVERDUE MANAGER DRAWER -->
    <?php if(!empty($overdueTasks)): ?>
    <div class="overdue-strip shadow-sm">
        <div class="d-flex align-items-center gap-3">
            <div class="bg-white rounded-circle d-flex align-items-center justify-content-center text-danger shadow-sm" style="width:40px;height:40px;">
                <i class="fa-solid fa-triangle-exclamation fs-5"></i>
            </div>
            <div>
                <h6 class="fw-bold m-0 text-danger">ملاحظة ذكية! لديك مهام متأخرة</h6>
                <p class="m-0 fs-7 text-secondary">يوجد <?= count($overdueTasks) ?> مهمة لم يتم إنجازها في وقتها، النظام يقترح إعادة جدولتها لليوم لتنظيم عقلك.</p>
            </div>
        </div>
        <button class="btn btn-danger rounded-pill fw-bold" data-bs-toggle="modal" data-bs-target="#overdueModal">معالجتها الآن</button>
    </div>
    <?php endif; ?>

    <!-- Control Bar -->
    <div class="control-bar">
        <div>
            <h1 class="page-title m-0">محرك المهام <i class="fa-solid fa-bolt text-warning ms-1"></i></h1>
            <p class="sub-title m-0 mt-1">تخطيط ذكي، تنفيذ دقيق، وزخم مستمر.</p>
        </div>
        <div class="nav-arrows">
            <a href="<?= BASE_URL ?>/todo/index?date=<?= $prevDay ?>"><i class="fa-solid fa-chevron-right"></i></a>
            <input type="date" value="<?= $targetDate ?>" onchange="window.location.href='/todo/index?date='+this.value">
            <a href="<?= BASE_URL ?>/todo/index?date=<?= $nextDay ?>"><i class="fa-solid fa-chevron-left"></i></a>
        </div>
        <?php if(!$isToday): ?>
            <a href="<?= BASE_URL ?>/todo/index?date=<?= $today ?>" class="btn btn-outline-primary rounded-pill fw-bold">العودة لليوم</a>
        <?php else: ?>
            <a href="<?= BASE_URL ?>/journal/manage" class="close-day-btn shadow-sm">
                <i class="fa-solid fa-book-journal-whills"></i> إغلاق اليوم
            </a>
        <?php endif; ?>
    </div>

    <!-- STATS ROW -->
    <div class="row g-4 mb-4">
        <!-- Momentum Stat -->
        <div class="col-md-4">
            <?php 
                $mClass = 'bg-white';
                if ($momentumScore['score'] >= 90) $mClass = 'momentum-high shadow-lg';
                if ($momentumScore['score'] >= 75 && $momentumScore['score'] < 90) $mClass = 'momentum-med shadow-sm';
            ?>
            <div class="stat-widget <?= $mClass ?>">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-title opacity-75">مؤشر الزخم (Momentum)</div>
                        <div class="stat-value"><?= $momentumScore['score'] ?>%</div>
                        <div class="fw-bold opacity-75 fs-7"><i class="fa-solid fa-fire me-1"></i> <?= $momentumScore['label'] ?></div>
                    </div>
                    <!-- SVGs drawn dynamically below -->
                    <div style="position:relative; width:80px; height:80px;">
                        <svg class="progress-ring" width="80" height="80">
                          <circle stroke="<?= $mClass==='bg-white' ? '#e2e8f0' : 'rgba(255,255,255,0.3)' ?>" stroke-width="6" fill="transparent" r="34" cx="40" cy="40"/>
                          <circle id="momentumRing" class="progress-ring__circle" stroke="<?= $mClass==='bg-white' ? '#3b82f6' : '#fff' ?>" stroke-width="6" stroke-linecap="round" fill="transparent" r="34" cx="40" cy="40"/>
                        </svg>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="stat-widget d-flex align-items-center gap-3">
                <div class="bg-light rounded-circle d-flex justify-content-center align-items-center" style="width:60px;height:60px;">
                    <i class="fa-solid fa-check-double fs-3 text-success"></i>
                </div>
                <div>
                    <div class="stat-title">الإنجاز الرقمي</div>
                    <div class="stat-value mb-1"><span id="doneCount"><?= $completedTasks ?></span> <span class="fs-5 text-muted fw-normal">/ <?= $totalTasks ?></span></div>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="stat-widget p-0" style="background:none; border:none; box-shadow:none;">
                <form action="<?= BASE_URL ?>/todo/storeTask" method="POST" class="bg-white p-3 rounded-4 shadow-sm h-100 border">
                    <?= csrf_field() ?>
                    <input type="hidden" name="target_date" value="<?= $targetDate ?>">
                    <h6 class="fw-bold fs-7 text-primary mb-3"><i class="fa-solid fa-bolt me-1"></i> أضف مهمة جديدة</h6>
                    <div class="input-group input-group-lg mb-2">
                        <input type="text" name="title" class="form-control border-light bg-light rounded-start-pill fs-6" placeholder="اكتب المهمة هنا..." required>
                        <button type="submit" class="btn btn-primary rounded-end-pill px-4"><i class="fa-solid fa-paper-plane"></i></button>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mt-2 px-1">
                        <select name="priority" class="form-select form-select-sm border-0 bg-transparent w-auto py-0 fw-bold text-secondary">
                            <option value="medium" selected>م. عادية</option>
                            <option value="high">م. قصوى</option>
                        </select>
                        <select name="category" class="form-select form-select-sm border-0 bg-transparent w-auto py-0 fw-bold text-secondary">
                            <?php foreach($catMap as $sysKey => $data): ?>
                            <option value="<?= $sysKey ?>"><?= $data['name'] ?></option>
                            <?php endforeach; ?>
                        </select>
                        <label class="form-check-label fs-7 fw-bold" title="ربط بالتقويم">
                            <i class="fa-regular fa-calendar-check text-primary"></i>
                            <input class="form-check-input ms-1" type="checkbox" name="add_to_calendar" value="1" checked style="accent-color:#3b82f6;">
                        </label>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?= display_flash_message('todo') ?>

    <div class="row g-4">
        <!-- THE LIST -->
        <div class="col-lg-12">
            <div class="stage-card">

                <!-- INTENTIONAL FOCUS MODE -->
                <div class="focus-bucket focus-bucket-active mb-5" ondragover="allowDrop(event)" ondrop="dropToFocus(event)" ondragenter="dragEnterFocus(event)" ondragleave="dragLeaveFocus(event)" id="focusContainer">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h5 class="fw-bold text-primary m-0"><i class="fa-solid fa-crosshairs me-2"></i> منطقة التركيز اليومي</h5>
                        <span class="badge bg-white text-primary border rounded-pill shadow-sm py-2 px-3 fw-bold"><i class="fa-solid fa-lightbulb text-warning me-1"></i> اسحب الـ Top 3 هنا</span>
                    </div>

                    <div class="row g-3">
                        <?php if(empty($focusTasks)): ?>
                            <div class="col-12">
                                <div class="text-center p-4 border border-info border-dashed rounded-4 bg-white opacity-75">
                                    <i class="fa-regular fa-star fs-3 text-info mb-2"></i>
                                    <p class="m-0 fw-bold text-info">لم تحدد تركيزك اليوم.</p>
                                </div>
                            </div>
                        <?php else: ?>
                            <?php foreach($focusTasks as $t): 
                                $isDone = ($t->status === 'done');
                                $pUI = $priorityProps[$t->priority];
                                $cUI = $catMap[$t->category] ?? $catFallback;
                            ?>
                                <div class="col-md-4">
                                    <div class="task-item shadow-sm <?= $isDone ? 'completed' : '' ?>" id="task-card-<?= $t->id ?>" data-id="<?= $t->id ?>" draggable="true" ondragstart="dragStartTask(event)" style="border-right:4px solid <?= $isDone ? '#94a3b8' : '#3b82f6' ?>;">
                                        <div class="task-checkbox-wrap">
                                            <input class="task-checkbox" type="checkbox" onchange="updateTaskStatus(<?= $t->id ?>, this.checked)" <?= $isDone ? 'checked' : '' ?>>
                                        </div>
                                        <div class="task-content">
                                            <div class="task-title" title="<?= htmlspecialchars($t->title) ?>"><?= htmlspecialchars($t->title) ?></div>
                                            <div class="meta-badges">
                                                <span class="badge-pill bg-light border" style="color:<?= $cUI['text'] ?>"><i class="fa-solid fa-circle fa-2xs"></i> <?= $cUI['name'] ?></span>
                                                <?php if($t->estimated_time > 0): ?>
                                                    <span class="badge-pill bg-light border text-secondary"><i class="fa-regular fa-clock"></i> <?= $t->estimated_time ?> دق</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div>
                                            <button class="btn btn-sm text-warning" onclick="toggleFocus(<?= $t->id ?>, 0)"><i class="fa-solid fa-star"></i></button>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; endif; ?>
                    </div>
                </div>

                <!-- MAIN backlog -->
                <div class="d-flex justify-content-between align-items-center mb-4 pb-2 border-bottom">
                    <h5 class="fw-bold text-dark m-0"><i class="fa-solid fa-layer-group me-2 text-secondary"></i> باقي المهام</h5>
                </div>

                <div class="row g-3" id="regularContainer" ondragover="allowDrop(event)" ondrop="dropToRegular(event)">
                    <?php if(empty($regularTasks)): ?>
                        <div class="col-12 text-center py-5">
                            <i class="fa-solid fa-clipboard-check fs-1 text-light mb-3"></i>
                            <h6 class="fw-bold text-muted">القائمة فارغة!</h6>
                        </div>
                    <?php endif; ?>

                    <?php foreach($regularTasks as $t): 
                        $isDone = ($t->status === 'done');
                        $pUI = $priorityProps[$t->priority];
                        $cUI = $catMap[$t->category] ?? $catFallback;
                        $isOverdue = $t->is_overdue;
                    ?>
                        <div class="col-lg-6">
                            <div class="task-item <?= $isDone ? 'completed' : '' ?>" id="task-card-<?= $t->id ?>" data-id="<?= $t->id ?>" draggable="true" ondragstart="dragStartTask(event)">
                                <div class="task-checkbox-wrap">
                                    <input class="task-checkbox" type="checkbox" onchange="updateTaskStatus(<?= $t->id ?>, this.checked)" <?= $isDone ? 'checked' : '' ?>>
                                </div>
                                <div class="task-content">
                                    <div class="task-title">
                                        <?= htmlspecialchars($t->title) ?>
                                        <?php if($isOverdue): ?><span class="badge bg-danger ms-2" style="font-size:0.6rem;">متأخرة!</span><?php endif; ?>
                                        <?php if($t->event_id): ?><i class="fa-regular fa-calendar-check text-primary ms-1 fs-7" title="مرتبطة بالتقويم"></i><?php endif; ?>
                                    </div>
                                    <div class="meta-badges">
                                        <span class="badge-pill <?= $pUI['badge'] ?>"><i class="fa-solid <?= $pUI['icon'] ?>"></i> <?= $pUI['name'] ?></span>
                                        <span class="badge-pill" style="background:<?= $cUI['bg'] ?>; color:<?= $cUI['text'] ?>; border:1px solid <?= $cUI['border'] ?>"><?= $cUI['name'] ?></span>
                                        <?php if($t->estimated_time > 0): ?>
                                            <span class="badge-pill bg-light border text-secondary"><i class="fa-regular fa-clock"></i> <?= $t->estimated_time ?> دق</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="d-flex flex-column gap-1 align-items-center">
                                    <i class="fa-solid fa-grip-vertical text-muted mb-2 cursor-grab" style="cursor:grab;"></i>
                                    <?php if(!$isDone): ?>
                                        <button class="btn btn-sm text-secondary p-1" onclick="toggleFocus(<?= $t->id ?>, 1)" title="تسليط الضوء"><i class="fa-regular fa-star"></i></button>
                                    <?php endif; ?>
                                    <button class="btn btn-sm text-danger p-1" onclick="deleteTask(<?= $t->id ?>)" title="حذف"><i class="fa-regular fa-trash-can"></i></button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

            </div>
        </div>
    </div>
</div>

<!-- OVERDUE MANAGER MODAL -->
<div class="modal fade" id="overdueModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content border-0 shadow-lg rounded-4">
      <div class="modal-header bg-danger text-white border-0 py-3">
        <h5 class="modal-title fw-bold"><i class="fa-solid fa-triangle-exclamation me-2"></i> معالجة المهام المتأخرة</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-4 bg-light">
          <p class="mb-4 text-muted fw-bold">هذه المهام عالقة في الأيام الماضية. العبء الذهني يتراكم، إما أن تنجزها الآن، تؤجلها لتاريخ جديد، أو تحذفها بثقة!</p>
          <div class="list-group">
              <?php if(!empty($overdueTasks)): foreach($overdueTasks as $ot): ?>
                  <div class="list-group-item d-flex justify-content-between align-items-center mb-2 border rounded-3 shadow-sm" id="overdue-item-<?= $ot->id ?>">
                      <div>
                          <del class="text-danger fw-bold fs-7 d-block mb-1"><?= $ot->target_date ?></del>
                          <h6 class="fw-bold m-0"><?= htmlspecialchars($ot->title) ?></h6>
                      </div>
                      <div class="d-flex gap-2">
                          <button class="btn btn-sm btn-success fw-bold px-3 rounded-pill" onclick="rescheduleTask(<?= $ot->id ?>, '<?= $today ?>')"><i class="fa-solid fa-arrow-turn-down me-1"></i> لليوم</button>
                          <input type="date" class="form-control form-control-sm border-0 bg-light" style="width:130px; border-radius:50px;" onchange="rescheduleTask(<?= $ot->id ?>, this.value)">
                          <button class="btn btn-sm btn-outline-danger rounded-circle" onclick="deleteOverdue(<?= $ot->id ?>)"><i class="fa-solid fa-trash-can"></i></button>
                      </div>
                  </div>
              <?php endforeach; endif; ?>
          </div>
      </div>
    </div>
  </div>
</div>

<script>
// Token Security Initializer
const THE_CSRF_TOKEN = '<?= $_SESSION['csrf_token'] ?? '' ?>';

// Ring Progress Logic
const circle = document.getElementById('momentumRing');
if(circle) {
    const radius = circle.r.baseVal.value;
    const circumference = radius * 2 * Math.PI;
    circle.style.strokeDasharray = `${circumference} ${circumference}`;
    circle.style.strokeDashoffset = circumference;
    function setProgress(percent) {
        const offset = circumference - percent / 100 * circumference;
        circle.style.strokeDashoffset = offset;
    }
    setTimeout(() => setProgress(<?= $momentumScore['score'] ?>), 200);
}

// Global Toast System via OTIS if exists, else native fallback
function appToast(title, msg, type) {
    if(typeof OTIS !== 'undefined' && OTIS.toast) {
        OTIS.toast(title, msg, type);
    } else {
        alert(title + " - " + msg);
    }
}

// Drag & Drop
function dragStartTask(ev) {
    let card = ev.target.closest('.task-item');
    if(!card) return;
    ev.dataTransfer.setData("text/plain", card.getAttribute('data-id'));
    setTimeout(() => { card.style.opacity = '0.4'; }, 10);
}

function allowDrop(ev) { ev.preventDefault(); }

function dragEnterFocus(ev) {
    ev.preventDefault();
    let container = document.getElementById('focusContainer');
    if(container) container.classList.add('bg-white', 'shadow-lg');
}

function dragLeaveFocus(ev) {
    let container = document.getElementById('focusContainer');
    if(container) container.classList.remove('bg-white', 'shadow-lg');
}

function dropToFocus(ev) {
    ev.preventDefault();
    let container = document.getElementById('focusContainer');
    if(container) container.classList.remove('bg-white', 'shadow-lg');
    
    let taskId = ev.dataTransfer.getData("text/plain");
    if(taskId) toggleFocus(taskId, 1);
}

function dropToRegular(ev) {
    ev.preventDefault();
    let taskId = ev.dataTransfer.getData("text/plain");
    if(taskId) toggleFocus(taskId, 0);
}

// Sync Interactions
function updateTaskStatus(taskId, isChecked) {
    let newStatus = isChecked ? 'done' : 'pending';
    let card = document.getElementById('task-card-' + taskId);
    
    if(isChecked) { card.classList.add('completed'); } 
    else { card.classList.remove('completed'); }

    fetch('<?= BASE_URL ?>/todo/updateStatus', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ task_id: taskId, status: newStatus, target_date: '<?= $targetDate ?>', csrf_token: THE_CSRF_TOKEN })
    }).then(r => r.json()).then(data => {
        if(data.success) {
            document.getElementById('doneCount').innerText = data.done;
            if(circle) setProgress(data.momentum.score);
        } else {
            // Revert
            if(isChecked) card.classList.remove('completed'); else card.classList.add('completed');
            appToast('خطأ', 'فشل المزامنة', 'danger');
        }
    });
}

function toggleFocus(taskId, isFocus) {
    fetch('<?= BASE_URL ?>/todo/toggleFocus', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ task_id: taskId, is_focus: isFocus, csrf_token: THE_CSRF_TOKEN })
    }).then(r => r.json()).then(data => {
        if(data.success) {
            let card = document.getElementById('task-card-' + taskId);
            if(card) { card.style.transition = 'opacity 0.2s'; card.style.opacity = '0.5'; }
            setTimeout(() => window.location.reload(), 200);
        }
    });
}

function deleteTask(taskId) {
    if(!confirm('حذف نهائي؟')) return;
    fetch('<?= BASE_URL ?>/todo/delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ task_id: taskId, csrf_token: THE_CSRF_TOKEN })
    }).then(r => r.json()).then(data => {
        if(data.success) {
            let card = document.getElementById('task-card-' + taskId);
            if(card) card.remove();
        }
    });
}

// Overdue Manager
function rescheduleTask(taskId, newDate) {
    if(!newDate) return;
    fetch('<?= BASE_URL ?>/todo/reschedule', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ task_id: taskId, new_date: newDate, csrf_token: THE_CSRF_TOKEN })
    }).then(r => r.json()).then(data => {
        if(data.success) {
            let item = document.getElementById('overdue-item-' + taskId);
            if(item) item.remove();
            appToast('عظيم!', 'تم إعادة جدولة المهمة', 'success');
            setTimeout(() => window.location.reload(), 1500);
        }
    });
}

function deleteOverdue(taskId) {
    if(!confirm('إسقاط المهمة من حياتك؟')) return;
    fetch('<?= BASE_URL ?>/todo/delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ task_id: taskId, csrf_token: THE_CSRF_TOKEN })
    }).then(r => r.json()).then(data => {
        if(data.success) {
            let item = document.getElementById('overdue-item-' + taskId);
            if(item) item.remove();
        }
    });
}

</script>
