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

hw_require_auth(['admin']);

// Get search/filter parameters
$search = hw_sanitize_string($_GET['search'] ?? '');
$limit = 50;
$offset = (int)($_GET['page'] ?? 0) * $limit;

try {
    $pdo = hw_db();

    // Count total
    $countQuery = 'SELECT COUNT(*) as count FROM users WHERE id IN (SELECT DISTINCT user_id FROM user_roles WHERE role_id = (SELECT id FROM roles WHERE name = "client"))';
    if ($search) {
        $countQuery .= ' AND (first_name LIKE ? OR last_name LIKE ? OR email LIKE ?)';
    }
    $stmt = $pdo->prepare($countQuery);
    if ($search) {
        $searchTerm = "%$search%";
        $stmt->execute([$searchTerm, $searchTerm, $searchTerm]);
    } else {
        $stmt->execute();
    }
    $totalCount = (int)($stmt->fetch()['count'] ?? 0);
    $totalPages = ceil($totalCount / $limit);

    // Get customers
    $query = 'SELECT u.id, u.first_name, u.last_name, u.email, u.status, u.created_at FROM users u WHERE u.id IN (SELECT DISTINCT user_id FROM user_roles WHERE role_id = (SELECT id FROM roles WHERE name = "client"))';
    
    if ($search) {
        $query .= ' AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ?)';
    }
    
    $query .= ' ORDER BY u.created_at DESC LIMIT ? OFFSET ?';
    
    $stmt = $pdo->prepare($query);
    $params = [];
    if ($search) {
        $searchTerm = "%$search%";
        $params = [$searchTerm, $searchTerm, $searchTerm, $limit, $offset];
    } else {
        $params = [$limit, $offset];
    }
    $stmt->execute($params);
    $customers = $stmt->fetchAll();
} catch (Exception $e) {
    $customers = [];
    $totalPages = 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customers - 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">
        <!-- Sidebar -->
        <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 bg-emerald-700 text-white">
                    <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 text-emerald-100 hover:bg-emerald-700/50">
                    <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>

        <!-- Main Content -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <header class="bg-white border-b border-gray-200 px-8 py-4 shadow-sm">
                <div class="flex items-center justify-between">
                    <h1 class="text-2xl font-bold text-gray-900">Customers & Leads</h1>
                    <button class="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors">
                        <i class="fas fa-plus mr-2"></i>Add Customer
                    </button>
                </div>
            </header>

            <main class="flex-1 overflow-auto p-8">
                <!-- Search & Filters -->
                <div class="bg-white rounded-lg shadow p-6 mb-6">
                    <form method="GET" class="flex gap-4 items-end">
                        <div class="flex-1">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Search</label>
                            <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                                   placeholder="Search by name or email..." 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                        </div>
                        <button type="submit" class="px-6 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors">
                            <i class="fas fa-search mr-2"></i>Search
                        </button>
                    </form>
                </div>

                <!-- Customers Table -->
                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Name</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Email</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Joined</th>
                                <th class="px-6 py-3 text-right text-xs font-semibold text-gray-700 uppercase">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php if (!empty($customers)): ?>
                                <?php foreach ($customers as $customer): ?>
                                <tr class="hover:bg-gray-50 transition-colors">
                                    <td class="px-6 py-4 text-sm font-medium text-gray-900">
                                        <div class="flex items-center gap-3">
                                            <div class="w-8 h-8 bg-emerald-100 rounded-full flex items-center justify-center">
                                                <i class="fas fa-user text-emerald-600 text-xs"></i>
                                            </div>
                                            <?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-600"><?php echo htmlspecialchars($customer['email']); ?></td>
                                    <td class="px-6 py-4 text-sm">
                                        <span class="inline-block px-3 py-1 bg-<?php echo $customer['status'] === 'active' ? 'emerald' : 'gray'; ?>-100 text-<?php echo $customer['status'] === 'active' ? 'emerald' : 'gray'; ?>-700 text-xs font-semibold rounded-full">
                                            <?php echo ucfirst($customer['status']); ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-600"><?php echo (new DateTime($customer['created_at']))->format('M d, Y'); ?></td>
                                    <td class="px-6 py-4 text-right text-sm">
                                        <a href="#" class="text-emerald-600 hover:text-emerald-700 font-medium">View</a>
                                        <span class="text-gray-300 mx-2">•</span>
                                        <a href="#" class="text-blue-600 hover:text-blue-700 font-medium">Edit</a>
                                        <span class="text-gray-300 mx-2">•</span>
                                        <a href="#" class="text-red-600 hover:text-red-700 font-medium">Delete</a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                            <tr>
                                <td colspan="5" class="px-6 py-8 text-center text-gray-600">
                                    <i class="fas fa-users text-4xl text-gray-300 mb-4 block"></i>
                                    No customers found
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                <div class="mt-6 flex items-center justify-between">
                    <p class="text-sm text-gray-600">Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $totalCount); ?> of <?php echo $totalCount; ?> customers</p>
                    <div class="flex gap-2">
                        <?php if ($offset > 0): ?>
                        <a href="?page=<?php echo ($offset / $limit) - 1; ?>" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        <?php endif; ?>
                        
                        <?php for ($i = 0; $i < $totalPages; $i++): ?>
                        <a href="?page=<?php echo $i; ?>" class="px-4 py-2 rounded-lg <?php echo ($offset / $limit) == $i ? 'bg-emerald-600 text-white' : 'border border-gray-300 hover:bg-gray-50'; ?>">
                            <?php echo $i + 1; ?>
                        </a>
                        <?php endfor; ?>
                        
                        <?php if ($offset + $limit < $totalCount): ?>
                        <a href="?page=<?php echo ($offset / $limit) + 1; ?>" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    <script>
    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>
