<?php
/**
 * Advanced Multi-View Calendar (Month, Week, Day)
 * Single-column, Full-width Premium Design
 */

$monthsArabic = [1=>'يناير',2=>'فبراير',3=>'مارس',4=>'أبريل',5=>'مايو',6=>'يونيو',7=>'يوليو',8=>'أغسطس',9=>'سبتمبر',10=>'أكتوبر',11=>'نوفمبر',12=>'ديسمبر'];
$daysHeader = ['السبت', 'الأحد', 'الإثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة'];

$viewMode = $viewMode ?? 'month';
$year = $year ?? date('Y');
$month = $month ?? date('n');

$todayDate = date('Y-m-d');
$currentTime = date('H:i:s');
$currentHour = date('H:i');

// Format Dynamic Categories for quick lookup
$catMap = [];
if (!empty($customCategories)) {
    foreach ($customCategories as $c) {
        $catKey = $c->system_key ?: 'cat_' . $c->id;
        $catMap[$catKey] = [
            'id' => $c->id,
            'name' => $c->name,
            'bg' => $c->bg_color,
            'text' => $c->text_color,
            'border' => $c->border_color
        ];
    }
}
$catFallback = ['bg' => '#f3f4f6', 'text' => '#374151', 'border' => '#9ca3af', 'name' => 'أخرى'];

// Now Engine Logic
$nowTask = null;
if (!empty($events)) {
    foreach ($events as $ev) {
        if ($ev->event_date === $todayDate && !empty($ev->start_time) && !empty($ev->end_time)) {
            if ($currentTime >= $ev->start_time && $currentTime <= $ev->end_time) {
                $nowTask = $ev;
                break;
            }
        }
    }
}
?>
<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: #f4f7f6; margin: 0; padding: 0; }

.cal-wrapper { max-width: 100%; margin: 0 auto; padding: 15px; }

/* Top Control Bar */
.top-control-bar { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; background: #ffffff; border-radius: 16px; padding: 15px 25px; box-shadow: 0 4px 20px rgba(0,0,0,0.03); margin-bottom: 20px; gap: 15px; }
.nav-arrows { display: flex; align-items: center; gap: 15px; background: #f8fafc; padding: 5px 15px; border-radius: 50px; border: 1px solid #e2e8f0; }
.nav-arrows a { color: #64748b; font-size: 1.1rem; padding: 5px; transition: 0.2s; }
.nav-arrows a:hover { color: #3b82f6; transform: scale(1.1); }
.nav-arrows .current-date { font-weight: 800; font-size: 1.2rem; color: #1e293b; min-width: 140px; text-align: center; }

/* View Toggles */
.view-toggles { display: flex; background: #f1f5f9; border-radius: 50px; padding: 4px; }
.view-toggles a { padding: 8px 24px; border-radius: 50px; font-weight: 700; color: #64748b; text-decoration: none; font-size: 0.95rem; transition: 0.3s; }
.view-toggles a.active { background: #ffffff; color: #3b82f6; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }

/* Quick Filters */
.quick-filters { display: flex; align-items: center; gap: 10px; background: #ffffff; padding: 12px 20px; border-radius: 12px; box-shadow: 0 2px 15px rgba(0,0,0,0.02); margin-bottom: 20px; flex-wrap: wrap; }
.filter-pill { display: inline-flex; align-items: center; padding: 6px 14px; border-radius: 50px; font-size: 0.85rem; font-weight: 600; cursor: pointer; transition: 0.2s; background: #f1f5f9; color: #475569; border: 1px solid transparent; user-select: none; }
.filter-chk-custom { display: none; }
.filter-chk-custom:checked + .filter-pill { box-shadow: inset 0 0 0 1px currentColor; filter: brightness(0.95); }
.filter-badge { width: 10px; height: 10px; border-radius: 50%; margin-left: 6px; }

/* Grid Systems */
.grid-container { background: #ffffff; border-radius: 20px; box-shadow: 0 5px 30px rgba(0,0,0,0.04); overflow: hidden; border: 1px solid #e2e8f0; }
.cal-grid-month, .cal-grid-week { display: grid; gap: 1px; background: #e2e8f0; }
.cal-grid-month { grid-template-columns: repeat(7, minmax(0, 1fr)); }
.cal-grid-week { grid-template-columns: repeat(7, minmax(0, 1fr)); }

.cal-header-day { background: #ffffff; text-align: center; font-size: 0.9rem; font-weight: 800; color: #475569; padding: 15px 0; border-bottom: 2px solid #f1f5f9; text-transform: uppercase; }
.cal-day { min-height: 130px; padding: 8px; position: relative; transition: background 0.2s; background: #ffffff; display: flex; flex-direction: column; }
.cal-day.week-body { min-height: 500px; } 
.cal-day:hover { background: #f8fafc; z-index: 10; }
.cal-empty { background: #fafafa; opacity: 0.6; }

/* Make weekend slightly different */
.bg-day-0 { background: #fdfdfd; } /* Sat */
.bg-day-6 { background: #fdfdfd; } /* Fri */

.day-header-row { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px; pointer-events: none; }
.cal-date-num { font-size: 0.9rem; font-weight: 700; color: #64748b; background: transparent; width: 26px; height: 26px; display: flex; align-items: center; justify-content: center; border-radius: 50%; transition: 0.3s; }
.cal-today { background: #f0fdf4 !important; }
.cal-today .cal-date-num { background: #16a34a; color: white; box-shadow: 0 4px 10px rgba(22, 163, 74, 0.3); transform: scale(1.1); font-weight: 800; }
.cal-past-day { opacity: 0.8; }
.cal-past-day .events-container { filter: grayscale(0.2); opacity: 0.9; }

.drag-over { background: #eef2ff !important; box-shadow: inset 0 0 0 2px #6366f1 !important; }

/* Timeline Day View */
.timeline-wrap { background: #fff; border-radius: 20px; padding: 20px; box-shadow: 0 5px 30px rgba(0,0,0,0.04); }
.timeline-hour { border-bottom: 1px solid #f1f5f9; min-height: 80px; display: flex; transition: auto; }
.timeline-hour:hover { background: #f8fafc; cursor: pointer; }
.timeline-label { width: 70px; font-weight: 700; color: #94a3b8; padding-top: 15px; font-size: 0.9rem; text-align: center; border-left: 2px solid #f1f5f9; }
.timeline-body { flex-grow: 1; padding: 10px; }

/* Event Cards */
.events-container { display: flex; flex-direction: column; gap: 5px; flex-grow: 1; }
.cal-event-card { 
    font-size: 0.75rem; font-weight: 700; padding: 6px 10px; border-radius: 6px; 
    border-right: 3px solid transparent; cursor: grab; transition: all 0.2s; 
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; box-shadow: 0 1px 3px rgba(0,0,0,0.05); margin: 0;
}
.cal-event-card:active { cursor: grabbing; opacity: 0.8; transform: scale(1.02); }
.cal-event-card:hover { transform: translateY(-1px); box-shadow: 0 4px 10px rgba(0,0,0,0.1); filter: brightness(0.95); }
.cal-event-card.archived { opacity: 0.4; text-decoration: line-through; filter: grayscale(1); }
.cal-event-card.is-block { border-style: dashed; opacity: 0.9; border-width: 2px; border-right-width: 3px; border-right-style: solid; }
.recurring-icon { font-size: 0.65rem; color: inherit; opacity: 0.6; margin-right: auto; }

/* Past Day Collapsed Events */
.past-events-badge {
    display: inline-flex; align-items: center; gap: 5px;
    background: #e2e8f0; color: #475569;
    font-size: 0.72rem; font-weight: 700;
    padding: 4px 10px; border-radius: 20px;
    cursor: pointer; border: none; width: 100%;
    justify-content: center; transition: all 0.2s;
    margin-top: 2px;
}
.past-events-badge:hover { background: #cbd5e1; color: #1e293b; transform: scale(1.02); }
.past-events-collapsed { display: none; flex-direction: column; gap: 5px; }
.past-events-collapsed.open { display: flex; }

/* Now Engine Ribbon */
.now-engine-ribbon { background: linear-gradient(90deg, #1e40af, #3b82f6); color: white; padding: 12px 20px; border-radius: 12px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3); }

/* Custom Toast overlay */
#customToast { position: fixed; bottom: 30px; left: 50%; transform: translateX(-50%) translateY(100px); z-index: 9999; background: #1e293b; color: white; padding: 12px 25px; border-radius: 50px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); opacity: 0; transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55); font-weight: 600; font-size: 0.9rem; }
#customToast.show { opacity: 1; transform: translateX(-50%) translateY(0); }

/* Responsive Grid Adjustments */
@media (max-width: 900px) {
    .cal-grid-month, .cal-grid-week { display: flex; flex-direction: column; gap: 10px; background: transparent; }
    .cal-header-day { display: none; }
    .cal-day { border-radius: 12px; border: 1px solid #e2e8f0; min-height: 80px; }
    .cal-empty { display: none; }
    .day-header-row { flex-direction: row-reverse; justify-content: flex-end; gap: 10px; align-items: center; }
    .cal-date-num { background: #f1f5f9; }
    .top-control-bar { flex-direction: column; align-items: stretch; }
    .nav-arrows { justify-content: center; }
    .view-toggles { justify-content: center; }
}
</style>

<div class="cal-wrapper">

    <!-- NOW ENGINE -->
    <?php if ($nowTask): ?>
    <div class="now-engine-ribbon">
        <div class="d-flex align-items-center gap-3">
            <div class="bg-white text-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                <i class="fa-solid fa-bolt fs-5"></i>
            </div>
            <div>
                <span class="d-block fs-7 opacity-75 mb-1" style="font-weight:600;">مهمتك الحالية</span>
                <h5 class="fw-bold m-0"><?= htmlspecialchars($nowTask->title) ?></h5>
            </div>
        </div>
        <div class="bg-white bg-opacity-25 px-3 py-1 rounded-pill fw-bold fs-6">
            <i class="fa-regular fa-clock me-1"></i> <?= date('H:i', strtotime($nowTask->start_time)) ?> - <?= date('H:i', strtotime($nowTask->end_time)) ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- TOP CONTROL BAR -->
    <div class="top-control-bar">
        <!-- Title & Add Btn -->
        <div class="d-flex align-items-center gap-3">
            <h2 class="h4 fw-bold m-0 text-dark">
                التقويم 
            </h2>
            <button class="btn btn-primary rounded-pill fw-bold px-4 shadow-sm" onclick="openEventModal('<?= $viewMode=='month' ? $todayDate : $targetDate ?>')">
                <i class="fa-solid fa-plus me-1"></i> جديد
            </button>
        </div>

        <!-- Date Navigation -->
        <div class="nav-arrows">
            <?php 
            $prevLink = $nextLink = '';
            if ($viewMode === 'day') {
                $prevDate = date('Y-m-d', strtotime($targetDate . ' -1 day'));
                $nextDate = date('Y-m-d', strtotime($targetDate . ' +1 day'));
                $prevLink = "?view=day&date={$prevDate}";
                $nextLink = "?view=day&date={$nextDate}";
                $currLabel = date('Y-m-d', strtotime($targetDate));
            } else if ($viewMode === 'week') {
                $prevDate = date('Y-m-d', strtotime($targetDate . ' -7 days'));
                $nextDate = date('Y-m-d', strtotime($targetDate . ' +7 days'));
                $prevLink = "?view=week&date={$prevDate}";
                $nextLink = "?view=week&date={$nextDate}";
                $currLabel = "أسبوع: " . date('M d', strtotime($targetDate));
            } else {
                $prevMonth = $month - 1; $nextMonth = $month + 1;
                $pYr = $year; $nYr = $year;
                if($prevMonth < 1) { $prevMonth=12; $pYr--; }
                if($nextMonth > 12) { $nextMonth=1; $nYr++; }
                $prevLink = "?view=month&year={$pYr}&month={$prevMonth}";
                $nextLink = "?view=month&year={$nYr}&month={$nextMonth}";
                $currLabel = $monthsArabic[$month] . ' ' . $year;
            }
            ?>
            <a href="<?= BASE_URL ?>/calendar/index<?= $nextLink ?>"><i class="fa-solid fa-chevron-right"></i></a>
            <div class="current-date"><?= $currLabel ?></div>
            <a href="<?= BASE_URL ?>/calendar/index<?= $prevLink ?>"><i class="fa-solid fa-chevron-left"></i></a>
        </div>

        <!-- View Toggles -->
        <div class="view-toggles">
            <a href="?view=month&date=<?= $targetDate ?>" class="<?= $viewMode=='month'?'active':'' ?>">شهر</a>
            <a href="?view=week&date=<?= $targetDate ?>" class="<?= $viewMode=='week'?'active':'' ?>">أسبوع</a>
            <a href="?view=day&date=<?= $targetDate ?>" class="<?= $viewMode=='day'?'active':'' ?>">يوم</a>
        </div>
    </div>

    <!-- QUICK FILTERS -->
    <div class="quick-filters">
        <span class="text-muted fw-bold fs-7 me-2"><i class="fa-solid fa-filter me-1"></i> عرض:</span>
        
        <label>
            <input type="checkbox" class="filter-chk-custom filter-chk" value="type-task" checked>
            <span class="filter-pill" style="color:#16a34a; background:#f0fdf4;"><i class="fa-solid fa-list-check me-2"></i> المهام المجدولة</span>
        </label>
        
        <label>
            <input type="checkbox" class="filter-chk-custom filter-chk" value="type-block" checked>
            <span class="filter-pill" style="color:#ca8a04; background:#fefce8;"><i class="fa-solid fa-stopwatch me-2"></i> الكتل الزمنية</span>
        </label>

        <div style="width:2px; height:20px; background:#e2e8f0; margin: 0 10px;"></div>
        
        <?php foreach($catMap as $sysKey => $catData): ?>
            <label>
                <input type="checkbox" class="filter-chk-custom filter-chk" value="cat-<?= $sysKey ?>" checked>
                <span class="filter-pill" style="color:<?= $catData['text'] ?>; background:<?= $catData['bg'] ?>;">
                    <?= htmlspecialchars($catData['name']) ?>
                </span>
            </label>
        <?php endforeach; ?>

        <button class="btn btn-sm btn-light border ms-auto rounded-circle" data-bs-toggle="modal" data-bs-target="#categoryModal" title="إدارة التصنيفات">
            <i class="fa-solid fa-gear text-secondary"></i>
        </button>
    </div>

    <!-- MILESTONES -->
    <?php if (!empty($milestones)): ?>
    <div class="d-flex flex-wrap gap-2 mb-3">
        <?php foreach($milestones as $gm): ?>
            <span class="badge bg-white text-dark shadow-sm border p-2 px-3 rounded-pill fs-7 fw-bold <?= $gm->is_primary?'border-warning':'' ?>">
                <?= $gm->is_primary ? '<i class="fa-solid fa-star text-warning me-1"></i>' : '<i class="fa-solid fa-bullseye text-danger me-1"></i>' ?>
                <?= htmlspecialchars($gm->title) ?>
            </span>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <?= display_flash_message('calendar') ?>

    <?php 
    /**
     * RENDER COMPONENT: EVENT CARD
     */
    function renderEventCard($ev, $catMap, $catFallback) {
        $isTask = isset($ev->is_task) && $ev->is_task;
        $isOverdue = isset($ev->is_overdue) && $ev->is_overdue;
        $isBlock = isset($ev->event_type) && $ev->event_type === 'block';

        $catStr = $ev->category ?? 'other';
        $ui = $catMap[$catStr] ?? $catFallback;
        $isArchived = ($ev->status === 'archived');
        $isRecur = (!$isTask && $ev->recurrence_type !== 'none' && !empty($ev->recurrence_type));
        $recurIcon = $isRecur ? '<i class="fa-solid fa-rotate recurring-icon ms-2" title="تكرار"></i>' : '';
        $timeStr = (!$isTask && $ev->start_time) ? ' ' . date('H:i', strtotime($ev->start_time)) : '';

        $filterClasses = $isTask ? 'filter-type-task' : ($isBlock ? "filter-type-block filter-cat-{$catStr}" : "filter-cat-{$catStr}");
        
        $jsonEv = htmlspecialchars(json_encode([
            'id' => $ev->id, 'title' => $ev->title, 'category' => $catStr, 
            'date' => $ev->event_date, 'start' => $ev->start_time, 'end' => $ev->end_time,
            'color' => $ev->color_hex, 'desc' => $ev->description,
            'rec_type' => $ev->recurrence_type ?? 'none', 'rec_end' => $ev->recurrence_end_date ?? null,
            'is_task' => $isTask, 'event_type' => $ev->event_type ?? 'event'
        ]));

        if ($isTask) {
            $taskColor = $isOverdue ? '#dc2626' : '#16a34a';
            $taskBg = $isOverdue ? '#fef2f2' : '#f0fdf4';
            $icon = $ev->status === 'done' ? '<i class="fa-solid fa-check-circle flex-shrink-0 ms-2" style="color:#16a34a"></i>' : '<i class="fa-regular fa-circle flex-shrink-0 ms-2" style="color: '.$taskColor.'"></i>';
            $strike = $ev->status === 'done' ? 'text-decoration-line-through opacity-75' : '';
            return "
                <div class='cal-event-card task-card {$filterClasses} " . ($isArchived ? 'archived' : '') . "' 
                     draggable='false'
                     style='background-color: {$taskBg}; color: {$taskColor}; border-right-color: {$taskColor}; border-right-style: solid;' 
                     title='" . htmlspecialchars($ev->title) . "'
                     onclick='showToast(\"مهام To-Do يتم تعديلها من شاشتها الخاصة\", \"warning\")'>
                    {$icon}
                    <span class='text-truncate flex-grow-1 {$strike}'>" . htmlspecialchars($ev->title) . "</span>
                </div>
            ";
        }

        $blockClass = $isBlock ? 'is-block' : '';
        $borderCol = $ev->color_hex ?: $ui['border'];
        $iconBase = $isBlock ? '<i class="fa-solid fa-layer-group me-1 opacity-50"></i>' : '';
        
        return "
            <div class='cal-event-card {$catStr} {$blockClass} {$filterClasses} " . ($isArchived ? 'archived' : '') . "' 
                 draggable='true' ondragstart='dragStart(event)'
                 style='background-color: {$ui['bg']}; color: {$ui['text']}; border-right-color: {$borderCol};' 
                 title='" . htmlspecialchars($ev->title) . "$timeStr'
                 data-id='{$ev->id}' data-json='{$jsonEv}'
                 onclick='editEventModal(this, event)'>
                 {$iconBase}
                <span class='text-truncate flex-grow-1'>" . htmlspecialchars($ev->title) . "</span>
                <span class='opacity-75 ms-1' style='font-size:0.6rem;'>{$timeStr}</span>
                {$recurIcon}
            </div>
        ";
    }
    
    function detectOverload($eventsArr) {
        if (count($eventsArr) > 6) return '<span class="badge bg-danger rounded-pill shadow-sm" title="يوم مزدحم!"><i class="fa-solid fa-fire text-white"></i></span>';
        return '';
    }

    // MAIN RENDER AREA
    if ($viewMode === 'month') {
        $firstDay = mktime(0, 0, 0, $month, 1, $year);
        $daysInMonth = date('t', $firstDay);
        $startDayOfWeek = date('w', $firstDay); 
        $blankDays = ($startDayOfWeek + 1) % 7; 
        ?>
        <div class="grid-container">
            <div class="cal-grid-month d-none d-md-grid">
                <?php foreach($daysHeader as $idx => $dh): ?>
                    <div class="cal-header-day"><?= $dh ?></div>
                <?php endforeach; ?>
            </div>
            <div class="cal-grid-month">
                <?php for($b = 0; $b < $blankDays; $b++): ?>
                    <div class="cal-day cal-empty d-none d-md-block"></div>
                <?php endfor; ?>
                
                <?php for($d = 1; $d <= $daysInMonth; $d++): 
                    $currentDate = sprintf("%04d-%02d-%02d", $year, $month, $d);
                    $isToday = ($currentDate === $todayDate);
                    $isPast = ($currentDate < $todayDate);
                    $dayEvents = $eventsByDate[$currentDate] ?? [];
                    $dayIndex = ($blankDays + $d - 1) % 7;
                    $evCount = count($dayEvents);
                ?>
                    <div class="cal-day bg-day-<?= $dayIndex ?> <?= $isToday ? 'cal-today' : '' ?> <?= $isPast ? 'cal-past-day' : '' ?>"  
                         data-date="<?= $currentDate ?>"
                         ondragover="allowDrop(event)" ondrop="handleDrop(event)" ondragenter="dragEnter(event)" ondragleave="dragLeave(event)"
                         onclick="if(event.target === this || event.target.classList.contains('events-container')) openEventModal('<?= $currentDate ?>')">
                        <div class="day-header-row">
                            <span class="cal-date-num"><?= $d ?> <span class="d-md-none ms-2 fs-7"><?= date('D', strtotime($currentDate)) ?></span></span>
                            <?= detectOverload($dayEvents) ?>
                        </div>
                        <div class="events-container">
                            <?php if ($isPast && $evCount > 0): ?>
                                <!-- Collapsed badge for past days -->
                                <button class="past-events-badge" onclick="togglePastEvents(this, event)" type="button">
                                    <i class="fa-solid fa-clock-rotate-left" style="font-size:0.65rem;"></i>
                                    <?= $evCount ?> <?= $evCount === 1 ? 'حدث' : 'أحداث' ?>
                                </button>
                                <div class="past-events-collapsed">
                                    <?php foreach($dayEvents as $ev) echo renderEventCard($ev, $catMap, $catFallback); ?>
                                </div>
                            <?php elseif (!$isPast): ?>
                                <?php foreach($dayEvents as $ev) echo renderEventCard($ev, $catMap, $catFallback); ?>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endfor; ?>
                
                <?php 
                    $totalCells = $blankDays + $daysInMonth;
                    $remaining = 7 - ($totalCells % 7);
                    if ($remaining < 7): for($b = 0; $b < $remaining; $b++): 
                ?>
                   <div class="cal-day cal-empty d-none d-md-block"></div>
                <?php endfor; endif; ?>
            </div>
        </div>
        <?php
    } 
    else if ($viewMode === 'week') {
        $dateObj = new \DateTime($targetDate);
        $dayOfWeek = $dateObj->format('w');
        $offset = ($dayOfWeek == 6) ? 0 : ($dayOfWeek + 1);
        $dateObj->modify("-$offset days");
        
        $weekDates = [];
        for($i=0; $i<7; $i++) {
            $weekDates[] = clone $dateObj;
            $dateObj->modify("+1 day");
        }
        ?>
        <div class="grid-container">
            <div class="cal-grid-week d-none d-md-grid">
                <?php foreach($weekDates as $idx => $wdir): 
                    $cDate = $wdir->format('Y-m-d');
                    $isToday = ($cDate === $todayDate);
                ?>
                    <div class="cal-header-day <?= $isToday ? 'text-primary' : '' ?>">
                        <?= $daysHeader[$idx] ?> <br> 
                        <span class="fs-4 d-block mt-1"><?= $wdir->format('d') ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="cal-grid-week">
                <?php foreach($weekDates as $idx => $wdir): 
                    $cDate = $wdir->format('Y-m-d');
                    $isToday = ($cDate === $todayDate);
                    $isPast = ($cDate < $todayDate);
                    $dayEvents = $eventsByDate[$cDate] ?? [];
                ?>
                    <div class="cal-day week-body <?= $isToday ? 'cal-today' : '' ?> <?= $isPast ? 'cal-past-day' : '' ?>"  
                         data-date="<?= $cDate ?>"
                         ondragover="allowDrop(event)" ondrop="handleDrop(event)" ondragenter="dragEnter(event)" ondragleave="dragLeave(event)"
                         onclick="if(event.target === this || event.target.classList.contains('events-container')) openEventModal('<?= $cDate ?>')">
                        <div class="day-header-row d-md-none">
                            <span class="cal-date-num"><?= $wdir->format('d') ?> <span class="ms-1"><?= $daysHeader[$idx] ?></span></span>
                            <?= detectOverload($dayEvents) ?>
                        </div>
                        <div class="d-none d-md-flex justify-content-end mb-2">
                             <?= detectOverload($dayEvents) ?>
                        </div>
                        <div class="events-container">
                            <?php foreach($dayEvents as $ev) echo renderEventCard($ev, $catMap, $catFallback); ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php
    }
    else if ($viewMode === 'day') {
        $isPast = ($targetDate < $todayDate);
        $hours = [];
        for($i=0; $i<24; $i++) $hours[$i] = [];
        
        $allDayEvents = [];
        foreach($events as $ev) {
            if (empty($ev->start_time)) {
                $allDayEvents[] = $ev;
            } else {
                $h = (int)date('H', strtotime($ev->start_time));
                $hours[$h][] = $ev;
            }
        }
        ?>
        <div class="timeline-wrap <?= $isPast ? 'cal-past-day' : '' ?>">
            <?php if(!empty($allDayEvents)): ?>
            <div class="bg-light rounded p-3 mb-4 border">
                <span class="fw-bold text-muted mb-2 d-block"><i class="fa-solid fa-thumbtack me-1"></i> طوال اليوم</span>
                <div class="d-flex flex-wrap gap-2">
                    <?php foreach($allDayEvents as $ev) echo renderEventCard($ev, $catMap, $catFallback); ?>
                </div>
            </div>
            <?php endif; ?>

            <?php for($i=0; $i<24; $i++): ?>
               <div class="timeline-hour" data-date="<?= $targetDate ?>" data-hour="<?= $i ?>"
                    ondragover="allowDrop(event)" ondrop="handleDrop(event)" ondragenter="dragEnter(event)" ondragleave="dragLeave(event)"
                    onclick="if(event.target === this || event.target.classList.contains('timeline-body')) openEventModal('<?= $targetDate ?>', '<?= sprintf('%02d:00', $i) ?>')">
                   <div class="timeline-label"><?= sprintf('%02d:00', $i) ?></div>
                   <div class="timeline-body">
                       <div class="d-flex flex-wrap gap-2">
                           <?php foreach($hours[$i] as $ev) echo renderEventCard($ev, $catMap, $catFallback); ?>
                       </div>
                   </div>
               </div>
            <?php endfor; ?>
        </div>
        <?php
    }
    ?>
</div>

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

<!-- Add / Edit Event Modal -->
<div class="modal fade" id="eventModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content border-0 shadow-lg" style="border-radius: 20px; overflow:hidden;">
      <div class="modal-header bg-primary text-white border-0 py-3">
        <h5 class="modal-title fw-bold"><i class="fa-regular fa-calendar-plus me-2"></i> <span id="modalTitleText">تسجيل جديد</span></h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form action="<?= BASE_URL ?>/calendar/store" method="POST">
      <div class="modal-body p-4 bg-light">
          <?= csrf_field() ?>
          <input type="hidden" name="event_id" id="modalEventId">

          <div class="d-flex justify-content-center mb-4">
              <div class="btn-group shadow-sm bg-white rounded-pill p-1 border">
                  <input type="radio" class="btn-check" name="event_type" id="typeEvent" value="event" checked>
                  <label class="btn btn-outline-primary border-0 rounded-pill px-4 fw-bold" for="typeEvent"><i class="fa-solid fa-calendar-check me-1"></i> حدث</label>

                  <input type="radio" class="btn-check" name="event_type" id="typeBlock" value="block">
                  <label class="btn btn-outline-warning border-0 rounded-pill px-4 fw-bold" for="typeBlock"><i class="fa-solid fa-stopwatch me-1"></i> كتلة زمنية</label>
              </div>
          </div>
          
          <div class="row g-3 mb-3">
              <div class="col-md-8">
                  <div class="form-floating">
                      <input type="text" name="title" class="form-control fw-bold border-0 shadow-sm rounded-3" placeholder="العنوان" required>
                      <label>العنوان</label>
                  </div>
              </div>
              <div class="col-md-4">
                  <div class="form-floating">
                      <input type="date" name="event_date" id="modalDate" class="form-control fw-bold border-0 shadow-sm rounded-3 text-primary" required>
                      <label>التاريخ</label>
                  </div>
              </div>
          </div>
          
          <div class="row g-3 mb-3">
              <div class="col-md-4">
                  <div class="form-floating">
                      <select name="category" class="form-select border-0 shadow-sm rounded-3" id="modalCategory" required>
                          <?php foreach($catMap as $sysKey => $catData): ?>
                              <option value="<?= $sysKey ?>" data-color="<?= $catData['border'] ?>"><?= htmlspecialchars($catData['name']) ?></option>
                          <?php endforeach; ?>
                      </select>
                      <label>التصنيف</label>
                  </div>
              </div>
              <div class="col-md-4">
                  <div class="form-floating">
                      <input type="time" name="start_time" class="form-control border-0 shadow-sm rounded-3">
                      <label>من (اختياري)</label>
                  </div>
              </div>
              <div class="col-md-4">
                  <div class="form-floating">
                      <input type="time" name="end_time" class="form-control border-0 shadow-sm rounded-3">
                      <label>إلى (اختياري)</label>
                  </div>
              </div>
          </div>
          
          <div class="row g-3">
              <div class="col-md-12">
                  <div class="form-floating">
                      <textarea name="description" class="form-control border-0 shadow-sm rounded-3" placeholder="التفاصيل والملاحظات" style="height: 80px"></textarea>
                      <label>الملاحظات</label>
                  </div>
              </div>
          </div>

          <div class="row g-3 mt-2" id="recurringSection">
              <div class="col-md-6">
                  <div class="form-floating">
                      <select name="recurrence_type" class="form-select border-0 shadow-sm rounded-3" id="modalRecurrence" onchange="toggleRecurrenceEnd()">
                          <option value="none">بدون تكرار</option>
                          <option value="daily">يومياً</option>
                          <option value="weekly">أسبوعياً</option>
                          <option value="monthly">شهرياً</option>
                      </select>
                      <label><i class="fa-solid fa-redo me-1 text-muted"></i> التكرار التلقائي</label>
                  </div>
              </div>
              <div class="col-md-6 d-none" id="recurrenceEndDateDiv">
                  <div class="form-floating">
                      <input type="date" name="recurrence_end_date" class="form-control border-0 shadow-sm rounded-3 text-danger" id="modalRecurrenceEnd">
                      <label>تاريخ إيقاف التكرار</label>
                  </div>
              </div>
          </div>
          
          <div class="mt-3 form-check form-switch p-3 bg-white shadow-sm rounded-3 d-flex align-items-center">
              <input class="form-check-input ms-0 me-3" type="checkbox" name="create_task" id="createTaskCheck" value="1" style="width: 40px; height: 20px;">
              <label class="form-check-label fw-bold" for="createTaskCheck">تحويل لـ مهمة To-Do في نفس الوقت</label>
          </div>
      </div>
      <div class="modal-footer bg-white border-0 py-3 d-flex justify-content-between">
        <a href="#" id="btnDeleteEvent" class="btn btn-light text-danger d-none rounded-pill px-4" onclick="if(!confirm('تأكيد مسح؟')) return false;">
            <i class="fa-regular fa-trash-can me-1"></i> مسح
        </a>
        <button type="submit" class="btn btn-primary px-5 py-2 rounded-pill fw-bold shadow-sm" id="btnSaveEvent">حفظ</button>
      </div>
      </form>
    </div>
  </div>
</div>

<!-- Manage Categories Modal -->
<div class="modal fade" id="categoryModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 shadow-lg" style="border-radius: 20px;">
      <div class="modal-header bg-light border-0">
        <h5 class="modal-title fw-bold"><i class="fa-solid fa-tags me-2 text-secondary"></i> إدارة التصنيفات</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-4 bg-white">
          <ul class="list-group list-group-flush mb-4">
              <?php foreach($catMap as $sysKey => $catData): ?>
                <li class="list-group-item d-flex justify-content-between align-items-center px-0 border-light">
                    <span class="rounded-pill px-3 py-1 fw-bold fs-7" style="background:<?= $catData['bg'] ?>; color:<?= $catData['text'] ?>;">
                        <?= htmlspecialchars($catData['name']) ?>
                    </span>
                    <?php if(!in_array($sysKey, ['meetings','personal','health','finance','other'])): ?>
                        <a href="<?= BASE_URL ?>/calendar/deleteCategory/<?= $catData['id'] ?>" class="btn btn-sm btn-outline-danger rounded-circle p-1" style="width:28px;height:28px;" onclick="if(!confirm('حذف؟')) return false;"><i class="fa-regular fa-trash-can fa-xs"></i></a>
                    <?php endif; ?>
                </li>
              <?php endforeach; ?>
          </ul>
          
          <form action="<?= BASE_URL ?>/calendar/addCategory" method="POST" class="bg-light p-3 rounded-3 border">
              <h6 class="fw-bold mb-3 fs-7 text-muted">إضافة تصنيف جديد</h6>
              <?= csrf_field() ?>
              <div class="input-group">
                 <input type="text" name="name" class="form-control bg-white border-0 shadow-sm rounded-start-pill ps-3" required placeholder="اسم التصنيف...">
                 <button type="submit" class="btn btn-primary rounded-end-pill px-3 shadow-sm"><i class="fa-solid fa-plus"></i></button>
              </div>
          </form>
      </div>
    </div>
  </div>
</div>

<div id="customToast"></div>

<script>
const todayDate = '<?= date('Y-m-d') ?>';

function showToast(msg, type="info") {
    let t = document.getElementById('customToast');
    t.innerText = msg;
    t.style.background = type === 'danger' ? '#ef4444' : (type === 'warning' ? '#f59e0b' : '#1e293b');
    t.classList.add('show');
    setTimeout(() => t.classList.remove('show'), 3000);
}

function toggleRecurrenceEnd() {
    let type = document.getElementById('modalRecurrence').value;
    let div = document.getElementById('recurrenceEndDateDiv');
    if (type === 'none') {
        div.classList.add('d-none');
        document.getElementById('modalRecurrenceEnd').value = '';
    } else {
        div.classList.remove('d-none');
    }
}

document.querySelectorAll('input[name="event_type"]').forEach(r => {
    r.addEventListener('change', function() {
        let isBlock = (this.value === 'block');
        let sec = document.getElementById('recurringSection');
        sec.style.opacity = isBlock ? 0.3 : 1;
        sec.style.pointerEvents = isBlock ? 'none' : 'auto';
        if (isBlock) {
            document.getElementById('modalRecurrence').value = 'none';
            toggleRecurrenceEnd();
        }
    });
});

function openEventModal(dateStr, timeStr = '') {
    document.getElementById('modalDate').value = dateStr;
    document.getElementById('modalEventId').value = '';
    document.querySelector('input[name="title"]').value = '';
    document.querySelector('input[name="start_time"]').value = timeStr;
    document.querySelector('input[name="end_time"]').value = '';
    document.querySelector('textarea[name="description"]').value = '';
    document.querySelector('select[name="recurrence_type"]').value = 'none';
    document.querySelector('input[name="recurrence_end_date"]').value = '';

    document.getElementById('typeEvent').checked = true;
    document.getElementById('recurringSection').style.opacity = 1;
    document.getElementById('recurringSection').style.pointerEvents = 'auto';
    toggleRecurrenceEnd();
    
    document.getElementById('modalTitleText').innerText = 'تسجيل جديد';
    document.getElementById('btnSaveEvent').innerText = 'إضافة';
    document.getElementById('btnDeleteEvent').classList.add('d-none');
    
    new bootstrap.Modal(document.getElementById('eventModal')).show();
}

function editEventModal(element, event) {
    event.stopPropagation();
    let evData = JSON.parse(element.getAttribute('data-json'));
    
    document.getElementById('modalDate').value = evData.date;
    document.getElementById('modalEventId').value = evData.id;
    document.querySelector('input[name="title"]').value = evData.title;
    document.querySelector('input[name="start_time"]').value = evData.start;
    document.querySelector('input[name="end_time"]').value = evData.end;
    document.querySelector('textarea[name="description"]').value = evData.desc;
    
    let catSelect = document.querySelector('select[name="category"]');
    if (evData.category) catSelect.value = evData.category;
    
    document.querySelector('select[name="recurrence_type"]').value = evData.rec_type || 'none';
    document.querySelector('input[name="recurrence_end_date"]').value = evData.rec_end;
    
    if (evData.event_type === 'block') {
        document.getElementById('typeBlock').checked = true;
        document.getElementById('recurringSection').style.opacity = 0.3;
        document.getElementById('recurringSection').style.pointerEvents = 'none';
    } else {
        document.getElementById('typeEvent').checked = true;
        document.getElementById('recurringSection').style.opacity = 1;
        document.getElementById('recurringSection').style.pointerEvents = 'auto';
    }
    toggleRecurrenceEnd();
    
    document.getElementById('modalTitleText').innerText = 'تعديل السجل';
    document.getElementById('btnSaveEvent').innerText = 'حفظ التغييرات';

    let btnDelete = document.getElementById('btnDeleteEvent');
    btnDelete.href = '<?= BASE_URL ?>/calendar/archive/' + evData.id;
    btnDelete.classList.remove('d-none');
    
    new bootstrap.Modal(document.getElementById('eventModal')).show();
}

// Drag & Drop
function dragStart(ev) {
    let evId = ev.target.getAttribute('data-id');
    ev.dataTransfer.setData("text/plain", evId);
    ev.target.style.opacity = '0.4';
}
function allowDrop(ev) { ev.preventDefault(); }
function dragEnter(ev) { ev.preventDefault(); let target = ev.target.closest('.cal-day'); if (target) target.classList.add('drag-over'); }
function dragLeave(ev) { let target = ev.target.closest('.cal-day'); if (target) target.classList.remove('drag-over'); }

function togglePastEvents(btn, ev) {
    ev.stopPropagation(); // don't trigger the day's openEventModal
    const collapsed = btn.nextElementSibling;
    const isOpen = collapsed.classList.contains('open');
    if (isOpen) {
        collapsed.classList.remove('open');
        btn.innerHTML = '<i class="fa-solid fa-clock-rotate-left" style="font-size:0.65rem;"></i> ' + btn.dataset.count + ' ' + btn.dataset.label;
    } else {
        collapsed.classList.add('open');
        btn.innerHTML = '<i class="fa-solid fa-chevron-up" style="font-size:0.65rem;"></i> إخفاء';
    }
}

// Store count & label on badge init
document.querySelectorAll('.past-events-badge').forEach(btn => {
    const collapsed = btn.nextElementSibling;
    const count = collapsed ? collapsed.querySelectorAll('.cal-event-card').length : 0;
    btn.dataset.count = count;
    btn.dataset.label = count === 1 ? 'حدث' : 'أحداث';
});

function handleDrop(ev) {
    ev.preventDefault();
    let target = ev.target.closest('.cal-day');
    if (target) target.classList.remove('drag-over');
    
    let eventId = ev.dataTransfer.getData("text/plain");
    if(!eventId || !target) return;
    
    let newDate = target.getAttribute('data-date');
    if(!newDate) return;
    
    let csrfToken = document.querySelector('input[name="csrf_token"]').value;

    fetch('<?= BASE_URL ?>/calendar/reschedule', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ event_id: eventId, new_date: newDate, csrf_token: csrfToken })
    })
    .then(res => res.json())
    .then(data => {
        if(data.success) {
            window.location.reload(); 
        } else {
            showToast(data.message || 'خطأ', 'danger');
        }
    })
}

// Filters
function buildFilters() {
    let state = {};
    document.querySelectorAll('.filter-chk').forEach(c => { state[c.value] = c.checked; });
    applyFilters(state);
}

function applyFilters(state) {
    document.querySelectorAll('.cal-event-card').forEach(card => {
        card.style.display = 'none';
        let isTask = card.classList.contains('filter-type-task');
        let isBlock = card.classList.contains('filter-type-block');
        let isGeneralEvent = (!isTask && !isBlock);
        
        let catClass = Array.from(card.classList).find(c => c.startsWith('filter-cat-'));
        let catActive = true;
        if (catClass && state[catClass.replace('filter-cat-', 'cat-')] === false) {
            catActive = false;
        }

        if (isTask && state['type-task']) card.style.display = 'flex';
        else if (isBlock && state['type-block'] && catActive) card.style.display = 'flex';
        else if (isGeneralEvent && catActive) card.style.display = 'flex';
    });
}

document.querySelectorAll('.filter-chk').forEach(c => {
    c.addEventListener('change', buildFilters);
});

// Always start with all filters ON — no localStorage persistence to avoid stale hidden state
localStorage.removeItem('cal_filters');
let initState = {};
document.querySelectorAll('.filter-chk').forEach(c => {
    c.checked = true;
    initState[c.value] = true;
});
applyFilters(initState);
</script>
