<!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>Service Records - 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>
/* ================= EXISTING STYLES (UNCHANGED) ================= */

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

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

.service-table {
    width: 100%;
    border-collapse: collapse;
}

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

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

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

.status-sent {
    background: #dcfce7;
    color: #16a34a;
}

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

.status-call {
    background: #fee2e2;
    color: #dc2626;
}

.action-link {
    color: #FD4326;
    font-size: 13px;
    margin-right: 12px;
    cursor: pointer;
}

.action-link:hover {
    text-decoration: underline;
}

.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;
    top: 0;
    left: 0;
    right: 0;
    bottom: 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 (EXISTING BEHAVIOR) ================= */

@media (max-width: 768px) {

    .staff-sidebar {
        position: fixed;
        left: 0;
        top: 0;
        z-index: 100;
        transform: translateX(-100%);
    }

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

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

    .action-link {
        touch-action: manipulation;
        -webkit-tap-highlight-color: transparent;
    }

    .table-wrapper,
    table.service-table {
        display: none !important;
    }

    .mobile-cards {
        display: block !important;
    }

    .mobile-card {
        background: white;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 12px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    .mobile-card-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 12px;
    }

    .mobile-card-domain {
        font-weight: 700;
        font-size: 1rem;
        color: #1f2937;
    }

    .mobile-card-model {
        font-size: 0.85rem;
        color: #6b7280;
    }

    .mobile-card-row {
        display: flex;
        justify-content: space-between;
        padding: 6px 0;
        border-bottom: 1px solid #f3f4f6;
        font-size: 0.9rem;
    }

    .mobile-card-row:last-child {
        border-bottom: none;
    }

    .mobile-card-label {
        color: #6b7280;
    }

    .mobile-card-value {
        color: #1f2937;
        font-weight: 500;
    }

    .mobile-card-actions {
        display: flex;
        gap: 8px;
        margin-top: 12px;
        flex-wrap: wrap;
    }

    .mobile-card-actions .action-link {
        padding: 8px 14px;
        font-size: 0.85rem;
        border-radius: 6px;
        text-decoration: none;
        min-height: 36px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }
}

.mobile-cards {
    display: none;
}
</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" 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="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2" />
                    </svg>
                    Subscription Records
                </a>

                <a href="{{ @BASE_PATH }}/staff/reminders">
                    <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 Records
                    </h1>

                    <button onclick="openAddModal()"
                            class="btn btn-primary"
                            style="background: #FD4326;">
                        Add New Subscription
                    </button>
                </div>


                <!-- TABLE VIEW -->
                <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="service-table">

                            <thead>
                                <tr>
                                    <th>Asset ID</th>
                                    <th>Client</th>
                                    <th>Plan Type</th>
                                    <th>Start Date</th>
                                    <th>Renewal Date</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>

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

                        </table>

                    </div>

                </div>


                <!-- MOBILE VIEW -->
                <div class="mobile-cards" id="mobile-services">
                    <div style="text-align: center; padding: 40px; color: #6b7280;">
                        Loading subscription records...
                    </div>
                </div>

            </main>

        </div>
    </div>
    
    <div id="add-modal" class="modal-overlay">
        <div class="modal" style="max-width: 600px;">
            <div class="modal-header">
                <h3 class="modal-title">Add Service Record</h3>
                <button class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <form id="add-form">
                <div class="modal-body">
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group">
                            <label class="form-label">Customer Name *</label>
                            <input type="text" name="customer_name" class="form-input" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Customer Mobile *</label>
                            <input type="tel" name="customer_phone" class="form-input" required>
                        </div>
                    </div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px;">
                        <div class="form-group">
                            <label class="form-label">Domain *</label>
                            <input type="text" name="registration_number" class="form-input" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Make</label>
                            <input type="text" name="make" class="form-input">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Model</label>
                            <input type="text" name="model" class="form-input">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Service *</label>
                        <select name="service_type" class="form-input" required>
                            <option value="">Select Service</option>
                            <option value="Domain Registration">Domain Registration</option>
                            <option value="Web Hosting">Web Hosting</option>
                            <option value="Domain & Web Hosting">Domain & Web Hosting</option>
                            <option value="Domain/Hosting/Website Solutions">Domain/Hosting/Website Solutions</option>
                            <option value="Digital Infra & Solutions">Digital Infra & Solutions</option>
                        </select>
                    </div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div class="form-group">
                            <label class="form-label">Domain Expiry Date *</label>
                            <input type="date" name="service_date" class="form-input" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Next Due Date *</label>
                            <input type="date" name="next_service_date" class="form-input" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-input">
                            <option value="pending">Pending</option>
                            <option value="sent">Sent</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-input" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary" style="background: #FD4326;">Save Record</button>
                </div>
            </form>
        </div>
    </div>
    
    <div class="toast-container" id="toast-container"></div>
    
    <script>
        const BASE_PATH = '{{ @BASE_PATH }}';
        
        function toggleSidebar() {
            document.getElementById('staff-sidebar').classList.toggle('open');
            document.getElementById('sidebar-overlay').classList.toggle('active');
        }
        
        function showToast(message, type = 'info') {
            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);
        }
        
        function openAddModal() {
            document.getElementById('add-form').reset();
            document.querySelector('input[name="service_date"]').value = new Date().toISOString().split('T')[0];
            document.getElementById('add-modal').classList.add('active');
        }
        
        function closeModal() {
            document.getElementById('add-modal').classList.remove('active');
        }
        
        async function loadServices() {
            try {
                const response = await fetch(BASE_PATH + '/api/staff/services');
                const data = await response.json();
                
                if (data.success && data.services) {
                    const tbody = document.getElementById('services-body');
                    const mobileContainer = document.getElementById('mobile-services');
                    
                    if (data.services.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; padding: 40px; color: #6b7280;">No service records found</td></tr>';
                        mobileContainer.innerHTML = '<div style="text-align: center; padding: 40px; color: #6b7280;">No service records found</div>';
                    } else {
                        tbody.innerHTML = data.services.map(s => `
                            <tr data-id="${s.id}">
                                <td><strong>${s.registration_number}</strong><br><span style="color: #6b7280; font-size: 12px;">${s.make || ''} ${s.model || ''}</span></td>
                                <td>${s.customer_name}<br><span style="color: #6b7280; font-size: 12px;">${s.customer_phone}</span></td>
                                <td>${s.service_type}</td>
                                <td>${s.service_date}</td>
                                <td>${s.next_service_date}</td>
                                <td><span class="status-badge ${s.status === 'sent' ? 'status-sent' : 'status-pending'}">${s.status || 'Pending'}</span></td>
                                <td>
                                    <span class="action-link" onclick="editService(${s.id})">Edit</span>
                                    <span class="action-link" style="background: #dcfce7; color: #16a34a;" onclick="sendWhatsApp(${s.id}, '${s.customer_phone}', '${s.customer_name}', '${s.registration_number}', '${s.service_type}', '${s.next_service_date}')">WhatsApp</span>
                                    <span class="action-link" style="background: #dbeafe; color: #2563eb;" onclick="makeCall(${s.id}, '${s.customer_phone}')">Call</span>
                                    <span class="action-link" onclick="markSent(${s.id})">Mark Sent</span>
                                </td>
                            </tr>
                        `).join('');
                        
                        mobileContainer.innerHTML = data.services.map(s => `
                            <div class="mobile-card" data-id="${s.id}">
                                <div class="mobile-card-header">
                                    <div>
                                        <div class="mobile-card-domain">${s.registration_number}</div>
                                        <div class="mobile-card-model">${s.make || ''} ${s.model || ''}</div>
                                    </div>
                                    <span class="status-badge ${s.status === 'sent' ? 'status-sent' : 'status-pending'}">${s.status || 'Pending'}</span>
                                </div>
                                <div class="mobile-card-row">
                                    <span class="mobile-card-label">Customer</span>
                                    <span class="mobile-card-value">${s.customer_name}</span>
                                </div>
                                <div class="mobile-card-row">
                                    <span class="mobile-card-label">Phone</span>
                                    <span class="mobile-card-value">${s.customer_phone}</span>
                                </div>
                                <div class="mobile-card-row">
                                    <span class="mobile-card-label">Service</span>
                                    <span class="mobile-card-value">${s.service_type}</span>
                                </div>
                                <div class="mobile-card-row">
                                    <span class="mobile-card-label">Domain Expiry Date</span>
                                    <span class="mobile-card-value">${s.service_date}</span>
                                </div>
                                <div class="mobile-card-row">
                                    <span class="mobile-card-label">Next Due</span>
                                    <span class="mobile-card-value">${s.next_service_date}</span>
                                </div>
                                <div class="mobile-card-actions">
                                    <span class="action-link" onclick="editService(${s.id})" style="background: #e0e7ff; color: #4f46e5;">Edit</span>
                                    <span class="action-link" onclick="sendWhatsApp(${s.id}, '${s.customer_phone}', '${s.customer_name}', '${s.registration_number}', '${s.service_type}', '${s.next_service_date}')" style="background: #dcfce7; color: #16a34a;">WhatsApp</span>
                                    <span class="action-link" onclick="makeCall(${s.id}, '${s.customer_phone}')" style="background: #dbeafe; color: #2563eb;">Call</span>
                                    <span class="action-link" onclick="markSent(${s.id})" style="background: #fef3c7; color: #d97706;">Mark Sent</span>
                                </div>
                            </div>
                        `).join('');
                    }
                }
            } catch (error) {
                console.error('Error loading services:', error);
                document.getElementById('services-body').innerHTML = '<tr><td colspan="7" style="text-align: center; padding: 40px; color: #dc2626;">Failed to load services</td></tr>';
                document.getElementById('mobile-services').innerHTML = '<div style="text-align: center; padding: 40px; color: #dc2626;">Failed to load services</div>';
            }
        }
        
        document.getElementById('add-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const data = Object.fromEntries(formData);
            
            try {
                const response = await fetch(BASE_PATH + '/api/staff/services', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });
                const result = await response.json();
                
                if (result.success) {
                    showToast('Service record added successfully', 'success');
                    closeModal();
                    loadServices();
                } else {
                    showToast(result.message || 'Failed to add service record', 'error');
                }
            } catch (error) {
                showToast('Failed to add service record', 'error');
            }
        });
        
        async function markSent(id) {
            try {
                const response = await fetch(BASE_PATH + '/api/staff/services/' + id, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ status: 'sent' })
                });
                const result = await response.json();
                if (result.success) {
                    showToast('Marked as sent', 'success');
                    loadServices();
                }
            } catch (error) {
                showToast('Failed to update', 'error');
            }
        }
        
        async function sendWhatsApp(id, phone, customerName, vehicleNo, serviceType, dueDate) {
            if (!phone) {
                showToast('No phone number available', 'error');
                return;
            }
            
            const cleanPhone = phone.replace(/\D/g, '');
            const message = `Hi ${customerName}, this is a reminder for your ${serviceType} service for domain ${vehicleNo}. Your renewal date is due on ${dueDate}. Please contact us to schedule your appointment.`;
            const whatsappUrl = `https://wa.me/${cleanPhone}?text=${encodeURIComponent(message)}`;
            
            try {
                const response = await fetch(BASE_PATH + '/api/staff/services/' + id, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ status: 'sent' })
                });
                const result = await response.json();
                if (result.success) {
                    showToast('WhatsApp opened, status marked as sent', 'success');
                    loadServices();
                }
            } catch (error) {
                console.error('Error updating status:', error);
            }
            
            window.open(whatsappUrl, '_blank');
        }
        
        async function makeCall(id, phone) {
            if (!phone) {
                showToast('No phone number available', 'error');
                return;
            }
            
            try {
                const response = await fetch(BASE_PATH + '/api/staff/services/' + id, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ status: 'sent' })
                });
                const result = await response.json();
                if (result.success) {
                    showToast('Call initiated, status marked as sent', 'success');
                    loadServices();
                }
            } catch (error) {
                console.error('Error updating status:', error);
            }
            
            window.open('tel:' + phone, '_self');
        }
        
        function editService(id) {
            showToast('Edit functionality coming soon', 'info');
        }
        
        loadServices();
        
        if (new URLSearchParams(window.location.search).get('action') === 'add') {
            openAddModal();
        }
    </script>
</body>
</html>
