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

hw_require_auth(['admin']);
$pageTitle = 'Coaches';
$pageSection = 'coaches';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?> - 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 Navigation (inline copy from layout.php to avoid double HTML shells) -->
        <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 <?php echo ($pageSection === 'home' ? 'bg-emerald-700 text-white' : '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 <?php echo ($pageSection === 'bookings' ? 'bg-emerald-700 text-white' : '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/sales.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors <?php echo ($pageSection === 'sales' ? 'bg-emerald-700 text-white' : 'text-emerald-100 hover:bg-emerald-700/50'); ?>">
                    <i class="fas fa-chart-bar w-5"></i><span>Sales</span>
                </a>
                <a href="/atasteofafricanmarketplace/dashboard/admin/catalog.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors <?php echo ($pageSection === 'catalog' ? 'bg-emerald-700 text-white' : 'text-emerald-100 hover:bg-emerald-700/50'); ?>">
                    <i class="fas fa-boxes w-5"></i><span>Catalog</span>
                </a>
                <a href="/atasteofafricanmarketplace/dashboard/admin/products.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors <?php echo ($pageSection === 'products' ? 'bg-emerald-700 text-white' : 'text-emerald-100 hover:bg-emerald-700/50'); ?>">
                    <i class="fas fa-plus-circle w-5"></i><span>Products</span>
                </a>
                <a href="/atasteofafricanmarketplace/dashboard/admin/coaches.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors <?php echo ($pageSection === 'coaches' ? 'bg-emerald-700 text-white' : 'text-emerald-100 hover:bg-emerald-700/50'); ?>">
                    <i class="fas fa-user-md w-5"></i><span>Coaches</span>
                </a>
                <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 <?php echo ($pageSection === 'customers' ? 'bg-emerald-700 text-white' : '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 <?php echo ($pageSection === 'contacts' ? 'bg-emerald-700 text-white' : '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 <?php echo ($pageSection === 'loyalty' ? 'bg-emerald-700 text-white' : '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 <?php echo ($pageSection === 'analytics' ? 'bg-emerald-700 text-white' : '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 <?php echo ($pageSection === 'automations' ? 'bg-emerald-700 text-white' : '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 <?php echo ($pageSection === 'settings' ? 'bg-emerald-700 text-white' : '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 <?php echo ($pageSection === 'cms' ? 'bg-emerald-700 text-white' : '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 <?php echo ($pageSection === 'developers' ? 'bg-emerald-700 text-white' : 'text-emerald-100 hover:bg-emerald-700/50'); ?>">
                    <i class="fas fa-code w-5"></i><span>Developer Tools</span>
                </a>
            </nav>
        </aside>

        <main class="flex-1 overflow-y-auto p-8">
            <div class="max-w-6xl mx-auto">
                <div class="flex items-center justify-between mb-6">
                    <div>
                        <h1 class="text-3xl font-bold text-gray-900">Coaches</h1>
                        <p class="text-gray-600 mt-1">Add new coaches and manage existing profiles</p>
                    </div>
                    <button id="refreshBtn" class="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700" onclick="loadCoaches()">
                        <i class="fas fa-rotate mr-2"></i>Refresh
                    </button>
                </div>

                <div class="grid lg:grid-cols-2 gap-6">
                    <div class="bg-white rounded-xl shadow border border-gray-200 p-6">
                        <div class="flex items-center gap-3 mb-4">
                            <div class="w-10 h-10 bg-emerald-100 text-emerald-700 rounded-full grid place-items-center">
                                <i class="fas fa-user-plus"></i>
                            </div>
                            <div>
                                <h2 class="text-xl font-semibold text-gray-900">Add Coach</h2>
                                <p class="text-sm text-gray-600">Creates user + coach profile (admin only)</p>
                            </div>
                        </div>

                        <div class="space-y-4">
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">First Name</label>
                                    <input id="first_name" class="w-full border rounded-lg px-3 py-2" placeholder="Ava">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Last Name</label>
                                    <input id="last_name" class="w-full border rounded-lg px-3 py-2" placeholder="Rivera">
                                </div>
                            </div>
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                                    <input id="email" type="email" class="w-full border rounded-lg px-3 py-2" placeholder="coach@example.com">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Password</label>
                                    <input id="password" type="password" class="w-full border rounded-lg px-3 py-2" placeholder="Min 8 chars">
                                </div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Display Name</label>
                                <input id="display_name" class="w-full border rounded-lg px-3 py-2" placeholder="Coach Ava">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Bio</label>
                                <textarea id="bio" rows="3" class="w-full border rounded-lg px-3 py-2" placeholder="Short intro"></textarea>
                            </div>
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Certifications</label>
                                    <input id="certifications" class="w-full border rounded-lg px-3 py-2" placeholder="e.g. ND, RDN">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Hourly Rate (USD)</label>
                                    <input id="hourly_rate" type="number" step="0.01" class="w-full border rounded-lg px-3 py-2" placeholder="120">
                                </div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Expertise (comma separated)</label>
                                <input id="expertise" class="w-full border rounded-lg px-3 py-2" placeholder="nutrition, herbalism, breathwork">
                            </div>

                            <div class="border-t pt-4">
                                <div class="flex items-center justify-between mb-3">
                                    <div>
                                        <p class="text-sm font-semibold text-gray-800">Seed Availability (optional)</p>
                                        <p class="text-xs text-gray-500">Creates default availability slots</p>
                                    </div>
                                    <label class="flex items-center gap-2 text-sm text-gray-700">
                                        <input type="checkbox" id="seed_availability" class="h-4 w-4 text-emerald-600 border-gray-300 rounded">
                                        Enable
                                    </label>
                                </div>
                                <div id="availability_fields" class="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm" style="display:none;">
                                    <div>
                                        <label class="block text-gray-700 mb-1">Timezone</label>
                                        <select id="tz" class="w-full border rounded-lg px-3 py-2">
                                            <option value="America/New_York">Eastern (ET)</option>
                                            <option value="America/Chicago">Central (CT)</option>
                                            <option value="America/Denver">Mountain (MT)</option>
                                            <option value="America/Los_Angeles">Pacific (PT)</option>
                                        </select>
                                    </div>
                                    <div class="grid grid-cols-2 gap-2">
                                        <div>
                                            <label class="block text-gray-700 mb-1">Start</label>
                                            <input id="start_time" type="time" value="09:00" class="w-full border rounded-lg px-2 py-2">
                                        </div>
                                        <div>
                                            <label class="block text-gray-700 mb-1">End</label>
                                            <input id="end_time" type="time" value="17:00" class="w-full border rounded-lg px-2 py-2">
                                        </div>
                                    </div>
                                    <div class="sm:col-span-2">
                                        <label class="block text-gray-700 mb-1">Working Days</label>
                                        <div class="flex flex-wrap gap-2 text-xs">
                                            <?php foreach (['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] as $day): ?>
                                                <label class="flex items-center gap-1 px-3 py-2 border rounded-lg">
                                                    <input type="checkbox" class="day-check" value="<?php echo $day; ?>" <?php echo in_array($day, ['Monday','Tuesday','Wednesday','Thursday','Friday']) ? 'checked' : ''; ?>>
                                                    <span><?php echo $day; ?></span>
                                                </label>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="flex justify-end">
                                <button onclick="createCoach()" class="px-4 py-3 bg-emerald-600 text-white rounded-lg font-semibold hover:bg-emerald-700">
                                    <i class="fas fa-save mr-2"></i>Create Coach
                                </button>
                            </div>
                            <p id="form_status" class="text-sm text-gray-600"></p>
                        </div>
                    </div>

                    <div class="bg-white rounded-xl shadow border border-gray-200 p-6">
                        <div class="flex items-center gap-3 mb-4">
                            <div class="w-10 h-10 bg-blue-100 text-blue-700 rounded-full grid place-items-center">
                                <i class="fas fa-users"></i>
                            </div>
                            <div>
                                <h2 class="text-xl font-semibold text-gray-900">Existing Coaches</h2>
                                <p class="text-sm text-gray-600">Loaded from database</p>
                            </div>
                        </div>
                        <div id="coach_list" class="divide-y divide-gray-100 text-sm">
                            <div class="py-6 text-center text-gray-500" id="coach_loading">Loading...</div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
    const statusEl = document.getElementById('form_status');
    const availFields = document.getElementById('availability_fields');
    const seedToggle = document.getElementById('seed_availability');
    seedToggle.addEventListener('change', () => {
        availFields.style.display = seedToggle.checked ? 'grid' : 'none';
    });

    async function loadCoaches() {
        const listEl = document.getElementById('coach_list');
        listEl.innerHTML = '<div class="py-6 text-center text-gray-500">Loading...</div>';
        try {
            const res = await fetch('/atasteofafricanmarketplace/api/coaches/list.php?limit=50');
            const data = await res.json();
            if (!data || !data.coaches) {
                listEl.innerHTML = '<div class="py-6 text-center text-red-600">Unable to load coaches</div>';
                return;
            }
            if (data.coaches.length === 0) {
                listEl.innerHTML = '<div class="py-6 text-center text-gray-500">No coaches found</div>';
                return;
            }
            listEl.innerHTML = data.coaches.map(c => {
                const exp = Array.isArray(c.expertise) ? c.expertise.join(', ') : '';
                return `
                    <div class="py-3 flex items-start justify-between">
                        <div>
                            <div class="font-semibold text-gray-900">${c.display_name}</div>
                            <div class="text-gray-600">${c.first_name} ${c.last_name}</div>
                            <div class="text-xs text-gray-500">${exp}</div>
                        </div>
                        <div class="text-right text-xs text-gray-500">
                            ${c.has_availability ? '<span class="px-2 py-1 bg-green-100 text-green-700 rounded-full">Availability</span>' : '<span class="px-2 py-1 bg-amber-100 text-amber-700 rounded-full">No availability</span>'}
                        </div>
                    </div>`;
            }).join('');
        } catch (err) {
            console.error(err);
            listEl.innerHTML = '<div class="py-6 text-center text-red-600">Error loading coaches</div>';
        }
    }

    async function createCoach() {
        statusEl.textContent = '';
        const payload = {
            first_name: document.getElementById('first_name').value.trim(),
            last_name: document.getElementById('last_name').value.trim(),
            email: document.getElementById('email').value.trim(),
            password: document.getElementById('password').value,
            display_name: document.getElementById('display_name').value.trim(),
            bio: document.getElementById('bio').value.trim(),
            certifications: document.getElementById('certifications').value.trim(),
            hourly_rate: document.getElementById('hourly_rate').value ? parseFloat(document.getElementById('hourly_rate').value) : null,
            expertise: document.getElementById('expertise').value.split(',').map(x => x.trim()).filter(Boolean)
        };

        if (seedToggle.checked) {
            const days = Array.from(document.querySelectorAll('.day-check:checked')).map(cb => cb.value);
            payload.availability = {
                timezone: document.getElementById('tz').value,
                start_time: document.getElementById('start_time').value || '09:00',
                end_time: document.getElementById('end_time').value || '17:00',
                working_days: days
            };
        }

        statusEl.textContent = 'Saving...';
        try {
            const res = await fetch('/atasteofafricanmarketplace/api/coaches/create.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const data = await res.json();
            if (data.success) {
                statusEl.textContent = 'Coach created successfully';
                loadCoaches();
            } else {
                statusEl.textContent = 'Error: ' + (data.message || data.error || 'Unknown error');
            }
        } catch (err) {
            console.error(err);
            statusEl.textContent = 'Error creating coach';
        }
    }

    loadCoaches();
    </script>
</body>
</html>
