<!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>
/* =====================================================
   DESKTOP – KEEP AS IS
===================================================== */

.queue-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.queue-tab {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
  font-size: 14px;
  border: none;
  cursor: pointer;
  background: #e5e7eb;
  color: #374151;
}

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

.reminder-table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
}

.reminder-table th,
.reminder-table td {
  padding: 16px;
  font-size: 14px;
  border-bottom: 1px solid #eee;
}

.action-btn {
  padding: 8px 14px;
  border-radius: 6px;
  font-size: 12px;
  border: none;
  cursor: pointer;
}

.action-btn.whatsapp { background: #22c55e; color: #fff; }
.action-btn.call { background: #f97316; color: #fff; }
.action-btn.mark { background: #3b82f6; color: #fff; }

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
}

.status-badge.pending { background: #fef3c7; color: #b45309; }
.status-badge.sent { background: #d1fae5; color: #047857; }
.status-badge.overdue { background: #fee2e2; color: #b91c1c; }

/* =====================================================
   🔥 MOBILE – ABSOLUTE RESET (THIS FIXES BLANK PAGE)
===================================================== */

@media (max-width: 768px) {

  /* 🚨 HARD RESET – THIS IS THE KEY */
  html, body {
    height: auto !important;
    min-height: 100% !important;
    overflow-x: hidden !important;
  }

  .app-container,
  .main-content,
  .content-area,
  .page-transition {
    display: block !important;
    height: auto !important;
    min-height: auto !important;
    overflow: visible !important;
    transform: none !important;
    opacity: 1 !important;
    position: relative !important;
  }

  /* Disable animations that collapse height */
  .page-transition {
    animation: none !important;
    transition: none !important;
  }

  /* Sidebar safety */
  .sidebar {
    position: fixed;
    height: 100vh;
    z-index: 1000;
  }

  /* Header visible */
  .header {
    position: sticky;
    top: 0;
    z-index: 1001;
    background: #fff;
  }

  /* ===============================
     TABLE → CARD VIEW
  =============================== */

  .glass-card,
  .table-wrapper {
    overflow: visible !important;
  }

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

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

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

  .reminder-table tr {
    background: #fff;
    margin-bottom: 16px;
    border-radius: 14px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.08);
  }

  .reminder-table td {
    display: flex !important;
    justify-content: space-between;
    gap: 12px;
    padding: 14px 16px;
    font-size: 14px;
    border-bottom: 1px solid #eee;
    text-align: right;
  }

  .reminder-table td:last-child {
    border-bottom: none;
  }

  .reminder-table td::before {
    font-weight: 600;
    font-size: 12px;
    color: #374151;
    text-transform: uppercase;
    text-align: left;
  }

  .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"; }

  /* Buttons compact */
  .action-btn {
    padding: 6px 10px;
    font-size: 12px;
    margin-left: 6px;
  }
}

/* =========================================================
   🚨 HARD MOBILE LAYOUT RESET – FINAL FIX
   This OVERRIDES layout.css completely on mobile
========================================================= */

@media (max-width: 768px) {

  /* FULL RESET */
  html, body {
    height: auto !important;
    min-height: 100% !important;
    overflow-x: hidden !important;
    overflow-y: auto !important;
  }

  /* Kill flex + height traps */
  .app-container {
    display: block !important;
    height: auto !important;
    min-height: 100vh !important;
    overflow: visible !important;
  }

  .main-content {
    display: block !important;
    height: auto !important;
    min-height: auto !important;
    overflow: visible !important;
    position: relative !important;
  }

  /* 🚨 THIS IS THE KILL SWITCH */
  .content-area,
  .content-area.page-transition {
    display: block !important;
    height: auto !important;
    min-height: auto !important;
    max-height: none !important;
    overflow: visible !important;

    transform: none !important;
    opacity: 1 !important;
    position: relative !important;
  }

  /* Disable SPA animation wrapper */
  .page-transition {
    animation: none !important;
    transition: none !important;
  }

  /* Table containers */
  .glass-card,
  .table-wrapper {
    height: auto !important;
    max-height: none !important;
    overflow: visible !important;
  }

  /* Safety */
  * {
    max-height: none !important;
  }
}

</style>



</head>
<body>
    <check if="{{ @is_impersonating }}">
        <true>
            <div style="background: linear-gradient(90deg, #FD4326, #6d28d9); color: white; padding: 12px 20px; text-align: center; font-weight: 500;">
                You are viewing as {{ @user.name }}. 
                <a href="{{ @BASE_PATH }}/super-admin/return" style="color: #fbbf24; text-decoration: underline; margin-left: 10px;">Return to Super Admin</a>
            </div>
        </true>
    </check>

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

        <aside class="sidebar">
            <div class="sidebar-header">
                <img src="{{ @ASSET_PATH }}/images/logo.png" alt="Logo" class="sidebar-logo" onerror="this.style.display='none'">
                <div class="sidebar-brand">
                    <h1>INWAY Service Hub</h1>
                </div>
            </div>

            <nav class="sidebar-nav">
                <a href="{{ @BASE_PATH }}/company" class="nav-item">
                    <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>
                    <span>Dashboard</span>
                </a>

                <a href="{{ @BASE_PATH }}/company/services" class="nav-item">
                    <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 12h6m-6 4h6" />
                    </svg>
                    <span>Subscriptions</span>
                </a>

                <a href="{{ @BASE_PATH }}/company/reminders" class="nav-item 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>
                    <span>Renewal Management</span>
                </a>

                <a href="{{ @BASE_PATH }}/company/settings" class="nav-item">
                    <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 12a3 3 0 11-6 0" />
                    </svg>
                    <span>System Settings</span>
                </a>
            </nav>

            <div class="sidebar-footer">
                <div class="user-info">
                    <div class="user-avatar">{{ substr(@user.name, 0, 1) }}</div>
                    <div class="user-details">
                        <div class="user-name">{{ @user.name }}</div>
                        <div class="user-role">Service Admin</div>
                    </div>
                </div>
                <a href="{{ @BASE_PATH }}/logout" class="btn btn-secondary btn-sm" style="width: 100%; margin-top: 12px;">Sign Out</a>
            </div>
        </aside>

        <main class="main-content">
            <header class="header">
                <div class="header-left">
                    <button class="menu-toggle" onclick="toggleSidebar()">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                        </svg>
                    </button>
                    <h1 class="page-title">Renewal Management</h1>
                </div>
            </header>

            <div class="content-area page-transition">

                <div class="queue-tabs">
                    <button class="queue-tab active" data-filter="all" onclick="filterQueue('all', this)">All Renewals</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>

                <div class="glass-card" style="padding: 0; overflow: hidden; border-radius: 16px;">
                    <div class="table-wrapper">
                        <table class="reminder-table">
                            <thead>
                                <tr>
                                    <th>Domain</th>
                                    <th>Client</th>
                                    <th>Phone</th>
                                    <th>Service Category</th>
                                    <th>Renewal Date</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>

                            <tbody id="reminders-tbody">
                                <tr class="loading-row">
                                    <td colspan="7">Loading renewals...</td>
                                </tr>
                            </tbody>

                        </table>
                    </div>
                </div>

            </div>
        </main>
    </div>
    <div id="toast-container"></div>
    
    <script src="{{ @ASSET_PATH }}/js/app.js"></script>
    <script>
        const BASE_PATH = '{{ @BASE_PATH }}';
        let allReminders = [];
        let currentFilter = 'all';
        
       
        
        function showToast(message, type) {
            const container = document.getElementById('toast-container');
            const toast = document.createElement('div');
            toast.className = 'toast ' + type;
            toast.textContent = message;
            container.appendChild(toast);
            setTimeout(() => toast.remove(), 3000);
        }
        
        async function loadReminders() {
            try {
                let url = BASE_PATH + '/api/company/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();
                }
            } catch (error) {
                console.error('Error loading reminders:', error);
                document.getElementById('reminders-tbody').innerHTML = 
                    '<tr class="empty-row"><td colspan="7">Error loading reminders</td></tr>';
            }
        }
        
        function renderReminders() {
            const tbody = document.getElementById('reminders-tbody');
            let reminders = allReminders;
            
            if (reminders.length === 0) {
                tbody.innerHTML = '<tr class="empty-row"><td colspan="7">No pending reminders found</td></tr>';
                return;
            }
            
            tbody.innerHTML = reminders.map(r => {
                const isOverdue = new Date(r.next_service_date) < new Date();
                const statusClass = r.status === 'sent' ? 'sent' : (isOverdue ? 'overdue' : 'pending');
                const statusText = r.status === 'sent' ? 'Reminder Sent' : (isOverdue ? 'Overdue' : 'Pending');
                const rowClass = r.status === 'sent' ? 'style="background-color: #d1fae5;"' : '';
                
                return `
                    <tr data-id="${r.id}" ${rowClass}>
                        <td>
                            <div class="domain-info">${r.registration_number || ''}</div>
                            <div class="domain-details">${r.make || ''} ${r.model || ''}</div>
                        </td>
                        <td>
                            <div class="customer-name">${r.customer_name || ''}</div>
                        </td>
                        <td>
                            <div class="customer-phone">${r.customer_phone || ''}</div>
                        </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:${(r.customer_phone || '').replace(/[^0-9+]/g, '')}" class="action-btn call" onclick="logCallAction(${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(filter, btn) {
            currentFilter = filter;
            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/company/reminders/' + id + '/whatsapp', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                const result = await response.json();
                
                if (result.success) {
                    showToast('WhatsApp reminder logged', 'success');
                    if (result.whatsapp_url) {
                        // Use window.open for cross-browser/iframe compatibility
                        window.open(result.whatsapp_url, '_blank');
                    }
                    loadReminders();
                } else {
                    showToast(result.message || 'Failed to send WhatsApp', 'error');
                }
            } catch (error) {
                showToast('Failed to send WhatsApp', 'error');
            }
        }
        
        // FIXED: Direct WhatsApp open for mobile compatibility
        function openWhatsAppDirect(phone, message) {
            let cleanPhone = phone.replace(/[^0-9+]/g, '');
            if (!cleanPhone.startsWith('+')) {
                if (cleanPhone.startsWith('0')) {
                    cleanPhone = '91' + cleanPhone.substring(1);
                } else if (!cleanPhone.startsWith('91')) {
                    cleanPhone = '91' + cleanPhone;
                }
            } else {
                cleanPhone = cleanPhone.replace('+', '');
            }
            const encodedMessage = encodeURIComponent(message || '');
            const whatsappUrl = 'https://wa.me/' + cleanPhone + (encodedMessage ? '?text=' + encodedMessage : '');
            window.location.href = whatsappUrl;
        }
        
        function logCallAction(id) {
            // Log the call, but don't prevent the tel: link from working
            fetch(BASE_PATH + '/api/company/reminders/' + id + '/call', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ notes: 'Call initiated' })
            }).then(() => showToast('Call logged', 'success')).catch(() => {});
            // Return true to allow the tel: link to proceed
            return true;
        }
        
        async function markSent(id) {
            try {
                const response = await fetch(BASE_PATH + '/api/company/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');
            }
        }
        
        document.addEventListener('DOMContentLoaded', loadReminders);
    </script>
</body>
</html>
