<?php
/**
 * Dashboard Sidebar
 * LandSales Pro - Subscriber dashboard navigation
 */

// Get current page for active state
$currentPage = basename($_SERVER['PHP_SELF']);
$currentDir = basename(dirname($_SERVER['PHP_SELF']));

// Get subscription summary
$subscriptionSummary = getSubscriptionSummary($_SESSION['user_id']);

// Check if user can view payments (for followup notifications)
$canViewFollowups = canView('payments');
?>

<!-- Sidebar Overlay for Mobile -->
<div class="sidebar-overlay" onclick="toggleSidebar()"></div>

<!-- Sidebar -->
<aside class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <a href="<?php echo SITE_URL; ?>/dashboard/" class="sidebar-logo">
            <i class="fas fa-map-marked-alt"></i>
            <span><?php echo APP_NAME; ?></span>
        </a>
        <button class="sidebar-close" onclick="toggleSidebar()">
            <i class="fas fa-times"></i>
        </button>
    </div>

    <div class="sidebar-user">
        <div class="user-avatar">
            <?php echo strtoupper(substr($_SESSION['user_name'] ?? 'U', 0, 1)); ?>
        </div>
        <div class="user-info">
            <div class="user-name"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'User'); ?></div>
            <div class="user-plan">
                <?php if (isStaff()): ?>
                <span class="plan-badge staff-badge"><i class="fas fa-user-tag"></i> Staff</span>
                <?php else: ?>
                <span class="plan-badge"><?php echo $subscriptionSummary['plan']; ?></span>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Subscription Status -->
    <?php if ($subscriptionSummary['active'] && $subscriptionSummary['days_remaining'] <= 14): ?>
    <div class="subscription-alert">
        <i class="fas fa-exclamation-triangle"></i>
        <span><?php echo $subscriptionSummary['days_remaining']; ?> days remaining</span>
        <a href="settings/subscription.php">Renew</a>
    </div>
    <?php endif; ?>

    <nav class="sidebar-nav">
        <div class="nav-section">
            <div class="nav-section-title">Main</div>
            <a href="<?php echo SITE_URL; ?>/dashboard/" class="nav-link <?php echo $currentPage === 'index.php' && $currentDir === 'dashboard' ? 'active' : ''; ?>">
                <i class="fas fa-tachometer-alt"></i>
                <span>Dashboard</span>
            </a>
        </div>

        <div class="nav-section">
            <div class="nav-section-title">Land Management</div>
            <?php if (canView('projects')): ?>
            <a href="<?php echo SITE_URL; ?>/dashboard/projects/" class="nav-link <?php echo $currentDir === 'projects' ? 'active' : ''; ?>">
                <i class="fas fa-project-diagram"></i>
                <span>Projects</span>
            </a>
            <?php endif; ?>
            <?php if (canView('plots')): ?>
            <a href="<?php echo SITE_URL; ?>/dashboard/plots/" class="nav-link <?php echo $currentDir === 'plots' && $currentPage !== 'grid.php' ? 'active' : ''; ?>">
                <i class="fas fa-th"></i>
                <span>Plots</span>
            </a>
            <a href="<?php echo SITE_URL; ?>/dashboard/plots/grid.php" class="nav-link <?php echo $currentPage === 'grid.php' ? 'active' : ''; ?>">
                <i class="fas fa-border-all"></i>
                <span>Plot Grid</span>
            </a>
            <a href="<?php echo SITE_URL; ?>/dashboard/plots/scan.php" class="nav-link <?php echo $currentPage === 'scan.php' ? 'active' : ''; ?>">
                <i class="fas fa-crosshairs"></i>
                <span>Scan Location</span>
            </a>
            <?php endif; ?>
        </div>

        <div class="nav-section">
            <div class="nav-section-title">Sales</div>
            <?php if (canView('buyers')): ?>
            <a href="<?php echo SITE_URL; ?>/dashboard/buyers/" class="nav-link <?php echo $currentDir === 'buyers' ? 'active' : ''; ?>">
                <i class="fas fa-users"></i>
                <span>Buyers</span>
            </a>
            <?php endif; ?>
            <?php if (canView('sales')): ?>
            <a href="<?php echo SITE_URL; ?>/dashboard/sales/" class="nav-link <?php echo $currentDir === 'sales' ? 'active' : ''; ?>">
                <i class="fas fa-handshake"></i>
                <span>Sales</span>
            </a>
            <?php endif; ?>
            <?php if (canView('payments')): ?>
            <a href="<?php echo SITE_URL; ?>/dashboard/payments/" class="nav-link <?php echo $currentDir === 'payments' ? 'active' : ''; ?>">
                <i class="fas fa-money-bill-wave"></i>
                <span>Payments</span>
            </a>
            <?php endif; ?>
        </div>

        <div class="nav-section">
            <div class="nav-section-title">Team & Finance</div>
            <?php if (canView('agents')): ?>
            <a href="<?php echo SITE_URL; ?>/dashboard/agents/" class="nav-link <?php echo $currentDir === 'agents' ? 'active' : ''; ?>">
                <i class="fas fa-user-tie"></i>
                <span>Agents</span>
            </a>
            <?php endif; ?>
            <a href="<?php echo SITE_URL; ?>/dashboard/expenses/" class="nav-link <?php echo $currentDir === 'expenses' ? 'active' : ''; ?>">
                <i class="fas fa-receipt"></i>
                <span>Expenses</span>
            </a>
            <?php if (!isStaff()): ?>
            <a href="<?php echo SITE_URL; ?>/dashboard/users/" class="nav-link <?php echo $currentDir === 'users' ? 'active' : ''; ?>">
                <i class="fas fa-user-friends"></i>
                <span>Staff Users</span>
            </a>
            <?php endif; ?>
        </div>

        <?php if (canView('reports')): ?>
        <div class="nav-section">
            <div class="nav-section-title">Reports</div>
            <a href="<?php echo SITE_URL; ?>/dashboard/reports/" class="nav-link <?php echo $currentDir === 'reports' ? 'active' : ''; ?>">
                <i class="fas fa-chart-bar"></i>
                <span>Reports</span>
            </a>
        </div>
        <?php endif; ?>

        <div class="nav-section">
            <div class="nav-section-title">Account</div>
            <?php if (!isStaff() || canView('settings')): ?>
            <a href="<?php echo SITE_URL; ?>/dashboard/settings/" class="nav-link <?php echo $currentDir === 'settings' && $currentPage === 'index.php' ? 'active' : ''; ?>">
                <i class="fas fa-cog"></i>
                <span>Settings</span>
            </a>
            <?php endif; ?>
            <a href="<?php echo SITE_URL; ?>/contact.php" class="nav-link">
                <i class="fas fa-headset"></i>
                <span>Contact Us</span>
            </a>
            <a href="<?php echo SITE_URL; ?>/logout.php" class="nav-link">
                <i class="fas fa-sign-out-alt"></i>
                <span>Logout</span>
            </a>
        </div>
    </nav>

    <div class="sidebar-footer">
        <small>&copy; <?php echo date('Y'); ?> <?php echo APP_NAME; ?></small>
    </div>
</aside>

<style>
    /* Sidebar Styles */
    .sidebar {
        position: fixed;
        top: 0;
        left: 0;
        width: 260px;
        height: 100vh;
        background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
        color: white;
        z-index: 1000;
        display: flex;
        flex-direction: column;
        transition: transform 0.3s ease;
    }

    .sidebar-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.5);
        z-index: 999;
    }

    .sidebar-header {
        padding: 1.5rem;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .sidebar-logo {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        color: white;
        text-decoration: none;
        font-size: 1.25rem;
        font-weight: 700;
    }

    .sidebar-logo i {
        color: #667eea;
    }

    .sidebar-close {
        display: none;
        background: none;
        border: none;
        color: #94a3b8;
        font-size: 1.25rem;
        cursor: pointer;
    }

    .sidebar-user {
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .user-avatar {
        width: 42px;
        height: 42px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        font-size: 1rem;
    }

    .user-info {
        flex: 1;
    }

    .user-name {
        font-weight: 600;
        font-size: 0.9rem;
    }

    .user-plan {
        margin-top: 0.25rem;
    }

    .plan-badge {
        font-size: 0.7rem;
        padding: 0.2rem 0.5rem;
        background: rgba(102, 126, 234, 0.3);
        border-radius: 4px;
        color: #a5b4fc;
    }

    .staff-badge {
        background: rgba(34, 197, 94, 0.3);
        color: #86efac;
    }

    .staff-badge i {
        margin-right: 0.25rem;
    }

    .subscription-alert {
        margin: 1rem;
        padding: 0.75rem 1rem;
        background: rgba(245, 158, 11, 0.15);
        border: 1px solid rgba(245, 158, 11, 0.3);
        border-radius: 8px;
        font-size: 0.8rem;
        color: #fbbf24;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .subscription-alert a {
        margin-left: auto;
        color: #fbbf24;
        text-decoration: underline;
    }

    .sidebar-nav {
        flex: 1;
        overflow-y: auto;
        padding: 1rem 0;
    }

    .nav-section {
        margin-bottom: 0.75rem;
    }

    .nav-section-title {
        padding: 0.5rem 1.5rem;
        font-size: 0.7rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #64748b;
    }

    .nav-link {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 0.65rem 1.5rem;
        color: #94a3b8;
        text-decoration: none;
        transition: all 0.2s;
        border-left: 3px solid transparent;
        font-size: 0.9rem;
    }

    .nav-link:hover {
        background: rgba(255,255,255,0.05);
        color: white;
    }

    .nav-link.active {
        background: rgba(102, 126, 234, 0.15);
        color: #667eea;
        border-left-color: #667eea;
    }

    .nav-link i {
        width: 20px;
        text-align: center;
        font-size: 0.9rem;
    }

    .sidebar-footer {
        padding: 1rem 1.5rem;
        border-top: 1px solid rgba(255,255,255,0.1);
        color: #64748b;
        font-size: 0.75rem;
        text-align: center;
    }

    /* Main Content Area */
    .main-content {
        margin-left: 260px;
        min-height: 100vh;
        background: #f1f5f9;
    }

    .top-header {
        background: white;
        padding: 1rem 2rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .menu-toggle {
        display: none;
        background: none;
        border: none;
        font-size: 1.25rem;
        cursor: pointer;
        color: #64748b;
        padding: 0.5rem;
    }

    .page-title {
        font-size: 1.25rem;
        font-weight: 600;
        color: #1e293b;
    }

    .content-wrapper {
        padding: 2rem;
    }

    /* Notification Bell Styles */
    .notification-wrapper {
        position: relative;
        margin-left: auto;
        margin-right: 1rem;
    }

    .notification-bell {
        position: relative;
        background: none;
        border: none;
        cursor: pointer;
        padding: 0.5rem;
        color: #64748b;
        font-size: 1.25rem;
        transition: all 0.2s;
    }

    .notification-bell:hover {
        color: #667eea;
    }

    .notification-badge {
        position: absolute;
        top: 2px;
        right: 2px;
        min-width: 18px;
        height: 18px;
        background: #ef4444;
        color: white;
        font-size: 0.65rem;
        font-weight: 600;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 4px;
        animation: pulse-badge 2s infinite;
    }

    @keyframes pulse-badge {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.1); }
    }

    .notification-dropdown {
        position: absolute;
        top: 100%;
        right: 0;
        width: 400px;
        max-height: 500px;
        background: white;
        border-radius: 12px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.15);
        z-index: 1100;
        display: none;
        overflow: hidden;
    }

    .notification-dropdown.show {
        display: block;
        animation: slideDown 0.2s ease;
    }

    @keyframes slideDown {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .notification-header {
        padding: 1rem 1.25rem;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .notification-header h3 {
        margin: 0;
        font-size: 1rem;
        font-weight: 600;
    }

    .notification-header .date-badge {
        font-size: 0.75rem;
        opacity: 0.9;
    }

    .notification-list {
        max-height: 380px;
        overflow-y: auto;
    }

    .notification-item {
        padding: 1rem 1.25rem;
        border-bottom: 1px solid #f1f5f9;
        transition: background 0.2s;
    }

    .notification-item:hover {
        background: #f8fafc;
    }

    .notification-item.handled {
        opacity: 0.6;
        background: #f8fafc;
    }

    .notification-buyer {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 0.5rem;
    }

    .buyer-info h4 {
        margin: 0 0 0.25rem;
        font-size: 0.95rem;
        color: #1e293b;
    }

    .buyer-info .phone {
        font-size: 0.8rem;
        color: #64748b;
    }

    .buyer-info .phone a {
        color: #667eea;
        text-decoration: none;
    }

    .amount-due {
        text-align: right;
    }

    .amount-due .amount {
        font-weight: 700;
        color: #1e293b;
        font-size: 0.95rem;
    }

    .amount-due .due-label {
        font-size: 0.7rem;
        color: #16a34a;
    }

    .amount-due .due-label i {
        margin-right: 0.25rem;
        color: #9333ea;
    }

    .notification-details {
        font-size: 0.8rem;
        color: #64748b;
        margin-bottom: 0.75rem;
    }

    .notification-details span {
        margin-right: 1rem;
    }

    .notification-details i {
        margin-right: 0.25rem;
        width: 14px;
    }

    .notification-actions {
        display: flex;
        gap: 0.5rem;
        flex-wrap: wrap;
    }

    .followup-btn {
        padding: 0.35rem 0.75rem;
        border-radius: 6px;
        font-size: 0.75rem;
        font-weight: 500;
        border: none;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 0.35rem;
        transition: all 0.2s;
    }

    .followup-btn.called {
        background: #dbeafe;
        color: #2563eb;
    }

    .followup-btn.called:hover {
        background: #bfdbfe;
    }

    .followup-btn.no-answer {
        background: #fef3c7;
        color: #d97706;
    }

    .followup-btn.no-answer:hover {
        background: #fde68a;
    }

    .followup-btn.paid {
        background: #dcfce7;
        color: #16a34a;
    }

    .followup-btn.paid:hover {
        background: #bbf7d0;
    }

    .followup-btn.promised {
        background: #ede9fe;
        color: #7c3aed;
    }

    .followup-btn.promised:hover {
        background: #ddd6fe;
    }

    .followup-status {
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
        border-radius: 4px;
        display: inline-flex;
        align-items: center;
        gap: 0.25rem;
    }

    .followup-status.called {
        background: #dbeafe;
        color: #2563eb;
    }

    .followup-status.no_answer {
        background: #fef3c7;
        color: #d97706;
    }

    .followup-status.rescheduled {
        background: #f3e8ff;
        color: #9333ea;
    }

    .followup-status.promised_today {
        background: #ede9fe;
        color: #7c3aed;
    }

    .notification-empty {
        padding: 2rem;
        text-align: center;
        color: #94a3b8;
    }

    .notification-empty i {
        font-size: 2.5rem;
        margin-bottom: 0.75rem;
        color: #22c55e;
    }

    .notification-empty h4 {
        margin: 0 0 0.25rem;
        color: #1e293b;
    }

    .notification-footer {
        padding: 0.75rem 1.25rem;
        border-top: 1px solid #f1f5f9;
        text-align: center;
    }

    .notification-footer a {
        color: #667eea;
        text-decoration: none;
        font-size: 0.85rem;
        font-weight: 500;
    }

    /* Reschedule Modal */
    .reschedule-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.5);
        z-index: 1200;
        align-items: center;
        justify-content: center;
    }

    .reschedule-modal.show {
        display: flex;
    }

    .reschedule-content {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        width: 90%;
        max-width: 400px;
        animation: slideDown 0.2s ease;
    }

    .reschedule-content h4 {
        margin: 0 0 1rem;
        color: #1e293b;
    }

    .reschedule-content .form-group {
        margin-bottom: 1rem;
    }

    .reschedule-content label {
        display: block;
        font-size: 0.85rem;
        color: #64748b;
        margin-bottom: 0.5rem;
    }

    .reschedule-content input,
    .reschedule-content textarea {
        width: 100%;
        padding: 0.625rem;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        font-size: 0.9rem;
        box-sizing: border-box;
    }

    .reschedule-content textarea {
        resize: vertical;
        min-height: 60px;
    }

    .reschedule-buttons {
        display: flex;
        gap: 0.75rem;
        justify-content: flex-end;
        margin-top: 1.25rem;
    }

    .reschedule-buttons button {
        padding: 0.5rem 1rem;
        border-radius: 6px;
        font-weight: 500;
        cursor: pointer;
        border: none;
    }

    .reschedule-buttons .cancel-btn {
        background: #f1f5f9;
        color: #64748b;
    }

    .reschedule-buttons .save-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    /* Mobile Responsive */
    @media (max-width: 992px) {
        .sidebar {
            transform: translateX(-100%);
        }

        .sidebar.active {
            transform: translateX(0);
        }

        .sidebar-overlay.active {
            display: block;
        }

        .sidebar-close {
            display: block;
        }

        .main-content {
            margin-left: 0;
        }

        .menu-toggle {
            display: block;
        }

        .content-wrapper {
            padding: 1.5rem;
        }

        .notification-dropdown {
            width: calc(100vw - 2rem);
            max-width: 400px;
            right: -1rem;
        }

        .notification-item {
            padding: 0.875rem 1rem;
        }

        .notification-actions {
            flex-wrap: wrap;
        }

        .followup-btn {
            flex: 1 1 45%;
            justify-content: center;
        }
    }

    @media (max-width: 480px) {
        .notification-dropdown {
            width: calc(100vw - 1rem);
            right: -0.5rem;
        }

        .notification-buyer {
            flex-direction: column;
            gap: 0.5rem;
        }

        .amount-due {
            text-align: left;
        }
    }
</style>

<script>
function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('active');
    document.querySelector('.sidebar-overlay').classList.toggle('active');
}

<?php if ($canViewFollowups): ?>
// Payment Follow-up Notifications
const FollowupNotifications = {
    dropdown: null,
    badge: null,
    list: null,
    currentScheduleId: null,

    init() {
        this.dropdown = document.getElementById('followupDropdown');
        this.badge = document.getElementById('followupBadge');
        this.list = document.getElementById('followupList');

        if (!this.dropdown) return;

        // Load followups on init
        this.loadFollowups();

        // Refresh every 5 minutes
        setInterval(() => this.loadFollowups(), 300000);

        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.notification-wrapper')) {
                this.dropdown.classList.remove('show');
            }
        });
    },

    toggle() {
        this.dropdown.classList.toggle('show');
        if (this.dropdown.classList.contains('show')) {
            this.loadFollowups();
        }
    },

    async loadFollowups() {
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/ajax/get-followups.php');
            const data = await response.json();

            if (data.success) {
                this.renderFollowups(data);
                this.updateBadge(data.pending_count);
            }
        } catch (error) {
            console.error('Error loading followups:', error);
        }
    },

    updateBadge(count) {
        if (count > 0) {
            this.badge.textContent = count > 99 ? '99+' : count;
            this.badge.style.display = 'flex';
        } else {
            this.badge.style.display = 'none';
        }
    },

    renderFollowups(data) {
        if (data.followups.length === 0) {
            this.list.innerHTML = `
                <div class="notification-empty">
                    <i class="fas fa-check-circle"></i>
                    <h4>All caught up!</h4>
                    <p>No payments due for follow-up today</p>
                </div>`;
            return;
        }

        let html = '';
        data.followups.forEach(f => {
            const isHandled = f.followup_status !== 'pending';
            html += `
                <div class="notification-item ${isHandled ? 'handled' : ''}" data-schedule-id="${f.schedule_id}">
                    <div class="notification-buyer">
                        <div class="buyer-info">
                            <h4>${this.escapeHtml(f.buyer_name)}</h4>
                            <div class="phone"><a href="tel:${f.buyer_phone}">${f.buyer_phone}</a></div>
                        </div>
                        <div class="amount-due">
                            <div class="amount">TZS ${f.amount}</div>
                            <div class="due-label">
                                ${f.is_rescheduled ? '<i class="fas fa-redo"></i> Rescheduled' : 'Due today'}
                            </div>
                        </div>
                    </div>
                    <div class="notification-details">
                        <span><i class="fas fa-map-marker-alt"></i>${this.escapeHtml(f.project_name)} - Plot ${f.plot_number}</span>
                        <span><i class="fas fa-hashtag"></i>${f.installment}</span>
                    </div>
                    ${isHandled ? this.renderStatus(f) : this.renderActions(f.schedule_id)}
                </div>`;
        });

        this.list.innerHTML = html;
    },

    renderActions(scheduleId) {
        return `
            <div class="notification-actions">
                <button class="followup-btn promised" onclick="FollowupNotifications.showPromised(${scheduleId})">
                    <i class="fas fa-handshake"></i> Promised
                </button>
                <button class="followup-btn no-answer" onclick="FollowupNotifications.markAs(${scheduleId}, 'no_answer')">
                    <i class="fas fa-phone-slash"></i> No Answer
                </button>
                <button class="followup-btn paid" onclick="FollowupNotifications.markAs(${scheduleId}, 'paid')">
                    <i class="fas fa-check"></i> Paid
                </button>
            </div>`;
    },

    renderStatus(f) {
        const statusMap = {
            'called': { icon: 'fa-phone', label: 'Called', time: f.called_at },
            'no_answer': { icon: 'fa-phone-slash', label: 'No Answer', time: f.called_at },
            'rescheduled': { icon: 'fa-calendar-alt', label: 'Promised: ' + (f.promised_date || ''), time: '' },
            'promised_today': { icon: 'fa-handshake', label: 'Promised Today', time: f.called_at },
            'paid': { icon: 'fa-check', label: 'Marked as Paid', time: f.called_at }
        };
        const status = statusMap[f.followup_status] || { icon: 'fa-clock', label: f.followup_status, time: '' };

        return `
            <div class="followup-status ${f.followup_status}">
                <i class="fas ${status.icon}"></i>
                ${status.label} ${status.time ? '@ ' + status.time : ''}
            </div>`;
    },

    async markAs(scheduleId, action, notes = '', promisedDate = null) {
        try {
            const response = await fetch('<?php echo SITE_URL; ?>/ajax/update-followup.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    schedule_id: scheduleId,
                    action: action,
                    notes: notes,
                    promised_date: promisedDate
                })
            });

            const data = await response.json();

            if (data.success) {
                this.loadFollowups();
            } else {
                alert(data.error || 'Failed to update');
            }
        } catch (error) {
            console.error('Error updating followup:', error);
            alert('Failed to update followup');
        }
    },

    showPromised(scheduleId) {
        this.currentScheduleId = scheduleId;
        document.getElementById('promisedModal').classList.add('show');
        document.getElementById('promisedDate').value = '';
        document.getElementById('promisedNotes').value = '';
        document.getElementById('promisedDateGroup').style.display = 'none';

        // Reset radio buttons
        document.querySelectorAll('input[name="promisedType"]').forEach(r => r.checked = false);

        // Set min date to tomorrow for "another date" option
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        document.getElementById('promisedDate').min = tomorrow.toISOString().split('T')[0];
    },

    closePromised() {
        document.getElementById('promisedModal').classList.remove('show');
        this.currentScheduleId = null;
    },

    togglePromisedDate(show) {
        document.getElementById('promisedDateGroup').style.display = show ? 'block' : 'none';
        if (!show) {
            document.getElementById('promisedDate').value = '';
        }
    },

    submitPromised() {
        const promisedType = document.querySelector('input[name="promisedType"]:checked')?.value;
        const notes = document.getElementById('promisedNotes').value;

        if (!promisedType) {
            alert('Please select when the buyer promised to pay');
            return;
        }

        if (promisedType === 'today') {
            // Promised to pay today
            this.markAs(this.currentScheduleId, 'promised_today', notes, null);
        } else {
            // Promised to pay on another date
            const date = document.getElementById('promisedDate').value;
            if (!date) {
                alert('Please select the promised payment date');
                return;
            }
            this.markAs(this.currentScheduleId, 'rescheduled', notes, date);
        }
        this.closePromised();
    },

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
};

document.addEventListener('DOMContentLoaded', () => FollowupNotifications.init());
<?php endif; ?>
</script>
