<?php
$pageTitle = 'Edit Game';
ob_start();
?>

<div class="bg-dark rounded-lg shadow-lg p-6">
    <h2 class="text-2xl font-bold mb-6">Edit Game: <?= htmlspecialchars($game['title']) ?></h2>

    <?php if (!empty($success)): ?>
        <div class="bg-green-800 text-white p-4 rounded-md mb-6">
            <i class="fas fa-check-circle mr-2"></i> <?= htmlspecialchars($success) ?>
        </div>
    <?php endif; ?>

    <?php if (!empty($error)): ?>
        <div class="bg-red-800 text-white p-4 rounded-md mb-6">
            <i class="fas fa-exclamation-circle mr-2"></i> <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <form action="/admin/games/update" method="POST">
        <input type="hidden" name="id" value="<?= htmlspecialchars($game['id']) ?>">

        <div class="mb-4">
            <label for="title" class="block text-sm font-medium text-gray-400 mb-1">Title</label>
            <input 
                type="text" 
                id="title" 
                name="title" 
                value="<?= htmlspecialchars($game['title']) ?>"
                required
                class="bg-sidebar-bg border border-gray-700 rounded px-4 py-2 w-full focus:outline-none focus:ring-2 focus:ring-primary"
            >
        </div>

        <div class="mb-4">
            <div class="flex items-center justify-between mb-1">
                <label for="description" class="block text-sm font-medium text-gray-400">Description</label>
                <button type="button" id="generate_description" class="btn-secondary text-sm px-3 py-1">
                    <i class="fas fa-magic mr-1"></i>Generate with AI
                </button>
            </div>
            <!-- Hidden textarea for form submission -->
            <textarea
                id="description"
                name="description"
                rows="4"
                class="hidden"
            ><?= htmlspecialchars($game['description']) ?></textarea>
            
            <!-- QuillJS Editor Container -->
            <div id="editor" class="bg-sidebar-bg border border-gray-700 rounded focus:outline-none focus:ring-2 focus:ring-primary" style="height: 200px;">
                <?= $game['description'] ?>
            </div>
            
            <!-- Initialize QuillJS -->
            <script>
                const quill = new Quill('#editor', {
                    theme: 'snow',
                    modules: {
                        toolbar: [
                            [{ 'header': [1, 2, 3, false] }],
                            ['bold', 'italic', 'underline', 'strike'],
                            [{ 'color': [] }, { 'background': [] }],
                            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                            ['link', 'image'],
                            ['clean']
                        ]
                    },
                    placeholder: 'Enter game description...',
                });

                // Set initial content if it exists
                quill.root.innerHTML = document.getElementById('description').value;

                // Update hidden textarea on content change
                quill.on('text-change', function() {
                    document.getElementById('description').value = quill.root.innerHTML;
                });

                // Handle AI generation
                document.getElementById('generate_description').addEventListener('click', function() {
                    const gameTitle = document.getElementById('title').value;
                    const categoryId = document.getElementById('category_id').value;
                    const gameId = document.querySelector('input[name="id"]').value;
                    
                    if (!gameTitle.trim()) {
                        alert('Please enter a game title first.');
                        return;
                    }

                    // Show loading state
                    const button = this;
                    const originalText = button.innerHTML;
                    button.disabled = true;
                    button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Generating...';

                    // Send AJAX request to generate description
                    fetch('/admin/generate-description', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: new URLSearchParams({
                            game_title: gameTitle,
                            category_id: categoryId,
                            game_id: gameId
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Set the generated description in the editor
                            quill.root.innerHTML = data.description;
                            document.getElementById('description').value = data.description;
                            
                            // Show success message
                            showToast('Description generated successfully!', 'success');
                        } else {
                            showToast('Failed to generate description: ' + (data.message || 'Unknown error'), 'error');
                        }
                    })
                    .catch(error => {
                        showToast('Error generating description: ' + error.message, 'error');
                    })
                    .finally(() => {
                        // Reset button state
                        button.disabled = false;
                        button.innerHTML = originalText;
                    });
                });

                function showToast(message, type) {
                    const toast = document.createElement('div');
                    toast.className = `fixed bottom-4 right-4 px-4 py-2 rounded shadow-lg z-50 ${type === 'success' ? 'bg-green-600' : 'bg-red-600'} text-white`;
                    toast.textContent = message;
                    document.body.appendChild(toast);

                    setTimeout(() => {
                        toast.remove();
                    }, 3000);
                }
            </script>
        </div>

        <div class="mb-4">
            <label for="thumbnail" class="block text-sm font-medium text-gray-400 mb-1">Thumbnail URL</label>
            <input 
                type="text" 
                id="thumbnail" 
                name="thumbnail" 
                value="<?= htmlspecialchars($game['thumbnail']) ?>"
                required
                class="bg-sidebar-bg border border-gray-700 rounded px-4 py-2 w-full focus:outline-none focus:ring-2 focus:ring-primary"
            >
            <img src="<?= htmlspecialchars($game['thumbnail']) ?>" alt="Current Thumbnail" class="mt-2 w-32 h-32 object-cover rounded">
        </div>

        <div class="mb-4">
            <label for="category_id" class="block text-sm font-medium text-gray-400 mb-1">Category</label>
            <select 
                id="category_id" 
                name="category_id" 
                class="bg-sidebar-bg border border-gray-700 rounded px-4 py-2 w-full focus:outline-none focus:ring-2 focus:ring-primary"
            >
                <option value="">-- No Category --</option>
                <?php foreach ($categories as $category): ?>
                    <option value="<?= $category['id'] ?>" <?= $game['category_id'] == $category['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($category['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="flex justify-end space-x-4">
            <a href="/admin/games" class="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded">
                Cancel
            </a>
            <button type="submit" class="bg-primary hover:bg-secondary text-white px-4 py-2 rounded">
                Update Game
            </button>
        </div>
    </form>
</div>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>