<?php
$pageTitle = 'Home';
$activePage = 'home';
$additionalCSS = '
<style>
.profile-wrapper {
    position: relative;
}
.profile-btn {
    background: rgba(255,255,255,0.2);
    border: none;
    border-radius: 50%;
    width: 38px;
    height: 38px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.5rem;
    cursor: pointer;
    transition: background 0.2s;
}
.profile-btn:hover {
    background: rgba(255,255,255,0.35);
}
.profile-popup {
    display: none;
    position: absolute;
    top: calc(100% + 10px);
    right: 0;
    background: white;
    border-radius: 14px;
    box-shadow: 0 8px 30px rgba(0,0,0,0.18);
    padding: 1.25rem 1.5rem;
    min-width: 200px;
    z-index: 9999;
    text-align: center;
}
.profile-popup.open {
    display: block;
}
.profile-popup-avatar {
    font-size: 2.8rem;
    color: #667eea;
    margin-bottom: 0.5rem;
}
.profile-popup-name {
    font-weight: 700;
    font-size: 1rem;
    color: #2d3748;
}
.profile-popup-email {
    font-size: 0.8rem;
    color: #718096;
    margin-top: 0.2rem;
    word-break: break-all;
}
.profile-popup-divider {
    margin: 0.75rem 0;
    border-color: #e2e8f0;
}
.profile-popup-logout {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #e53e3e;
    font-size: 0.9rem;
    font-weight: 600;
    text-decoration: none;
    padding: 0.4rem 0;
    border-radius: 8px;
    transition: background 0.2s;
}
.profile-popup-logout:hover {
    background: #fff5f5;
    color: #c53030;
}
.profile-popup-export {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #276749;
    font-size: 0.9rem;
    font-weight: 600;
    text-decoration: none;
    padding: 0.4rem 0;
    border-radius: 8px;
    transition: background 0.2s;
    margin-bottom: 0.25rem;
}
.profile-popup-export:hover {
    background: #f0fff4;
    color: #22543d;
}
</style>
';
include __DIR__ . '/_header.php';
?>

<header class="pwa-header">
    <div class="container-fluid">
        <div class="d-flex align-items-center justify-content-between">
            <h1 class="header-title mb-0">
                <i class="bi bi-gift me-2"></i>
                Birthday Reminder
            </h1>
            <div class="d-flex align-items-center gap-2">
                <button id="refreshAppBtn" class="btn btn-sm btn-warning" title="Refresh App">
                    <i class="bi bi-arrow-clockwise"></i>
                    <span class="d-none d-md-inline ms-1">Refresh</span>
                </button>

                <!-- Profile Icon -->
                <div class="profile-wrapper" id="profileWrapper">
                    <button class="profile-btn" id="profileBtn" title="Profile">
                        <i class="bi bi-person-circle"></i>
                    </button>
                    <!-- Profile Popup -->
                    <div class="profile-popup" id="profilePopup">
                        <div class="profile-popup-avatar">
                            <i class="bi bi-person-circle"></i>
                        </div>
                        <div class="profile-popup-name"><?php echo htmlspecialchars($_SESSION['username'] ?? ''); ?></div>
                        <div class="profile-popup-email"><?php echo htmlspecialchars($_SESSION['email'] ?? ''); ?></div>
                        <hr class="profile-popup-divider">
                        <a href="<?php echo BASE_URL; ?>/api/export-contacts" class="profile-popup-export" download>
                            <i class="bi bi-file-earmark-excel me-2"></i>Export Contacts
                        </a>
                        <a href="<?php echo URL_PATH; ?>/logout" class="profile-popup-logout">
                            <i class="bi bi-box-arrow-right me-2"></i>Logout
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>

<main class="pwa-content">
    <div class="container-fluid">
        <!-- Install App Prompt Banner -->
        <div id="installPrompt" class="alert alert-success alert-dismissible fade show d-none" role="alert">
            <div class="d-flex align-items-center">
                <i class="bi bi-download fs-4 me-3"></i>
                <div class="flex-grow-1">
                    <strong>Install App</strong>
                    <p class="mb-0 small">Install Birthday Reminder on your device for quick access!</p>
                </div>
                <button type="button" class="btn btn-sm btn-success me-2" id="install-pwa-button">
                    Install
                </button>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>

        <!-- iOS Safari Install Instructions -->
        <div id="iosInstallPrompt" class="alert alert-info alert-dismissible fade show d-none" role="alert">
            <div class="d-flex align-items-center">
                <i class="bi bi-apple fs-4 me-3"></i>
                <div class="flex-grow-1">
                    <strong>Install on iOS</strong>
                    <p class="mb-0 small">Tap <i class="bi bi-box-arrow-up"></i> then "Add to Home Screen"</p>
                </div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>

        <!-- Notification Prompt Banner -->
        <div id="notificationPrompt" class="alert alert-info alert-dismissible fade show d-none" role="alert">
            <div class="d-flex align-items-center">
                <i class="bi bi-bell fs-4 me-3"></i>
                <div class="flex-grow-1">
                    <strong>Enable Notifications</strong>
                    <p class="mb-0 small">Get daily reminders at 9 AM for birthdays and important dates!</p>
                </div>
                <button type="button" class="btn btn-sm btn-primary me-2" id="enableNotificationsBtn">
                    Enable
                </button>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>

        <!-- Today's Date -->
        <div class="date-badge">
            <i class="bi bi-calendar3 me-2"></i>
            <?php echo date('l, F j, Y'); ?>
        </div>

        <!-- Tab Navigation -->
        <?php
        $todayCount = count($todayBirthdays ?? []) + count($todayReminders ?? []);
        $dayColors = [
            'day1' => ['bg' => 'upcoming-day-1', 'icon' => 'bi-sun', 'label' => 'Tomorrow', 'accent' => '#4ade80'],
            'day2' => ['bg' => 'upcoming-day-2', 'icon' => 'bi-cloud-sun', 'label' => date('l', strtotime('+2 days')), 'accent' => '#fbbf24'],
            'day3' => ['bg' => 'upcoming-day-3', 'icon' => 'bi-stars', 'label' => date('l', strtotime('+3 days')), 'accent' => '#a78bfa']
        ];
        $upcomingCount = 0;
        foreach (['day1', 'day2', 'day3'] as $dk) {
            $upcomingCount += count($nextThreeDaysBirthdays[$dk] ?? []);
        }
        ?>

        <div class="home-tabs">
            <div class="home-tab active" data-tab="today">
                <i class="bi bi-cake2"></i>
                <span>Today</span>
                <?php if ($todayCount > 0): ?>
                    <span class="home-tab-badge"><?php echo $todayCount; ?></span>
                <?php endif; ?>
            </div>
            <div class="home-tab" data-tab="upcoming">
                <i class="bi bi-calendar-week"></i>
                <span>Upcoming</span>
                <?php if ($upcomingCount > 0): ?>
                    <span class="home-tab-badge upcoming"><?php echo $upcomingCount; ?></span>
                <?php endif; ?>
            </div>
        </div>

        <!-- TODAY TAB CONTENT -->
        <div class="home-tab-content active" id="tab-today">

            <!-- Birthdays Section -->
            <?php if (!empty($todayBirthdays)): ?>
                <div class="section-header">
                    <h2 class="section-title">
                        <i class="bi bi-cake2 me-2"></i>
                        Birthdays Today
                    </h2>
                    <span class="badge bg-primary"><?php echo count($todayBirthdays); ?></span>
                </div>

                <div class="cards-grid">
                    <?php foreach ($todayBirthdays as $contact): ?>
                        <div class="contact-card birthday-card">
                            <div class="contact-card-header">
                                <div class="contact-info">
                                    <div class="row">
                                        <div class="col-8">
                                            <h3 class="contact-name"><?php echo htmlspecialchars($contact['full_name']); ?></h3>
                                        </div>
                                        <div class="col-4 float-end ">
                                            <p class="contact-phone ">
                                                <i class="bi bi-telephone me-2"></i>
                                                <?php echo htmlspecialchars($contact['contact_number']); ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <?php if (!empty($contact['note'])): ?>
                                <p class="contact-note">
                                    <i class="bi bi-sticky me-1 text-light"></i>
                                    <?php echo htmlspecialchars($contact['note']); ?>
                                </p>
                            <?php endif; ?>

                            <div class="contact-actions">
                                <?php
                                $firstName = explode(' ', $contact['full_name'])[0];

                                if ($defaultTemplate && !empty($defaultTemplate->content)) {
                                    $message =   $defaultTemplate->content;
                                } else {
                                    $message =  "Happy Birthday! ðŸŽ‰ðŸŽ‚\n\nWishing you a wonderful day filled with joy and happiness!";
                                }

                                $whatsappUrl = 'https://wa.me/91' . $contact['contact_number'] . '?text=' . urlencode($message);
                                $smsUrl = 'sms:' . $contact['contact_number'] . '?body=' . urlencode($message);
                                ?>
                                <a href="<?php echo $whatsappUrl; ?>" class="btn btn-success btn-sm" target="_blank">
                                    <i class="bi bi-whatsapp me-1"></i>
                                    WhatsApp
                                </a>
                                <a href="<?php echo $smsUrl; ?>" class="btn btn-primary btn-sm">
                                    <i class="bi bi-chat-dots me-1"></i>
                                    SMS
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <!-- Notes/Reminders Section -->
            <?php if (!empty($todayReminders)): ?>
                <div class="section-header mt-4">
                    <h2 class="section-title">
                        <i class="bi bi-bell me-2"></i>
                        Reminders Today
                    </h2>
                    <span class="badge bg-warning"><?php echo count($todayReminders); ?></span>
                </div>

                <div class="cards-grid ">
                    <?php foreach ($todayReminders as $note): ?>
                        <div class="note-card bg-warning">
                            <?php if (!empty($note['image_path'])): ?>
                                <?php
                                $images = json_decode($note['image_path'], true);
                                if (!is_array($images)) {
                                    $images = [$note['image_path']];
                                }
                                ?>
                                <div class="note-image">
                                    <?php if (count($images) === 1): ?>
                                        <img src="<?php echo URL_PATH; ?>/uploads/<?php echo htmlspecialchars($images[0]); ?>"
                                            alt="<?php echo htmlspecialchars($note['title']); ?>"
                                            style="width: 100%; height: 200px; object-fit: cover; border-radius: 8px 8px 0 0;">
                                    <?php else: ?>
                                        <div class="row g-1 p-2">
                                            <?php foreach ($images as $index => $imagePath): ?>
                                                <?php if ($index < 4): ?>
                                                    <div class="col-6">
                                                        <img src="<?php echo URL_PATH; ?>/uploads/<?php echo htmlspecialchars($imagePath); ?>"
                                                            alt="<?php echo htmlspecialchars($note['title']); ?>"
                                                            style="width: 100%; height: 100px; object-fit: cover; border-radius: 4px;">
                                                    </div>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                            <?php if (count($images) > 4): ?>
                                                <div class="col-12 text-center mt-1">
                                                    <small class="text-muted">+<?php echo count($images) - 4; ?> more</small>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>

                            <div class="note-content">
                                <h3 class="note-title"><?php echo htmlspecialchars($note['title']); ?></h3>
                                <div class="note-meta">
                                    <span class="badge text-light <?php echo $note['note_type'] === 'single' ? 'bg-info' : 'bg-success'; ?>">
                                        <i class="bi bi-<?php echo $note['note_type'] === 'single' ? 'calendar-event' : 'arrow-repeat'; ?> me-1"></i>
                                        <?php echo ucfirst($note['note_type']); ?>
                                    </span>
                                    <span class="note-date">
                                        <i class="bi bi-calendar3 me-1"></i>
                                        <?php echo date('M j, Y', strtotime($note['reminder_date'])); ?>
                                    </span>
                                </div>
                                <?php if (!empty($note['content'])): ?>
                                    <p class="note-description"><?php echo nl2br(htmlspecialchars($note['content'])); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <!-- Empty State for Today -->
            <?php if (empty($todayBirthdays) && empty($todayReminders)): ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="bi bi-calendar-check"></i>
                    </div>
                    <h3 class="empty-title">No Reminders Today</h3>
                    <p class="empty-text">You're all caught up! No birthdays or reminders for today.</p>
                    <a href="<?php echo URL_PATH; ?>/add-contact" class="btn btn-primary">
                        <i class="bi bi-person-plus me-2"></i>
                        Add Contact
                    </a>
                </div>
            <?php endif; ?>

        </div>

        <!-- UPCOMING TAB CONTENT -->
        <div class="home-tab-content" id="tab-upcoming">

            <?php
            $hasUpcomingBirthdays = !empty($nextThreeDaysBirthdays['day1']) ||
                !empty($nextThreeDaysBirthdays['day2']) ||
                !empty($nextThreeDaysBirthdays['day3']);
            ?>

            <?php if ($hasUpcomingBirthdays): ?>
                <?php foreach (['day1', 'day2', 'day3'] as $dayKey): ?>
                    <?php if (!empty($nextThreeDaysBirthdays[$dayKey])): ?>
                        <div class="upcoming-section-header">
                            <div class="section-header-content">
                                <div class="section-icon-wrapper" style="background: <?php echo $dayColors[$dayKey]['accent']; ?>20;">
                                    <i class="bi <?php echo $dayColors[$dayKey]['icon']; ?>" style="color: <?php echo $dayColors[$dayKey]['accent']; ?>;"></i>
                                </div>
                                <div>
                                    <h2 class="section-title mb-0">
                                        <?php echo $dayColors[$dayKey]['label']; ?>
                                    </h2>
                                    <p class="upcoming-date-info">
                                        <i class="bi bi-calendar3 me-1"></i>
                                        <?php echo date('M j, Y', strtotime('+' . substr($dayKey, 3) . ' days')); ?>
                                    </p>
                                </div>
                            </div>
                            <span class="upcoming-badge" style="background: <?php echo $dayColors[$dayKey]['accent']; ?>;">
                                <?php echo count($nextThreeDaysBirthdays[$dayKey]); ?>
                            </span>
                        </div>

                        <div class="cards-grid">
                            <?php foreach ($nextThreeDaysBirthdays[$dayKey] as $contact): ?>
                                <div class="upcoming-birthday-card <?php echo $dayColors[$dayKey]['bg']; ?>">
                                    <div class="upcoming-card-decoration" style="background: <?php echo $dayColors[$dayKey]['accent']; ?>;"></div>
                                    <div class="upcoming-card-pattern"></div>

                                    <div class="upcoming-card-header ">
                                        <div class="upcoming-contact-info d-flex justify-content-between align-items-center">
                                            <h3 class="upcoming-contact-name"><?php echo htmlspecialchars($contact['full_name']); ?></h3>
                                            <a href="tel:<?php echo htmlspecialchars($contact['contact_number']); ?>" class="upcoming-phone-link">
                                                <i class="bi bi-telephone-fill me-1"></i>
                                                <?php echo htmlspecialchars($contact['contact_number']); ?>
                                            </a>
                                        </div>
                                    </div>

                                    <div class="upcoming-details-row">
                                        <div class="upcoming-detail-item">
                                            <i class="bi bi-calendar-heart-fill"></i>
                                            <div>
                                                <span class="detail-label">Date of Birth</span>
                                                <span class="detail-value"><?php echo date('d M, Y', strtotime($contact['date_of_birth'])); ?></span>
                                            </div>
                                        </div>
                                        <div class="upcoming-detail-item">
                                            <i class="bi bi-gift-fill"></i>
                                            <div>
                                                <span class="detail-label">Birthday</span>
                                                <span class="detail-value"><?php echo date('D, M j', strtotime($contact['birthday_date'])); ?></span>
                                            </div>
                                        </div>
                                    </div>

                                    <?php if (!empty($contact['note'])): ?>
                                        <div class="upcoming-note">
                                            <i class="bi bi-sticky-fill me-2"></i>
                                            <span><?php echo htmlspecialchars($contact['note']); ?></span>
                                        </div>
                                    <?php endif; ?>

                                    <div class="upcoming-actions">
                                        <?php
                                        $firstName = explode(' ', $contact['full_name'])[0];

                                        if ($defaultTemplate && !empty($defaultTemplate->content)) {
                                            $message = "Dear " . $firstName . ",\n\n" . $defaultTemplate->content;
                                        } else {
                                            $message = "Dear " . $firstName . ",\n\nHappy Birthday! 🎉🎂\n\nWishing you a wonderful day filled with joy and happiness!";
                                        }

                                        $whatsappUrl = 'https://wa.me/91' . $contact['contact_number'] . '?text=' . urlencode($message);
                                        $smsUrl = 'sms:' . $contact['contact_number'] . '?body=' . urlencode($message);
                                        ?>
                                        <a href="<?php echo $whatsappUrl; ?>" class="btn btn-success btn-sm" target="_blank">
                                            <i class="bi bi-whatsapp me-1"></i>
                                            WhatsApp
                                        </a>
                                        <a href="<?php echo $smsUrl; ?>" class="btn btn-primary btn-sm">
                                            <i class="bi bi-chat-dots me-1"></i>
                                            SMS
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="bi bi-calendar-week"></i>
                    </div>
                    <h3 class="empty-title">No Upcoming Birthdays</h3>
                    <p class="empty-text">No birthdays in the next 3 days.</p>
                    <a href="<?php echo URL_PATH; ?>/add-contact" class="btn btn-primary">
                        <i class="bi bi-person-plus me-2"></i>
                        Add Contact
                    </a>
                </div>
            <?php endif; ?>

        </div>

    </div>
</main>

<?php
$additionalJS = <<<'JS'

<script>
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.addEventListener("message", event => {
    if (event.data?.type === "SW_UPDATED") {
      console.log("[PWA] New version detected, reloading...");
      window.location.reload();
    }
  });
}


    // Profile popup toggle
    const profileBtn = document.getElementById('profileBtn');
    const profilePopup = document.getElementById('profilePopup');
    profileBtn?.addEventListener('click', function(e) {
        e.stopPropagation();
        profilePopup.classList.toggle('open');
    });
    document.addEventListener('click', function(e) {
        if (!document.getElementById('profileWrapper')?.contains(e.target)) {
            profilePopup?.classList.remove('open');
        }
    });

    async function hardRefreshPWA() {
        try {
            // 1. Clear all Cache Storage
            if ('caches' in window) {
                const cacheNames = await caches.keys();
                await Promise.all(
                    cacheNames.map(cacheName => caches.delete(cacheName))
                );
            }

            // 2. Unregister all Service Workers
            if ('serviceWorker' in navigator) {
                const registrations = await navigator.serviceWorker.getRegistrations();
                await Promise.all(
                    registrations.map(reg => reg.unregister())
                );
            }

            // 3. Clear localStorage & sessionStorage (optional but safe)
            localStorage.clear();
            sessionStorage.clear();

            // 4. Force reload from network
            location.reload(true);
        } catch (err) {
            console.error('PWA hard refresh failed:', err);
            location.reload();
        }
    }

    document.getElementById('refreshAppBtn')?.addEventListener('click', hardRefreshPWA);
</script>

<script>
    // Tab switching
    document.querySelectorAll('.home-tab').forEach(function(tab) {
        tab.addEventListener('click', function() {
            document.querySelectorAll('.home-tab').forEach(function(t) { t.classList.remove('active'); });
            document.querySelectorAll('.home-tab-content').forEach(function(c) { c.classList.remove('active'); });
            this.classList.add('active');
            document.getElementById('tab-' + this.dataset.tab).classList.add('active');
        });
    });
</script>

<script>
    // Notification prompt handling
    async function checkAndShowNotificationPrompt() {
        try {
            const status = await checkNotificationStatus();
            const promptDismissed = localStorage.getItem('notificationPromptDismissed');
            
            if (status.supported && !status.subscribed && !promptDismissed) {
                document.getElementById('notificationPrompt').classList.remove('d-none');
            }
        } catch (error) {
            console.error('[Home] Error checking notification status:', error);
        }
    }
    
    document.getElementById('enableNotificationsBtn')?.addEventListener('click', async function() {
        const subscription = await subscribeToPushNotifications();
        if (subscription) {
            document.getElementById('notificationPrompt').classList.add('d-none');
            localStorage.setItem('notificationPromptDismissed', 'true');
        }
    });
    
    document.querySelector('#notificationPrompt .btn-close')?.addEventListener('click', function() {
        localStorage.setItem('notificationPromptDismissed', 'true');
    });
    
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.ready.then(() => {
            checkAndShowNotificationPrompt();
        });
    }
    
    // Midnight auto-refresh
    function scheduleNextRefresh() {
        const now = new Date();
        const tomorrow = new Date(now);
        tomorrow.setDate(tomorrow.getDate() + 1);
        tomorrow.setHours(0, 0, 0, 0);
        
        const timeUntilMidnight = tomorrow - now;
        setTimeout(() => location.reload(), timeUntilMidnight);
    }
    
    scheduleNextRefresh();
</script>
JS;

include __DIR__ . '/_footer.php';
?>