<?php
/**
 * Couple Portal — Wedding Schedule: All Items (RC-018 / UX007)
 * Location: app/views/timeline/tasks.php
 *
 * Chronological agenda view — feels like Google Calendar Agenda, not a task table.
 */

// Group tasks by date sections
$today    = date('Y-m-d');
$tomorrow = date('Y-m-d', strtotime('+1 day'));

$grouped = [
    'overdue'   => [],
    'today'     => [],
    'tomorrow'  => [],
    'upcoming'  => [],
    'completed' => [],
    'cancelled' => [],
];

foreach ($tasks as $t) {
    $status  = $t['status'] ?? 'Not Started';
    $dueDate = $t['due_date'] ?? null;
    $dueTs   = $dueDate ? strtotime($dueDate) : null;
    $todayTs = strtotime($today);

    if ($status === 'Completed') {
        $grouped['completed'][] = $t;
    } elseif ($status === 'Cancelled') {
        $grouped['cancelled'][] = $t;
    } elseif ($dueTs && $dueTs < $todayTs) {
        $grouped['overdue'][] = $t;
    } elseif ($dueDate === $today) {
        $grouped['today'][] = $t;
    } elseif ($dueDate === $tomorrow) {
        $grouped['tomorrow'][] = $t;
    } else {
        $grouped['upcoming'][] = $t;
    }
}

// Sort upcoming by due_date ascending
usort($grouped['upcoming'], fn($a, $b) => strcmp($a['due_date'] ?? '9999', $b['due_date'] ?? '9999'));
usort($grouped['overdue'],  fn($a, $b) => strcmp($a['due_date'] ?? '9999', $b['due_date'] ?? '9999'));

$statusDotMap = [
    'Not Started' => 'bg-slate-300',
    'In Progress' => 'bg-sky-400',
    'Waiting'     => 'bg-amber-400',
    'Completed'   => 'bg-emerald-400',
    'Cancelled'   => 'bg-slate-200',
];
?>

<div class="space-y-8">

    <!-- ── Page Header ──────────────────────────────────────────────────── -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <div class="page-breadcrumb">
                <a href="<?= url('/app/couple/timeline') ?>">Wedding Schedule</a>
                <span class="sep">/</span>
                <span>All Items</span>
            </div>
            <h1 class="text-2xl font-black tracking-tight text-slate-800 flex items-center gap-2.5">
                <span class="page-header-icon">
                    <i class="fa-solid fa-list-check"></i>
                </span>
                All Schedule Items
            </h1>
            <p class="text-sm text-slate-500 mt-1.5 ml-0.5">
                All your wedding events, meetings, and reminders — in one place.
            </p>
        </div>
        <div class="flex items-center gap-2.5">
            <a href="<?= url('/app/couple/timeline') ?>"
               class="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-slate-600 text-xs font-semibold shadow-sm transition-all" onmouseover="this.style.color='#232323'" onmouseout="this.style.color=''">
                <i class="fa-solid fa-calendar-heart text-slate-400 text-[10px]"></i> Dashboard
            </a>
            <a href="<?= url('/app/couple/timeline/tasks/create') ?>"
               class="btn btn-primary btn-md">
                <i class="fa-solid fa-plus text-[10px]"></i> Add to Schedule
            </a>
        </div>
    </div>

    <!-- ── Flash Alerts ─────────────────────────────────────────────────── -->
    <?php if (!empty($success)): ?>
        <div class="p-4 bg-emerald-50 border border-emerald-150 text-emerald-800 rounded-2xl flex items-center gap-3 text-sm shadow-sm">
            <i class="fa-solid fa-circle-check text-emerald-500 text-base flex-shrink-0"></i>
            <div class="font-semibold"><?= escape_html($success) ?></div>
        </div>
    <?php endif; ?>
    <?php if (!empty($error)): ?>
        <div class="p-4 bg-rose-50 border border-rose-150 text-rose-800 rounded-2xl flex items-center gap-3 text-sm shadow-sm">
            <i class="fa-solid fa-circle-xmark text-rose-500 text-base flex-shrink-0"></i>
            <div class="font-semibold"><?= escape_html($error) ?></div>
        </div>
    <?php endif; ?>

    <!-- ── Filter Bar ───────────────────────────────────────────────────── -->
    <div class="bg-white rounded-2xl border border-slate-100 shadow-sm px-5 py-4">
        <form method="GET" action="<?= url('/app/couple/timeline/tasks') ?>" class="flex flex-wrap gap-3 items-end">

            <!-- Search -->
            <div class="flex-1 min-w-[160px] space-y-1">
                <label for="search" class="text-[10px] font-bold uppercase tracking-wider text-slate-400 block">Search</label>
                <div class="relative">
                    <span class="absolute left-3 top-2.5 text-slate-400 text-[11px]"><i class="fa-solid fa-magnifying-glass"></i></span>
                    <input type="text" id="search" name="search"
                           value="<?= escape_html($filters['search'] ?? '') ?>"
                           placeholder="Search…"
                           class="form-input pl-8 text-xs w-full">
                </div>
            </div>

            <!-- Category -->
            <div class="min-w-[140px] space-y-1">
                <label for="category" class="text-[10px] font-bold uppercase tracking-wider text-slate-400 block">Type</label>
                <select id="category" name="category" class="form-select text-xs w-full">
                    <option value="">All types</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?= $cat ?>" <?= (isset($filters['category']) && $filters['category'] === $cat) ? 'selected' : '' ?>>
                            <?= escape_html($cat) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Status -->
            <div class="min-w-[140px] space-y-1">
                <label for="status" class="text-[10px] font-bold uppercase tracking-wider text-slate-400 block">Status</label>
                <select id="status" name="status" class="form-select text-xs w-full">
                    <option value="">All statuses</option>
                    <option value="Not Started" <?= (isset($filters['status']) && $filters['status'] === 'Not Started') ? 'selected' : '' ?>>Not Started</option>
                    <option value="In Progress" <?= (isset($filters['status']) && $filters['status'] === 'In Progress') ? 'selected' : '' ?>>In Progress</option>
                    <option value="Waiting"     <?= (isset($filters['status']) && $filters['status'] === 'Waiting')     ? 'selected' : '' ?>>Waiting</option>
                    <option value="Completed"   <?= (isset($filters['status']) && $filters['status'] === 'Completed')   ? 'selected' : '' ?>>Completed</option>
                    <option value="Cancelled"   <?= (isset($filters['status']) && $filters['status'] === 'Cancelled')   ? 'selected' : '' ?>>Cancelled</option>
                </select>
            </div>

            <!-- Phase (kept for filter compatibility) -->
            <?php if (count($phases) > 1): ?>
            <div class="min-w-[140px] space-y-1">
                <label for="phase_id" class="text-[10px] font-bold uppercase tracking-wider text-slate-400 block">Period</label>
                <select id="phase_id" name="phase_id" class="form-select text-xs w-full">
                    <option value="">All periods</option>
                    <?php foreach ($phases as $ph): ?>
                        <option value="<?= $ph['id'] ?>" <?= (isset($filters['phase_id']) && (int)$filters['phase_id'] === (int)$ph['id']) ? 'selected' : '' ?>>
                            <?= escape_html($ph['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php else: ?>
                <input type="hidden" name="phase_id" value="">
            <?php endif; ?>

            <!-- Actions -->
            <div class="flex gap-2">
                <button type="submit" class="btn btn-primary btn-md flex items-center gap-1.5">
                    <i class="fa-solid fa-filter text-[10px]"></i> Filter
                </button>
                <a href="<?= url('/app/couple/timeline/tasks') ?>" class="btn btn-secondary btn-md">
                    Reset
                </a>
            </div>

        </form>
    </div>

    <!-- ── Result count ─────────────────────────────────────────────────── -->
    <?php if ($total_tasks > 0): ?>
        <div class="flex items-center justify-between">
            <span class="text-xs text-slate-400 font-medium"><?= $total_tasks ?> item<?= $total_tasks !== 1 ? 's' : '' ?> found</span>
        </div>
    <?php endif; ?>

    <!-- ── Empty State (no tasks at all) ────────────────────────────────── -->
    <?php if (empty($tasks)): ?>
        <div class="empty-state-elegant">
            <div class="empty-state-icon">
                <i class="fa-regular fa-calendar text-slate-400"></i>
            </div>
            <h3 class="empty-state-title">Nothing here yet</h3>
            <p class="empty-state-text">
                <?php if (!empty(array_filter($filters, fn($v) => $v !== ''))): ?>
                    No items match your filters. <a href="<?= url('/app/couple/timeline/tasks') ?>" class="text-rose-500 hover:underline font-semibold">Clear filters</a>
                <?php else: ?>
                    Start adding events to your wedding schedule.
                <?php endif; ?>
            </p>
            <a href="<?= url('/app/couple/timeline/tasks/create') ?>" class="btn btn-primary btn-md">
                <i class="fa-solid fa-plus"></i> Add to Schedule
            </a>
        </div>

    <?php else: ?>

    <!-- ── Agenda Sections ──────────────────────────────────────────────── -->
    <div class="space-y-6">

        <?php
        // Helper: render an agenda section
        function renderSection(array $items, string $label, string $icon, string $iconColor, bool $dimmed, string $currency = 'IDR'): void {
            if (empty($items)) return;
            ?>
            <div>
                <!-- Section label -->
                <div class="flex items-center gap-2 mb-3">
                    <i class="<?= $icon ?> <?= $iconColor ?> text-xs"></i>
                    <h2 class="text-xs font-bold text-slate-500 uppercase tracking-wider"><?= $label ?></h2>
                    <span class="text-xs text-slate-300"><?= count($items) ?></span>
                </div>

                <div class="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden divide-y divide-slate-50">
                    <?php foreach ($items as $t):
                        $id       = (int) $t['id'];
                        $status   = $t['status'] ?? 'Not Started';
                        $dueDate  = $t['due_date'] ?? null;
                        $dueTs    = $dueDate ? strtotime($dueDate) : null;
                        $isOverdue = ($dueTs && $dueTs < strtotime(date('Y-m-d')) && $status !== 'Completed' && $status !== 'Cancelled');
                        $isDone   = in_array($status, ['Completed', 'Cancelled']);

                        $dotColors = [
                            'Not Started' => 'bg-slate-300',
                            'In Progress' => 'bg-sky-400',
                            'Waiting'     => 'bg-amber-400',
                            'Completed'   => 'bg-emerald-400',
                            'Cancelled'   => 'bg-slate-200',
                        ];
                        $dot = $dotColors[$status] ?? 'bg-slate-300';
                    ?>
                        <div class="px-5 py-4 flex items-center gap-4 group <?= $dimmed ? 'opacity-60 hover:opacity-100 transition-opacity' : '' ?>">

                            <!-- Toggle -->
                            <form method="POST" action="<?= url('/app/couple/timeline/tasks/toggle-status/' . $id) ?>" class="flex-shrink-0">
                                <input type="hidden" name="_csrf" value="<?= escape_html($_SESSION['csrf_token'] ?? '') ?>">
                                <button type="submit"
                                        class="w-5 h-5 rounded-full border-2 flex items-center justify-center transition-all flex-shrink-0 <?= $status === 'Completed' ? 'bg-emerald-500 border-emerald-500 text-white' : 'border-slate-300 bg-white text-transparent hover:text-indigo-500 hover:border-indigo-400' ?>">
                                    <i class="fa-solid fa-check text-[9px]"></i>
                                </button>
                            </form>

                            <!-- Date column (calendar-style) -->
                            <?php if ($dueDate): ?>
                                <div class="flex-shrink-0 w-11 text-center">
                                    <span class="text-[11px] font-bold text-slate-400 block leading-tight"><?= date('M', $dueTs) ?></span>
                                    <span class="text-base font-black <?= $isOverdue ? 'text-rose-500' : ($dueDate === date('Y-m-d') ? 'text-indigo-600' : 'text-slate-700') ?> leading-tight block"><?= date('j', $dueTs) ?></span>
                                </div>
                            <?php else: ?>
                                <div class="flex-shrink-0 w-11 text-center">
                                    <span class="text-[10px] text-slate-300 italic">—</span>
                                </div>
                            <?php endif; ?>

                            <!-- Title + meta -->
                            <div class="flex-1 min-w-0">
                                <span class="text-sm font-semibold block truncate <?= $isDone ? 'text-slate-400 line-through' : 'text-slate-800' ?>">
                                    <?= escape_html($t['title']) ?>
                                </span>
                                <div class="flex items-center gap-2 mt-0.5 flex-wrap">
                                    <?php if (!empty($t['category'])): ?>
                                        <span class="text-[11px] text-slate-400"><?= escape_html($t['category']) ?></span>
                                    <?php endif; ?>
                                    <?php if ($isOverdue): ?>
                                        <span class="text-[10px] font-bold text-rose-500">Overdue</span>
                                    <?php elseif ($dueDate === date('Y-m-d') && !$isDone): ?>
                                        <span class="text-[10px] font-bold text-indigo-500">Today</span>
                                    <?php elseif ($dueDate === date('Y-m-d', strtotime('+1 day')) && !$isDone): ?>
                                        <span class="text-[10px] font-semibold text-amber-500">Tomorrow</span>
                                    <?php endif; ?>
                                    <!-- Status dot -->
                                    <span class="inline-flex items-center gap-1 text-[11px] text-slate-400">
                                        <span class="w-1.5 h-1.5 rounded-full inline-block <?= $dot ?>"></span>
                                        <?= $status ?>
                                    </span>
                                </div>
                            </div>

                            <!-- Actions (hover-reveal) -->
                            <div class="flex-shrink-0 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                <a href="<?= url('/app/couple/timeline/tasks/edit/' . $id) ?>"
                                   class="p-1.5 rounded-lg bg-slate-50 hover:bg-indigo-50 hover:text-indigo-600 text-slate-400 transition-all text-xs"
                                   title="Edit">
                                    <i class="fa-solid fa-pen text-[10px]"></i>
                                </a>
                                <form method="POST" action="<?= url('/app/couple/timeline/tasks/delete/' . $id) ?>"
                                      onsubmit="return confirm('Remove this item from your schedule?');" class="inline">
                                    <input type="hidden" name="_csrf" value="<?= escape_html($_SESSION['csrf_token'] ?? '') ?>">
                                    <button type="submit"
                                            class="p-1.5 rounded-lg bg-slate-50 hover:bg-rose-50 hover:text-rose-600 text-slate-400 transition-all text-xs"
                                            title="Delete">
                                        <i class="fa-solid fa-trash-can text-[10px]"></i>
                                    </button>
                                </form>
                            </div>

                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php
        }
        ?>

        <?php renderSection($grouped['overdue'],   'Needs Attention',  'fa-solid fa-circle-exclamation', 'text-rose-400',    false); ?>
        <?php renderSection($grouped['today'],     'Today',            'fa-solid fa-sun',                'text-amber-400',   false); ?>
        <?php renderSection($grouped['tomorrow'],  'Tomorrow',         'fa-solid fa-sunrise',            'text-orange-400',  false); ?>
        <?php renderSection($grouped['upcoming'],  'Coming Up',        'fa-solid fa-calendar-week',      'text-indigo-400',  false); ?>
        <?php renderSection($grouped['completed'], 'Completed',        'fa-solid fa-circle-check',       'text-emerald-400', true); ?>
        <?php renderSection($grouped['cancelled'], 'Cancelled',        'fa-solid fa-ban',                'text-slate-300',   true); ?>

    </div>

    <!-- ── Pagination ───────────────────────────────────────────────────── -->
    <?php if ($total_pages > 1): ?>
        <div class="flex items-center justify-between py-2">
            <span class="text-xs text-slate-400">
                Page <?= $page ?> of <?= $total_pages ?>
            </span>
            <div class="flex items-center gap-1.5">
                <?php if ($page > 1): ?>
                    <a href="<?= url('/app/couple/timeline/tasks?' . http_build_query(array_merge($filters, ['page' => $page - 1]))) ?>"
                       class="inline-flex items-center gap-1 px-3 py-1.5 bg-white border border-slate-200 hover:bg-slate-50 text-slate-600 rounded-xl text-xs font-semibold transition-all">
                        <i class="fa-solid fa-chevron-left text-[10px]"></i> Previous
                    </a>
                <?php endif; ?>
                <?php if ($page < $total_pages): ?>
                    <a href="<?= url('/app/couple/timeline/tasks?' . http_build_query(array_merge($filters, ['page' => $page + 1]))) ?>"
                       class="inline-flex items-center gap-1 px-3 py-1.5 bg-white border border-slate-200 hover:bg-slate-50 text-slate-600 rounded-xl text-xs font-semibold transition-all">
                        Next <i class="fa-solid fa-chevron-right text-[10px]"></i>
                    </a>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>

    <?php endif; ?>

</div>
