<?php
declare(strict_types=1);
require_once __DIR__ . '/../../api/lib.php';

hw_require_auth(['admin']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contacts - Herbal Wellness Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gray-50">
    <div class="flex h-screen bg-gray-100">
        <aside class="w-64 bg-gradient-to-b from-emerald-900 to-emerald-800 text-white shadow-lg overflow-y-auto">
            <div class="p-6 border-b border-emerald-700">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-emerald-300 rounded-lg flex items-center justify-center">
                        <i class="fas fa-leaf text-emerald-900 text-lg"></i>
                    </div>
                    <div>
                        <h1 class="font-bold text-lg">Herbal Admin</h1>
                        <p class="text-emerald-200 text-xs">Management Portal</p>
                    </div>
                </div>
            </div>
            <nav class="p-4 space-y-1">
                <a href="/atasteofafricanmarketplace/dashboard/admin/" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-chart-line w-5"></i><span>Dashboard</span>
                </a>
                <a href="/atasteofafricanmarketplace/dashboard/admin/bookings.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-calendar-check w-5"></i><span>Booking Calendar</span>
                </a>

                <a href="/atasteofafricanmarketplace/dashboard/admin/coaches.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-user-md w-5"></i><span>Coaches</span>
                </a>
                <a href="/atasteofafricanmarketplace/dashboard/admin/sales.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-chart-bar w-5"></i><span>Sales</span>
                </a>
                <div>
                    <button onclick="toggleCatalog(event)" class="w-full flex items-center justify-between px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                        <div class="flex items-center gap-3">
                            <i class="fas fa-boxes w-5"></i><span>Catalog</span>
                        </div>
                        <i id="catalog-chevron" class="fas fa-chevron-down text-xs"></i>
                    </button>
                    <div id="catalog-submenu" class="hidden">
                        <a href="/atasteofafricanmarketplace/dashboard/admin/products.php" class="flex items-center gap-3 px-4 py-2 pl-12 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                            <i class="fas fa-plus-circle w-5 text-sm"></i>
                            <span class="text-sm">Products</span>
                        </a>
                    </div>
                </div>
                <div class="my-4 border-t border-emerald-700"></div>
                <a href="/atasteofafricanmarketplace/dashboard/admin/customers.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-users w-5"></i><span>Customers & Leads</span>
                </a>
                <a href="/atasteofafricanmarketplace/dashboard/admin/contacts.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors bg-emerald-700 text-white">
                    <i class="fas fa-address-book w-5"></i><span>Contacts</span>
                </a>
                <a href="/atasteofafricanmarketplace/dashboard/admin/loyalty.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-gift w-5"></i><span>Loyalty Program</span>
                </a>
                <div class="my-4 border-t border-emerald-700"></div>
                <a href="/atasteofafricanmarketplace/dashboard/admin/analytics.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-chart-pie w-5"></i><span>Analytics</span>
                </a>
                <a href="/atasteofafricanmarketplace/dashboard/admin/automations.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-robot w-5"></i><span>Automations</span>
                </a>
                <div class="my-4 border-t border-emerald-700"></div>
                <a href="/atasteofafricanmarketplace/dashboard/admin/settings.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-cog w-5"></i><span>Settings</span>
                </a>
                <a href="/atasteofafricanmarketplace/dashboard/admin/cms.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-file-alt w-5"></i><span>CMS</span>
                </a>
                <a href="/atasteofafricanmarketplace/dashboard/admin/developers.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-code w-5"></i><span>Developers</span>
                </a>
            </nav>
        </aside>

        <div class="flex-1 flex flex-col overflow-hidden">
            <header class="bg-white border-b border-gray-200 px-8 py-4 shadow-sm">
                <h1 class="text-2xl font-bold text-gray-900">Contacts</h1>
            </header>
            <main class="flex-1 overflow-auto p-8">
                <div class="mb-6 flex justify-between items-center">
                    <div class="flex gap-4 flex-1">
                        <div class="relative flex-1 max-w-md">
                            <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                            <input type="text" id="searchInput" placeholder="Search contacts..." 
                                   class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent">
                        </div>
                    </div>
                    <button id="importBtn" class="px-6 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors flex items-center gap-2">
                        <i class="fas fa-file-import"></i>
                        <span>Import CSV</span>
                    </button>
                </div>

                <div class="bg-white rounded-lg shadow">
                    <div id="loadingState" class="p-8 text-center">
                        <i class="fas fa-spinner fa-spin text-4xl text-emerald-600 mb-4"></i>
                        <p class="text-gray-600">Loading contacts...</p>
                    </div>
                    
                    <div id="contactsTable" class="hidden">
                        <div class="overflow-x-auto">
                            <table class="w-full">
                                <thead class="bg-gray-50 border-b">
                                    <tr>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Email</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Phone</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Location</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Last Activity</th>
                                    </tr>
                                </thead>
                                <tbody id="contactsBody" class="bg-white divide-y divide-gray-200">
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="px-6 py-4 border-t flex items-center justify-between">
                            <div class="text-sm text-gray-600">
                                Showing <span id="showingFrom">0</span> to <span id="showingTo">0</span> of <span id="totalContacts">0</span> contacts
                            </div>
                            <div class="flex gap-2" id="pagination"></div>
                        </div>
                    </div>

                    <div id="emptyState" class="hidden p-8 text-center">
                        <i class="fas fa-address-book text-6xl text-gray-300 mb-4"></i>
                        <h2 class="text-2xl font-bold text-gray-900 mb-2">No Contacts Yet</h2>
                        <p class="text-gray-600 mb-6">Import your contacts to get started</p>
                        <button onclick="document.getElementById('importBtn').click()" 
                                class="px-6 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors">
                            Import CSV File
                        </button>
                    </div>
                </div>
            </main>
        </div>
    </div>
    <script>
    let currentPage = 1;
    let searchTimeout = null;

    // Load contacts
    async function loadContacts(page = 1, search = '') {
        try {
            document.getElementById('loadingState').classList.remove('hidden');
            document.getElementById('contactsTable').classList.add('hidden');
            document.getElementById('emptyState').classList.add('hidden');

            const response = await fetch(`/atasteofafricanmarketplace/api/contacts/list.php?page=${page}&search=${encodeURIComponent(search)}`);
            const data = await response.json();

            if (!data.success) {
                throw new Error(data.error);
            }

            document.getElementById('loadingState').classList.add('hidden');

            if (data.contacts.length === 0 && page === 1 && !search) {
                document.getElementById('emptyState').classList.remove('hidden');
                return;
            }

            document.getElementById('contactsTable').classList.remove('hidden');
            
            const tbody = document.getElementById('contactsBody');
            tbody.innerHTML = data.contacts.map(contact => `
                <tr class="hover:bg-gray-50">
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            <div class="w-10 h-10 bg-emerald-100 rounded-full flex items-center justify-center text-emerald-600 font-semibold">
                                ${(contact.first_name?.[0] || contact.email?.[0] || '?').toUpperCase()}
                            </div>
                            <div class="ml-4">
                                <div class="text-sm font-medium text-gray-900">${contact.first_name || ''} ${contact.last_name || ''}</div>
                                ${contact.company ? `<div class="text-xs text-gray-500">${contact.company}</div>` : ''}
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-900">${contact.email || '-'}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-900">${contact.phone || '-'}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-900">${contact.address_city || ''} ${contact.address_state || ''}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                            contact.email_subscriber_status === 'Subscribed' ? 'bg-green-100 text-green-800' : 
                            contact.email_subscriber_status === 'Unsubscribed' ? 'bg-red-100 text-red-800' : 
                            'bg-gray-100 text-gray-800'
                        }">
                            ${contact.email_subscriber_status}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        ${contact.last_activity || '-'}
                    </td>
                </tr>
            `).join('');

            // Update pagination
            const { pagination } = data;
            document.getElementById('showingFrom').textContent = pagination.total > 0 ? ((page - 1) * pagination.per_page + 1) : 0;
            document.getElementById('showingTo').textContent = Math.min(page * pagination.per_page, pagination.total);
            document.getElementById('totalContacts').textContent = pagination.total;

            const paginationDiv = document.getElementById('pagination');
            paginationDiv.innerHTML = '';
            
            if (pagination.total_pages > 1) {
                for (let i = 1; i <= pagination.total_pages; i++) {
                    if (i === 1 || i === pagination.total_pages || Math.abs(i - page) <= 2) {
                        const btn = document.createElement('button');
                        btn.textContent = i;
                        btn.className = `px-3 py-1 rounded ${i === page ? 'bg-emerald-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'}`;
                        btn.onclick = () => loadContacts(i, search);
                        paginationDiv.appendChild(btn);
                    } else if (Math.abs(i - page) === 3) {
                        const span = document.createElement('span');
                        span.textContent = '...';
                        span.className = 'px-2 text-gray-500';
                        paginationDiv.appendChild(span);
                    }
                }
            }

        } catch (error) {
            console.error('Error loading contacts:', error);
            alert('Error loading contacts: ' + error.message);
        }
    }

    // Import CSV
    document.getElementById('importBtn').addEventListener('click', async () => {
        if (!confirm('Import contacts from CSV file? This will add new contacts and skip duplicates.')) {
            return;
        }

        try {
            const btn = document.getElementById('importBtn');
            const originalHTML = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Importing...';
            btn.disabled = true;

            const response = await fetch('/atasteofafricanmarketplace/api/contacts/import.php', {
                method: 'POST'
            });
            const data = await response.json();

            if (!data.success) {
                throw new Error(data.error);
            }

            alert(data.message);
            loadContacts();

        } catch (error) {
            console.error('Error importing contacts:', error);
            alert('Error importing contacts: ' + error.message);
        } finally {
            const btn = document.getElementById('importBtn');
            btn.innerHTML = '<i class="fas fa-file-import"></i> Import CSV';
            btn.disabled = false;
        }
    });

    // Search
    document.getElementById('searchInput').addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            loadContacts(1, e.target.value);
        }, 300);
    });

    // Initial load
    loadContacts();

    function toggleCatalog(event) {
        event.preventDefault();
        const submenu = document.getElementById('catalog-submenu');
        const chevron = document.getElementById('catalog-chevron');
        
        if (submenu.classList.contains('hidden')) {
            submenu.classList.remove('hidden');
            chevron.classList.remove('fa-chevron-down');
            chevron.classList.add('fa-chevron-up');
        } else {
            submenu.classList.add('hidden');
            chevron.classList.remove('fa-chevron-up');
            chevron.classList.add('fa-chevron-down');
        }
    }
    </script>
</body>
</html>
