<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <title>Reminder Queues - Inway Reminder System</title>
    <link rel="stylesheet" href="{{ @ASSET_PATH }}/css/variables.css">
    <link rel="stylesheet" href="{{ @ASSET_PATH }}/css/base.css">
    <link rel="stylesheet" href="{{ @ASSET_PATH }}/css/layout.css">
    <link rel="stylesheet" href="{{ @ASSET_PATH }}/css/components.css">
    <link rel="stylesheet" href="{{ @ASSET_PATH }}/css/mobile.css">
    <style>
/* =====================================================
   HEADER
===================================================== */
.staff-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    background: white;
    border-bottom: 1px solid #e5e7eb;
}

.staff-header-left {
    display: flex;
    align-items: center;
    gap: 16px;
}

.staff-header-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.company-name {
    font-weight: 600;
    color: #374151;
}

.user-avatar-sm {
    width: 32px;
    height: 32px;
    background: #FD4326;
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 14px;
}

/* =====================================================
   SIDEBAR
===================================================== */
.staff-sidebar {
    width: 220px;
    background: #FD4326;
    min-height: 100vh;
    padding: 20px 0;
    transition: transform 0.3s ease;
}

.staff-brand {
    padding: 0 20px 20px;
    color: white;
    font-size: 1.25rem;
    font-weight: 700;
}

.staff-nav a {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 20px;
    color: rgba(255,255,255,0.8);
    text-decoration: none;
    transition: all 0.2s;
}

.staff-nav a:hover,
.staff-nav a.active {
    background: rgba(255,255,255,0.1);
    color: white;
}

.staff-nav a svg {
    width: 20px;
    height: 20px;
}

/* =====================================================
   TABLE (DESKTOP)
===================================================== */
.reminder-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 700px;
}

.reminder-table th,
.reminder-table td {
    padding: 12px 16px;
    text-align: left;
    border-bottom: 1px solid #e5e7eb;
}

.reminder-table th {
    background: #f9fafb;
    font-weight: 600;
    font-size: 12px;
    text-transform: uppercase;
    color: #6b7280;
}

/* =====================================================
   STATUS BADGES
===================================================== */
.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
    display: inline-block;
}

.status-sent { background: #dcfce7; color: #16a34a; }
.status-pending { background: #fef3c7; color: #d97706; }
.status-overdue { background: #fee2e2; color: #dc2626; }

/* =====================================================
   QUEUE TABS
===================================================== */
.queue-tabs {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
    flex-wrap: wrap;
}

.queue-tab {
    padding: 8px 16px;
    border: 1px solid #e5e7eb;
    background: white;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
}

.queue-tab.active {
    background: #FD4326;
    color: white;
    border-color: #FD4326;
}

/* =====================================================
   ACTION BUTTONS
===================================================== */
.action-btn {
    padding: 6px 12px;
    border-radius: 6px;
    font-size: 12px;
    cursor: pointer;
    border: none;
    display: inline-block;
    text-decoration: none;
    margin-right: 4px;
}

.action-btn.whatsapp { background: #22c55e; color: white; }
.action-btn.call { background: #3b82f6; color: white; }
.action-btn.mark { background: #6b7280; color: white; }

/* =====================================================
   MOBILE MENU BUTTON
===================================================== */
.mobile-menu-toggle {
    display: none;
    background: #FD4326;
    color: white;
    border: none;
    padding: 10px 14px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 18px;
}

/* =====================================================
   SIDEBAR OVERLAY
===================================================== */
.sidebar-overlay {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.5);
    z-index: 99;
    pointer-events: none;
}

.sidebar-overlay.active,
.sidebar-overlay.open {
    display: block;
    pointer-events: auto;
}

/* =====================================================
   ✅ MOBILE RESPONSIVE FIX
===================================================== */
@media (max-width: 768px) {

    html, body {
        overflow-x: hidden !important;
    }

    /* Sidebar drawer */
    .staff-sidebar {
        position: fixed;
        top: 0;
        left: 0;
        width: 240px;
        height: 100vh;
        transform: translateX(-100%);
        z-index: 100;
    }

    .staff-sidebar.open {
        transform: translateX(0);
    }

    .mobile-menu-toggle {
        display: block;
        touch-action: manipulation;
        -webkit-tap-highlight-color: transparent;
    }

    /* TABLE → CARD CONVERSION */
    .table-wrapper {
        overflow: visible !important;
    }

    .reminder-table {
        min-width: 100% !important;
        border: none;
    }

    .reminder-table thead {
        display: none !important;
    }

    .reminder-table,
    .reminder-table tbody,
    .reminder-table tr {
        display: block !important;
        width: 100%;
    }

    .reminder-table tr {
        background: white;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 16px;
        box-shadow: 0 1px 4px rgba(0,0,0,0.1);
    }

    .reminder-table td {
        display: flex !important;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0 !important;
        border: none !important;
        font-size: 14px;
    }

    .reminder-table td::before {
        font-weight: 600;
        color: #6b7280;
        font-size: 13px;
        margin-right: 12px;
    }

    .reminder-table td:nth-child(1)::before { content: "Domain"; }
    .reminder-table td:nth-child(2)::before { content: "Customer"; }
    .reminder-table td:nth-child(3)::before { content: "Phone"; }
    .reminder-table td:nth-child(4)::before { content: "Service"; }
    .reminder-table td:nth-child(5)::before { content: "Due Date"; }
    .reminder-table td:nth-child(6)::before { content: "Status"; }
    .reminder-table td:nth-child(7)::before { content: "Actions"; }

    .reminder-table td:last-child {
        flex-direction: column;
        align-items: stretch;
        gap: 8px;
        margin-top: 12px;
    }

    .action-btn {
        width: 100%;
        text-align: center;
        font-size: 14px;
        padding: 10px;
        margin-right: 0;
        touch-action: manipulation;
        -webkit-tap-highlight-color: transparent;
    }

    /* Tabs spacing */
    .queue-tabs {
        gap: 8px;
    }

    /* Main spacing */
    main {
        padding: 12px !important;
    }

    h1 {
        font-size: 1.25rem !important;
    }
}
</style>

</head>
<body style="background: #f9fafb;">

    <div class="sidebar-overlay" id="sidebar-overlay" onclick="toggleSidebar()"></div>

    <div style="display: flex;">

        <!-- SIDEBAR -->
        <aside class="staff-sidebar" id="staff-sidebar">

            <div class="staff-brand">
                Inway Service Hub
            </div>

            <nav class="staff-nav">

                <a href="{{ @BASE_PATH }}/staff">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7" />
                    </svg>
                    Dashboard Overview
                </a>

                <a href="{{ @BASE_PATH }}/staff/services">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2" />
                    </svg>
                    Service Plans & Assets
                </a>

                <a href="{{ @BASE_PATH }}/staff/reminders" class="active">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5" />
                    </svg>
                    Renewal Management
                </a>

            </nav>

            <div style="padding: 16px; border-top: 1px solid rgba(255,255,255,0.1); margin-top: auto;">
                <a href="{{ @BASE_PATH }}/logout"
                   class="btn"
                   style="background: rgba(255,255,255,0.1); color: white; width: 100%; text-align: center;">
                    Logout
                </a>
            </div>

        </aside>


        <!-- MAIN CONTENT -->
        <div style="flex: 1;">

            <header class="staff-header">

                <div class="staff-header-left">
                    <button class="mobile-menu-toggle" onclick="toggleSidebar()">&#9776;</button>
                    <span class="company-name">
                        {{ @company.name ?? 'INWAY Service Hub' }}
                    </span>
                </div>

                <div class="staff-header-right">
                    <span style="font-size: 14px;">
                        {{ @user.name }}
                    </span>
                    <div class="user-avatar-sm">
                        {{ substr(@user.name, 0, 1) }}
                    </div>
                </div>

            </header>


            <main style="padding: 24px;">

                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 12px;">
                    <h1 style="font-size: 1.5rem; font-weight: 700;">
                        Subscription Renewal Queues
                    </h1>
                </div>

                <!-- FILTER TABS -->
                <div class="queue-tabs">
                    <button class="queue-tab active"
                            data-filter="all"
                            onclick="filterQueue('all', this)">
                        All Subscriptions
                    </button>

                    <button class="queue-tab"
                            data-filter="whatsapp"
                            onclick="filterQueue('whatsapp', this)">
                        WhatsApp Renewal Queue
                    </button>

                    <button class="queue-tab"
                            data-filter="call"
                            onclick="filterQueue('call', this)">
                        Client Follow-up Queue
                    </button>
                </div>


                <!-- TABLE -->
                <div style="background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">

                    <div class="table-wrapper">

                        <table class="reminder-table">

                            <thead>
                                <tr>
                                    <th>Asset ID</th>
                                    <th>Client</th>
                                    <th>Contact</th>
                                    <th>Service Plan</th>
                                    <th>Renewal Date</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>

                            <tbody id="reminders-body">
                                <tr>
                                    <td colspan="7"
                                        style="text-align: center; padding: 40px;">
                                        Loading subscription renewals...
                                    </td>
                                </tr>
                            </tbody>

                        </table>

                    </div>

                </div>

            </main>

        </div>
    </div>
    <div class="toast-container"></div>
    <script src="{{ @ASSET_PATH }}/js/app.js"></script>
    <script>
        const BASE_PATH = '{{ @BASE_PATH }}';
        let allReminders = [];
        let currentFilter = 'all';
        
        function toggleSidebar() {
            const sidebar = document.getElementById('staff-sidebar');
            const overlay = document.getElementById('sidebar-overlay');
            if (sidebar) sidebar.classList.toggle('open');
            if (overlay) overlay.classList.toggle('active');
        }
        
        async function loadReminders() {
            try {
                let url = BASE_PATH + '/api/staff/reminders';
                if (currentFilter && currentFilter !== 'all') {
                    url += '?type=' + currentFilter;
                }
                const response = await fetch(url);
                const data = await response.json();
                
                if (data.success) {
                    allReminders = data.reminders || [];
                    renderReminders(allReminders);
                }
            } catch (error) {
                console.error('Error loading reminders:', error);
            }
        }
        
        function renderReminders(reminders) {
            const tbody = document.getElementById('reminders-body');
            
            if (reminders.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; padding: 40px; color: #6b7280;">No reminders found</td></tr>';
                return;
            }
            
            tbody.innerHTML = reminders.map(r => {
                const today = new Date().toISOString().split('T')[0];
                const isOverdue = r.next_service_date < today;
                const statusClass = r.status === 'sent' ? 'status-sent' : (isOverdue ? 'status-overdue' : 'status-pending');
                const statusText = r.status === 'sent' ? 'Reminder Sent' : (isOverdue ? 'Overdue' : 'Pending');
                const phone = (r.customer_phone || '').replace(/[^0-9+]/g, '');
                const rowStyle = r.status === 'sent' ? 'background-color: #d1fae5;' : '';
                
                return `
                    <tr data-type="${r.reminder_type || 'service_due'}" style="${rowStyle}">
                        <td>${r.registration_number || ''}</td>
                        <td>${r.customer_name || ''}</td>
                        <td>${r.customer_phone || ''}</td>
                        <td>${r.service_type || ''}</td>
                        <td>${r.next_service_date || ''}</td>
                        <td><span class="status-badge ${statusClass}">${statusText}</span></td>
                        <td>
                            ${r.status !== 'sent' ? `
                            <button class="action-btn whatsapp" onclick="sendWhatsApp(${r.id})">WhatsApp</button>
                            <a href="tel:${phone}" class="action-btn call" onclick="logCall(${r.id})">Call</a>
                            <button class="action-btn mark" onclick="markSent(${r.id})">Mark Sent</button>
                            ` : '<span style="color: #047857; font-weight: 500;">Completed</span>'}
                        </td>
                    </tr>
                `;
            }).join('');
        }
        
        function filterQueue(type, btn) {
            currentFilter = type;
            document.querySelectorAll('.queue-tab').forEach(t => t.classList.remove('active'));
            btn.classList.add('active');
            loadReminders();
        }
        
        async function sendWhatsApp(id) {
            try {
                const response = await fetch(BASE_PATH + '/api/staff/reminders/' + id + '/whatsapp', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                const result = await response.json();
                
                if (result.success && result.whatsapp_url) {
                    window.open(result.whatsapp_url, '_blank');
                    showToast('WhatsApp opened', 'success');
                    loadReminders();
                } else {
                    showToast(result.message || 'Failed to send WhatsApp', 'error');
                }
            } catch (error) {
                showToast('Failed to send WhatsApp', 'error');
            }
        }
        
        function logCall(id) {
            fetch(BASE_PATH + '/api/staff/reminders/' + id + '/call', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ notes: 'Call initiated' })
            }).then(() => {
                showToast('Call logged', 'success');
                loadReminders();
            }).catch(() => {});
            return true;
        }
        
        async function markSent(id) {
            try {
                const response = await fetch(BASE_PATH + '/api/staff/reminders/' + id + '/mark-sent', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                const result = await response.json();
                
                if (result.success) {
                    showToast('Reminder marked as sent', 'success');
                    loadReminders();
                } else {
                    showToast(result.message || 'Failed to mark as sent', 'error');
                }
            } catch (error) {
                showToast('Failed to mark as sent', 'error');
            }
        }
        
        function showToast(message, type = 'info') {
            const container = document.querySelector('.toast-container');
            const toast = document.createElement('div');
            toast.className = 'toast toast-' + type;
            toast.textContent = message;
            toast.style.cssText = 'padding: 12px 20px; border-radius: 8px; color: white; margin-bottom: 8px; animation: slideIn 0.3s ease; background: ' + (type === 'success' ? '#22c55e' : type === 'error' ? '#ef4444' : '#3b82f6');
            container.appendChild(toast);
            setTimeout(() => toast.remove(), 3000);
        }
        
        loadReminders();
    </script>
</body>
</html>
