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

$pageTitle = 'Content Management';
$pageSection = 'cms';

hw_require_auth(['admin']);
$user = hw_get_auth_user();
?>
<!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">
    <!-- Rich Text Editor -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
</head>
<body class="bg-gray-50">
    <div class="flex h-screen bg-gray-100">
        <!-- Sidebar Navigation -->
        <aside class="w-64 bg-gradient-to-b from-emerald-900 to-emerald-800 text-white shadow-lg flex flex-col">
            <!-- Logo/Brand -->
            <div class="p-6 border-b border-emerald-700 flex-shrink-0">
                <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>

            <!-- Navigation Menu -->
            <nav class="flex-1 overflow-y-auto p-4 space-y-2">
                <!-- Dashboard Home -->
                <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-home w-5"></i>
                    <span class="font-medium">Dashboard</span>
                </a>

                <!-- CATEGORY: BUSINESS OPERATIONS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Business</p>
                </div>

                <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-shopping-cart w-5"></i>
                    <span>Sales & Orders</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/products.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-boxes w-5"></i>
                    <span>Products</span>
                </a>

                <!-- CATEGORY: CUSTOMERS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Customers</p>
                </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>All Customers</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 & Leads</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>

                <!-- CATEGORY: INSIGHTS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Insights</p>
                </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-line w-5"></i>
                    <span>Analytics</span>
                </a>

                <!-- CATEGORY: AUTOMATION & TOOLS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Tools</p>
                </div>

                <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>

                <a href="/atasteofafricanmarketplace/dashboard/admin/cms.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors bg-emerald-700 text-white">
                    <i class="fas fa-file-alt w-5"></i>
                    <span>Content Manager</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>Developer Tools</span>
                </a>

                <!-- CATEGORY: SETTINGS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">System</p>
                </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>
            </nav>

            <!-- User Profile Footer -->
            <div class="flex-shrink-0 p-4 border-t border-emerald-700 bg-emerald-800">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-emerald-300 rounded-full flex items-center justify-center">
                        <i class="fas fa-user text-emerald-900"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="text-sm font-semibold truncate"><?php echo htmlspecialchars($user['first_name'] ?? 'Admin'); ?></p>
                        <p class="text-xs text-emerald-200 truncate"><?php echo htmlspecialchars($user['email'] ?? ''); ?></p>
                    </div>
                    <a href="/atasteofafricanmarketplace/api/auth/logout.php" class="text-emerald-200 hover:text-white">
                        <i class="fas fa-sign-out-alt"></i>
                    </a>
                </div>
            </div>
        </aside>

        <!-- Main Content -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <!-- Top Header Bar -->
            <header class="bg-white border-b border-gray-200 px-8 py-4 shadow-sm">
                <div class="flex items-center justify-between">
                    <div>
                        <h1 class="text-2xl font-bold text-gray-900">Content Management System</h1>
                        <p class="text-sm text-gray-600 mt-1">Manage pages, blog posts, and website content</p>
                    </div>
                    <div class="flex gap-2">
                        <button onclick="showTab('pages')" class="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors">
                            <i class="fas fa-file-alt mr-2"></i>Pages
                        </button>
                        <button onclick="showTab('blog')" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                            <i class="fas fa-blog mr-2"></i>Blog
                        </button>
                        <button onclick="showTab('media')" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors">
                            <i class="fas fa-images mr-2"></i>Media
                        </button>
                    </div>
                </div>
            </header>

            <!-- Content Area -->
            <main class="flex-1 overflow-auto p-8">
            <!-- Content Area -->
            <main class="flex-1 overflow-auto p-8">
                <!-- Pages Tab -->
                <div id="pages-tab" class="tab-content">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-bold text-gray-900">Pages</h2>
                        <button onclick="openPageEditor()" 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>New Page
                        </button>
                    </div>

                    <!-- Pages List -->
                    <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-sm font-semibold text-gray-900">Title</th>
                                    <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Slug</th>
                                    <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Status</th>
                                    <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Updated</th>
                                    <th class="px-6 py-3 text-center text-sm font-semibold text-gray-900">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="pages-tbody" class="divide-y divide-gray-100">
                                <tr>
                                    <td class="px-6 py-4">
                                        <div class="font-medium text-gray-900">About Us</div>
                                        <div class="text-sm text-gray-500">Learn about our mission</div>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-600">/about</td>
                                    <td class="px-6 py-4">
                                        <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Published</span>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-600">2 days ago</td>
                                    <td class="px-6 py-4 text-center">
                                        <button class="text-blue-600 hover:text-blue-800 mx-1" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="text-gray-600 hover:text-gray-800 mx-1" title="Preview">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <button class="text-red-600 hover:text-red-800 mx-1" title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="px-6 py-4">
                                        <div class="font-medium text-gray-900">Services</div>
                                        <div class="text-sm text-gray-500">Our wellness services</div>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-600">/services</td>
                                    <td class="px-6 py-4">
                                        <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Published</span>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-600">5 days ago</td>
                                    <td class="px-6 py-4 text-center">
                                        <button class="text-blue-600 hover:text-blue-800 mx-1" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="text-gray-600 hover:text-gray-800 mx-1" title="Preview">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <button class="text-red-600 hover:text-red-800 mx-1" title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Blog Tab -->
                <div id="blog-tab" class="tab-content hidden">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-bold text-gray-900">Blog Posts</h2>
                        <button onclick="openBlogEditor()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                            <i class="fas fa-plus mr-2"></i>New Post
                        </button>
                    </div>

                    <!-- Blog Posts Grid -->
                    <div id="blog-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <!-- Blog posts loaded by JavaScript -->
                    </div>
                </div>

                <!-- Media Library Tab -->
                <div id="media-tab" class="tab-content hidden">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-bold text-gray-900">Media Library</h2>
                        <button onclick="openMediaUploader()" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors">
                            <i class="fas fa-upload mr-2"></i>Upload Media
                        </button>
                    </div>

                    <!-- Media Filter -->
                    <div class="flex gap-4 mb-6">
                        <button class="px-4 py-2 bg-emerald-600 text-white rounded-lg">All Files</button>
                        <button class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300">Images</button>
                        <button class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300">Documents</button>
                        <button class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300">Videos</button>
                    </div>

                    <!-- Media Grid -->
                    <div id="media-grid" class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                        <!-- Media files loaded by JavaScript -->
                    </div>
                </div>

                <!-- Page Editor Modal (Hidden by default) -->
                <div id="page-editor-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
                    <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto">
                        <div class="p-6 border-b border-gray-200 flex justify-between items-center">
                            <h3 class="text-xl font-bold text-gray-900">Edit Content</h3>
                            <button onclick="closeEditor()" class="text-gray-500 hover:text-gray-700">
                                <i class="fas fa-times text-xl"></i>
                            </button>
                        </div>
                        <div class="p-6 space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Title</label>
                                <input type="text" id="page-title" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent" placeholder="Enter title">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Slug</label>
                                <input type="text" id="page-slug" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent" placeholder="Enter slug">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Excerpt (for blog posts)</label>
                                <textarea id="page-excerpt" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent" placeholder="Enter excerpt" rows="2"></textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                                <select id="page-status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent">
                                    <option value="draft">Draft</option>
                                    <option value="published">Published</option>
                                    <option value="archived">Archived</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Content</label>
                                <div id="editor" style="height: 300px; background: white;"></div>
                            </div>
                        </div>
                        <div class="p-6 border-t border-gray-200 flex justify-end gap-3">
                            <button onclick="closeEditor()" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">Cancel</button>
                            <button onclick="savePage()" class="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700">Save</button>
                        </div>
                    </div>
                </div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">URL Slug</label>
                                <input type="text" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent" placeholder="page-url-slug">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Content</label>
                                <div id="editor" class="bg-white border border-gray-300 rounded-lg" style="height: 300px;"></div>
                            </div>
                        </div>
                        <div class="p-6 border-t border-gray-200 flex justify-end gap-3">
                            <button onclick="closeEditor()" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">Cancel</button>
                            <button onclick="savePage()" class="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700">Save</button>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script>
    let quillEditor;
    let currentEditingPageId = null;
    let currentEditingBlogId = null;

    // Tab Management
    function showTab(tabName) {
        // Hide all tabs
        document.querySelectorAll('.tab-content').forEach(tab => tab.classList.add('hidden'));
        
        // Show selected tab
        if (tabName === 'pages') {
            document.getElementById('pages-tab').classList.remove('hidden');
            loadPages();
        } else if (tabName === 'blog') {
            document.getElementById('blog-tab').classList.remove('hidden');
            loadBlogPosts();
        } else if (tabName === 'media') {
            document.getElementById('media-tab').classList.remove('hidden');
            loadMediaFiles();
        }
    }

    // Load Pages
    async function loadPages() {
        try {
            const response = await fetch('/atasteofafricanmarketplace/api/cms/pages.php?limit=50');
            const data = await response.json();
            
            if (!data.success) {
                document.getElementById('pages-tbody').innerHTML = '<tr><td colspan="5" class="px-6 py-4 text-center text-gray-600">Error loading pages</td></tr>';
                return;
            }
            
            const html = data.pages.length > 0 ? data.pages.map(page => {
                const date = new Date(page.updated_at).toLocaleDateString();
                const statusColor = page.status === 'published' ? 'green' : page.status === 'draft' ? 'yellow' : 'gray';
                return `
                    <tr>
                        <td class="px-6 py-4">
                            <div class="font-medium text-gray-900">${page.title}</div>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-600">/${page.slug}</td>
                        <td class="px-6 py-4">
                            <span class="px-2 py-1 text-xs font-semibold rounded-full bg-${statusColor}-100 text-${statusColor}-800 capitalize">${page.status}</span>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-600">${date}</td>
                        <td class="px-6 py-4 text-center">
                            <button class="text-blue-600 hover:text-blue-800 mx-1" onclick="editPage(${page.id})" title="Edit">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="text-red-600 hover:text-red-800 mx-1" onclick="deletePage(${page.id})" title="Delete">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                `;
            }).join('') : '<tr><td colspan="5" class="px-6 py-4 text-center text-gray-600">No pages found</td></tr>';
            
            document.getElementById('pages-tbody').innerHTML = html;
        } catch (error) {
            console.error('Error loading pages:', error);
            document.getElementById('pages-tbody').innerHTML = '<tr><td colspan="5" class="px-6 py-4 text-center text-red-600">Error loading pages</td></tr>';
        }
    }

    // Load Blog Posts
    async function loadBlogPosts() {
        try {
            const response = await fetch('/atasteofafricanmarketplace/api/cms/blog.php?limit=50');
            const data = await response.json();
            
            if (!data.success) {
                document.getElementById('blog-grid').innerHTML = '<div class="text-center text-gray-600 py-8">Error loading blog posts</div>';
                return;
            }
            
            const html = data.posts.map(post => {
                const date = new Date(post.published_at || post.updated_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                return `
                    <div class="bg-white rounded-lg shadow overflow-hidden">
                        <img src="${post.featured_image || 'data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22400%22 height=%22200%22%3E%3Crect fill=%22%23e5e7eb%22 width=%22400%22 height=%22200%22/%3E%3Ctext x=%2250%25%22 y=%2250%25%22 text-anchor=%22middle%22 dy=%22.3em%22 fill=%22%239ca3af%22%3EBlog Image%3C/text%3E%3C/svg%3E'}" alt="Blog" class="w-full h-48 object-cover">
                        <div class="p-4">
                            <span class="px-2 py-1 text-xs font-semibold rounded-full bg-emerald-100 text-emerald-800">${post.status}</span>
                            <h3 class="font-bold text-gray-900 mt-2 mb-1 line-clamp-2">${post.title}</h3>
                            <p class="text-sm text-gray-600 mb-3 line-clamp-2">${post.excerpt || 'No excerpt'}</p>
                            <div class="flex items-center justify-between text-sm text-gray-500 mb-4">
                                <span><i class="far fa-calendar mr-1"></i>${date}</span>
                                <span><i class="far fa-eye mr-1"></i>${post.view_count} views</span>
                            </div>
                            <div class="flex gap-2">
                                <button class="flex-1 px-3 py-2 bg-blue-50 text-blue-600 rounded hover:bg-blue-100" onclick="editBlogPost(${post.id})">
                                    <i class="fas fa-edit mr-1"></i>Edit
                                </button>
                                <button class="flex-1 px-3 py-2 bg-red-50 text-red-600 rounded hover:bg-red-100" onclick="deleteBlogPost(${post.id})">
                                    <i class="fas fa-trash mr-1"></i>Delete
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
            
            document.getElementById('blog-grid').innerHTML = html || '<div class="text-center text-gray-600 py-8">No blog posts found</div>';
        } catch (error) {
            console.error('Error loading blog posts:', error);
            document.getElementById('blog-grid').innerHTML = '<div class="text-center text-red-600 py-8">Error loading blog posts</div>';
        }
    }

    // Load Media Files
    async function loadMediaFiles() {
        try {
            const response = await fetch('/atasteofafricanmarketplace/api/cms/media.php');
            const data = await response.json();
            
            if (!data.success) {
                document.getElementById('media-grid').innerHTML = '<div class="text-center text-gray-600 py-8">Error loading media files</div>';
                return;
            }
            
            const html = data.files.map(file => {
                const isImage = file.type.startsWith('image');
                const icon = isImage ? 'fa-image' : file.type === 'application/pdf' ? 'fa-file-pdf' : 'fa-file';
                return `
                    <div class="bg-white rounded-lg shadow p-2 cursor-pointer hover:shadow-lg transition-shadow group relative">
                        <div class="aspect-square bg-gray-200 rounded mb-2 flex items-center justify-center text-gray-400">
                            ${isImage ? `<img src="${file.url}" class="w-full h-full object-cover rounded" alt="${file.name}">` : `<i class="fas ${icon} text-3xl"></i>`}
                        </div>
                        <p class="text-xs text-gray-600 truncate">${file.name}</p>
                        <button class="absolute top-2 right-2 bg-red-500 text-white p-1 rounded opacity-0 group-hover:opacity-100 transition" onclick="deleteMediaFile('${file.name}')">
                            <i class="fas fa-trash text-xs"></i>
                        </button>
                    </div>
                `;
            }).join('');
            
            document.getElementById('media-grid').innerHTML = html + `
                <div class="bg-white rounded-lg shadow border-2 border-dashed border-gray-300 p-2 cursor-pointer hover:border-purple-400 transition-colors flex items-center justify-center" onclick="document.getElementById('media-file-input').click()">
                    <div class="text-center">
                        <i class="fas fa-plus-circle text-2xl text-gray-400 mb-1"></i>
                        <p class="text-xs text-gray-500">Upload</p>
                    </div>
                </div>
                <input type="file" id="media-file-input" class="hidden" onchange="uploadMediaFile()" multiple>
            `;
        } catch (error) {
            console.error('Error loading media files:', error);
            document.getElementById('media-grid').innerHTML = '<div class="text-center text-red-600 py-8">Error loading media files</div>';
        }
    }

    // Upload Media File
    async function uploadMediaFile() {
        const input = document.getElementById('media-file-input');
        if (!input.files.length) return;
        
        for (const file of input.files) {
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                const response = await fetch('/atasteofafricanmarketplace/api/cms/media.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                if (data.success) {
                    loadMediaFiles();
                } else {
                    alert('Error uploading file: ' + (data.error || 'Unknown error'));
                }
            } catch (error) {
                console.error('Error uploading file:', error);
                alert('Error uploading file');
            }
        }
    }

    // Delete Media File
    async function deleteMediaFile(filename) {
        if (!confirm('Delete this file?')) return;
        
        try {
            const response = await fetch('/atasteofafricanmarketplace/api/cms/media.php', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ filename })
            });
            const data = await response.json();
            if (data.success) {
                loadMediaFiles();
            } else {
                alert('Error deleting file: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error deleting file:', error);
        }
    }

    // Editor Functions
    function openPageEditor() {
        currentEditingPageId = null;
        document.getElementById('page-editor-modal').classList.remove('hidden');
        document.getElementById('page-title').value = '';
        document.getElementById('page-slug').value = '';
        document.getElementById('page-status').value = 'draft';
        
        // Initialize Quill editor if not already initialized
        if (!quillEditor) {
            quillEditor = new Quill('#editor', {
                theme: 'snow',
                placeholder: 'Start writing your content here...',
                modules: {
                    toolbar: [
                        [{ 'header': [1, 2, 3, false] }],
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'color': [] }, { 'background': [] }],
                        ['link', 'image'],
                        ['clean']
                    ]
                }
            });
        }
        quillEditor.setContents([]);
    }

    function editPage(id) {
        // For now, just open editor
        openPageEditor();
        currentEditingPageId = id;
        alert('Edit functionality coming soon');
    }

    async function savePage() {
        const title = document.getElementById('page-title').value;
        const slug = document.getElementById('page-slug').value;
        const status = document.getElementById('page-status').value;
        const content = quillEditor.root.innerHTML;
        
        if (!title || !slug) {
            alert('Title and slug are required');
            return;
        }
        
        try {
            const response = await fetch('/atasteofafricanmarketplace/api/cms/pages.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    id: currentEditingPageId,
                    title,
                    slug,
                    content,
                    status
                })
            });
            const data = await response.json();
            if (data.success) {
                alert(data.message);
                closeEditor();
                loadPages();
            } else {
                alert('Error: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error:', error);
            alert('Error saving page');
        }
    }

    function openBlogEditor() {
        currentEditingBlogId = null;
        document.getElementById('page-editor-modal').classList.remove('hidden');
        document.getElementById('page-title').value = '';
        document.getElementById('page-slug').value = '';
        document.getElementById('page-excerpt').value = '';
        document.getElementById('page-status').value = 'draft';
        
        if (!quillEditor) {
            quillEditor = new Quill('#editor', {
                theme: 'snow',
                placeholder: 'Start writing your blog post here...',
                modules: {
                    toolbar: [
                        [{ 'header': [1, 2, 3, false] }],
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'color': [] }, { 'background': [] }],
                        ['link', 'image'],
                        ['clean']
                    ]
                }
            });
        }
        quillEditor.setContents([]);
    }

    function editBlogPost(id) {
        openBlogEditor();
        currentEditingBlogId = id;
        alert('Edit functionality coming soon');
    }

    async function saveBlogPost() {
        const title = document.getElementById('page-title').value;
        const slug = document.getElementById('page-slug').value;
        const excerpt = document.getElementById('page-excerpt').value;
        const status = document.getElementById('page-status').value;
        const content = quillEditor.root.innerHTML;
        
        if (!title || !slug) {
            alert('Title and slug are required');
            return;
        }
        
        try {
            const response = await fetch('/atasteofafricanmarketplace/api/cms/blog.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    id: currentEditingBlogId,
                    title,
                    slug,
                    excerpt,
                    content,
                    status
                })
            });
            const data = await response.json();
            if (data.success) {
                alert(data.message);
                closeEditor();
                loadBlogPosts();
            } else {
                alert('Error: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error:', error);
            alert('Error saving blog post');
        }
    }

    async function deletePage(id) {
        if (!confirm('Delete this page?')) return;
        
        try {
            const response = await fetch('/atasteofafricanmarketplace/api/cms/pages.php', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id })
            });
            const data = await response.json();
            if (data.success) {
                loadPages();
            } else {
                alert('Error: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }

    async function deleteBlogPost(id) {
        if (!confirm('Delete this blog post?')) return;
        
        try {
            const response = await fetch('/atasteofafricanmarketplace/api/cms/blog.php', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id })
            });
            const data = await response.json();
            if (data.success) {
                loadBlogPosts();
            } else {
                alert('Error: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }

    function closeEditor() {
        document.getElementById('page-editor-modal').classList.add('hidden');
    }

    // Load content on page load
    document.addEventListener('DOMContentLoaded', function() {
        showTab('pages'); // Show pages tab by default
    });

    // Close modal when clicking outside
    document.getElementById('page-editor-modal')?.addEventListener('click', function(e) {
        if (e.target === this) {
            closeEditor();
        }
    });
    </script>
</body>
</html>
