<?php
require_once 'config.php';
$adminId = requireAdminAuth();
$admin = getCurrentAdmin();

$pageTitle = "Hero Banners Management";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?> - ENSI Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/style.css" rel="stylesheet">
    <style>
        .banner-preview {
            min-height: 120px;
            border-radius: 12px;
            padding: 20px;
            margin: 10px 0;
            position: relative;
            overflow: hidden;
            background-size: cover;
            background-position: center;
        }
        .banner-preview-overlay {
            position: absolute;
            inset: 0;
            background: rgba(0, 0, 0, 0.5);
        }
        .banner-preview-content {
            position: relative;
            z-index: 1;
        }
        .color-square {
            width: 30px;
            height: 30px;
            border-radius: 6px;
            display: inline-block;
            border: 2px solid #dee2e6;
        }
        .icon-preview {
            font-size: 32px;
        }
        .dismissal-badge {
            font-size: 0.9em;
        }
        .drag-handle {
            cursor: move;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2><i class="bi bi-card-image"></i> Hero Banners</h2>
                        <p class="text-muted">Manage swipeable hero banners for app home screen</p>
                    </div>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#bannerModal" onclick="openCreateModal()">
                        <i class="bi bi-plus-circle"></i> Add New Banner
                    </button>
                </div>

                <!-- Banners List -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">All Banners</h5>
                    </div>
                    <div class="card-body">
                        <div id="banners-list">
                            <div class="text-center py-5">
                                <div class="spinner-border" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2">Loading banners...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit Banner Modal -->
    <div class="modal fade" id="bannerModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">Add New Banner</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="bannerForm">
                        <input type="hidden" id="banner_id" name="id">
                        
                        <!-- Content Section -->
                        <h6 class="border-bottom pb-2 mb-3"><i class="bi bi-text-left"></i> Content</h6>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Title *</label>
                                <input type="text" class="form-control" id="title" name="title" required maxlength="100">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Icon</label>
                                <select class="form-select" id="icon" name="icon">
                                    <option value="star">⭐ star</option>
                                    <option value="workspace_premium">💎 workspace_premium</option>
                                    <option value="phone_android">📱 phone_android</option>
                                    <option value="celebration">🎉 celebration</option>
                                    <option value="school">🎓 school</option>
                                    <option value="record_voice_over">🗣️ record_voice_over</option>
                                    <option value="library_books">📚 library_books</option>
                                    <option value="games">🎮 games</option>
                                    <option value="card_giftcard">🎁 card_giftcard</option>
                                    <option value="local_fire_department">🔥 local_fire_department</option>
                                    <option value="rocket_launch">🚀 rocket_launch</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Description *</label>
                            <textarea class="form-control" id="description" name="description" rows="2" required maxlength="255"></textarea>
                        </div>

                        <!-- Design Section -->
                        <h6 class="border-bottom pb-2 mb-3 mt-4"><i class="bi bi-palette"></i> Design</h6>
                        
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">Gradient Start</label>
                                <input type="color" class="form-control form-control-color w-100" id="gradient_start" name="gradient_start" value="#FF6B6B">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Gradient End</label>
                                <input type="color" class="form-control form-control-color w-100" id="gradient_end" name="gradient_end" value="#FFE66D">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Text Color</label>
                                <input type="color" class="form-control form-control-color w-100" id="text_color" name="text_color" value="#FFFFFF">
                            </div>
                        </div>

                        <!-- Image Section -->
                        <div class="mb-3">
                            <label class="form-label">Image Display Mode</label>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="image_mode" value="icon_only" id="mode_icon" checked>
                                <label class="form-check-label" for="mode_icon">
                                    <strong>Icon Only</strong> - Simple gradient with material icon
                                </label>
                            </div>
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="radio" name="image_mode" value="background" id="mode_bg">
                                <label class="form-check-label" for="mode_bg">
                                    <strong>Background Image</strong> - Full-width image with text overlay
                                </label>
                            </div>
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="radio" name="image_mode" value="side" id="mode_side">
                                <label class="form-check-label" for="mode_side">
                                    <strong>Side Image</strong> - Image on left, content on right
                                </label>
                            </div>
                        </div>

                        <div class="mb-3" id="image_url_field" style="display: none;">
                            <label class="form-label">Image URL</label>
                            <input type="url" class="form-control" id="image_url" name="image_url" placeholder="https://example.com/image.jpg">
                            <small class="text-muted">Recommended: 800x400px, under 500KB</small>
                        </div>

                        <div class="mb-3" id="overlay_field" style="display: none;">
                            <label class="form-label">Dark Overlay Opacity (for text readability)</label>
                            <input type="range" class="form-range" id="image_overlay_opacity" name="image_overlay_opacity" 
                                   min="0" max="1" step="0.1" value="0.5">
                            <div class="d-flex justify-content-between">
                                <small>Light (0%)</small>
                                <strong id="overlay_value">50%</strong>
                                <small>Dark (100%)</small>
                            </div>
                        </div>

                        <!-- Action Section -->
                        <h6 class="border-bottom pb-2 mb-3 mt-4"><i class="bi bi-cursor"></i> Action</h6>
                        
                        <div class="mb-3">
                            <label class="form-label">Action Type</label>
                            <select class="form-select" id="action_type" name="action_type">
                                <option value="none">None - No action on click</option>
                                <option value="web_url">Open Web URL in browser</option>
                                <option value="app_route">Navigate within app</option>
                            </select>
                        </div>

                        <div class="mb-3" id="action_value_field" style="display: none;">
                            <label class="form-label" id="action_value_label">URL / Route</label>
                            <input type="text" class="form-control" id="action_value" name="action_value" placeholder="https://ensi.lk/pricing">
                        </div>

                        <div class="mb-3" id="action_text_field" style="display: none;">
                            <label class="form-label">Button Text</label>
                            <input type="text" class="form-control" id="action_text" name="action_text" placeholder="Learn More" maxlength="50">
                        </div>

                        <!-- Settings Section -->
                        <h6 class="border-bottom pb-2 mb-3 mt-4"><i class="bi bi-gear"></i> Settings</h6>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Banner Type</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="banner_type" value="permanent" id="type_permanent" checked>
                                    <label class="form-check-label" for="type_permanent">
                                        <strong>Permanent</strong> - Always shows
                                    </label>
                                </div>
                                <div class="form-check mt-2">
                                    <input class="form-check-input" type="radio" name="banner_type" value="dismissible" id="type_dismissible">
                                    <label class="form-check-label" for="type_dismissible">
                                        <strong>Dismissible</strong> - User can close it
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Display Order</label>
                                <input type="number" class="form-control" id="display_order" name="display_order" value="0" min="0">
                                <small class="text-muted">Lower number shows first</small>
                                
                                <div class="form-check mt-3">
                                    <input class="form-check-input" type="checkbox" id="is_active" name="is_active" value="1" checked>
                                    <label class="form-check-label" for="is_active">
                                        <strong>Active</strong> - Show in app
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- Preview -->
                        <div class="mt-4">
                            <h6 class="border-bottom pb-2 mb-3"><i class="bi bi-eye"></i> Preview</h6>
                            <div id="banner-preview-container"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="saveBanner()">
                        <i class="bi bi-save"></i> Save Banner
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/admin.js"></script>
    <script>
        let banners = [];
        const modal = new bootstrap.Modal(document.getElementById('bannerModal'));

        // Load banners on page load
        document.addEventListener('DOMContentLoaded', loadBanners);

        // Load all banners
        async function loadBanners() {
            try {
                const response = await fetch('api/hero_banners.php?action=list');
                const result = await response.json();
                
                if (result.success) {
                    banners = result.data;
                    renderBanners();
                } else {
                    showError('Failed to load banners');
                }
            } catch (error) {
                showError('Error loading banners: ' + error.message);
            }
        }

        // Render banners list
        function renderBanners() {
            const container = document.getElementById('banners-list');
            
            if (banners.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-5">
                        <i class="bi bi-card-image" style="font-size: 48px; color: #ccc;"></i>
                        <p class="mt-3 text-muted">No banners yet. Click "Add New Banner" to create one.</p>
                    </div>
                `;
                return;
            }

            let html = '<div class="table-responsive"><table class="table table-hover align-middle">';
            html += `
                <thead>
                    <tr>
                        <th width="50">Order</th>
                        <th>Preview</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Dismissed By</th>
                        <th width="200">Actions</th>
                    </tr>
                </thead>
                <tbody>
            `;

            banners.forEach(banner => {
                const gradient = `linear-gradient(135deg, ${banner.gradient_start}, ${banner.gradient_end})`;
                const statusBadge = banner.is_active 
                    ? '<span class="badge bg-success">Active</span>' 
                    : '<span class="badge bg-secondary">Inactive</span>';
                const typeBadge = banner.banner_type === 'permanent'
                    ? '<span class="badge bg-info">Permanent</span>'
                    : '<span class="badge bg-warning text-dark">Dismissible</span>';
                
                let previewStyle = `background: ${gradient};`;
                if (banner.image_url && banner.image_mode === 'background') {
                    previewStyle = `background: url('${banner.image_url}') center/cover;`;
                }

                html += `
                    <tr>
                        <td class="text-center">
                            <span class="badge bg-secondary">${banner.display_order}</span>
                        </td>
                        <td>
                            <div class="banner-preview" style="${previewStyle}">
                                ${banner.image_mode === 'background' ? `<div class="banner-preview-overlay" style="background: rgba(0,0,0,${banner.image_overlay_opacity});"></div>` : ''}
                                <div class="banner-preview-content" style="color: ${banner.text_color};">
                                    <div class="icon-preview">${getIconEmoji(banner.icon)}</div>
                                    <strong>${banner.title}</strong><br>
                                    <small>${banner.description}</small>
                                </div>
                            </div>
                            <small class="text-muted">
                                Mode: ${banner.image_mode} 
                                ${banner.action_type !== 'none' ? `| Action: ${banner.action_type}` : ''}
                            </small>
                        </td>
                        <td>${typeBadge}</td>
                        <td>${statusBadge}</td>
                        <td>
                            ${banner.banner_type === 'dismissible' 
                                ? `<span class="dismissal-badge badge ${banner.dismissal_count > 0 ? 'bg-danger' : 'bg-light text-dark'}">
                                     ${banner.dismissal_count} users
                                   </span>
                                   ${banner.dismissal_count > 0 ? `<br><small><a href="javascript:void(0)" onclick="resetDismissals(${banner.id})">Reset All</a></small>` : ''}`
                                : '<span class="text-muted">N/A</span>'
                            }
                        </td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" onclick="editBanner(${banner.id})">
                                <i class="bi bi-pencil"></i> Edit
                            </button>
                            <button class="btn btn-sm btn-outline-${banner.is_active ? 'warning' : 'success'}" onclick="toggleStatus(${banner.id})">
                                <i class="bi bi-${banner.is_active ? 'pause' : 'play'}-circle"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteBanner(${banner.id})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </td>
                    </tr>
                `;
            });

            html += '</tbody></table></div>';
            container.innerHTML = html;
        }

        // Get icon emoji
        function getIconEmoji(icon) {
            const icons = {
                'star': '⭐',
                'workspace_premium': '💎',
                'phone_android': '📱',
                'celebration': '🎉',
                'school': '🎓',
                'record_voice_over': '🗣️',
                'library_books': '📚',
                'games': '🎮',
                'card_giftcard': '🎁',
                'local_fire_department': '🔥',
                'rocket_launch': '🚀'
            };
            return icons[icon] || '⭐';
        }

        // Open create modal
        function openCreateModal() {
            document.getElementById('modalTitle').textContent = 'Add New Banner';
            document.getElementById('bannerForm').reset();
            document.getElementById('banner_id').value = '';
            document.getElementById('is_active').checked = true;
            updatePreview();
        }

        // Edit banner
        function editBanner(id) {
            const banner = banners.find(b => b.id === id);
            if (!banner) return;

            document.getElementById('modalTitle').textContent = 'Edit Banner';
            document.getElementById('banner_id').value = banner.id;
            document.getElementById('title').value = banner.title;
            document.getElementById('description').value = banner.description;
            document.getElementById('icon').value = banner.icon;
            document.getElementById('gradient_start').value = banner.gradient_start;
            document.getElementById('gradient_end').value = banner.gradient_end;
            document.getElementById('text_color').value = banner.text_color;
            document.getElementById('image_url').value = banner.image_url || '';
            document.querySelector(`input[name="image_mode"][value="${banner.image_mode}"]`).checked = true;
            document.getElementById('image_overlay_opacity').value = banner.image_overlay_opacity;
            document.getElementById('action_type').value = banner.action_type;
            document.getElementById('action_value').value = banner.action_value || '';
            document.getElementById('action_text').value = banner.action_text || '';
            document.querySelector(`input[name="banner_type"][value="${banner.banner_type}"]`).checked = true;
            document.getElementById('is_active').checked = banner.is_active;
            document.getElementById('display_order').value = banner.display_order;

            // Trigger change events to show/hide fields
            document.querySelector('input[name="image_mode"]:checked').dispatchEvent(new Event('change'));
            document.getElementById('action_type').dispatchEvent(new Event('change'));
            updateOverlayValue();
            updatePreview();

            modal.show();
        }

        // Save banner
        async function saveBanner() {
            const form = document.getElementById('bannerForm');
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }

            const formData = new FormData(form);
            const data = {};
            
            formData.forEach((value, key) => {
                if (key === 'is_active') {
                    data[key] = value ? 1 : 0;
                } else if (key === 'image_overlay_opacity' || key === 'display_order') {
                    data[key] = parseFloat(value);
                } else {
                    data[key] = value || null;
                }
            });

            // Handle checkbox properly
            if (!formData.has('is_active')) {
                data.is_active = 0;
            }

            const bannerId = document.getElementById('banner_id').value;
            const action = bannerId ? 'update' : 'create';
            const url = `api/hero_banners.php?action=${action}`;

            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (result.success) {
                    showSuccess(bannerId ? 'Banner updated successfully' : 'Banner created successfully');
                    modal.hide();
                    loadBanners();
                } else {
                    showError(result.message || 'Failed to save banner');
                }
            } catch (error) {
                showError('Error saving banner: ' + error.message);
            }
        }

        // Delete banner
        async function deleteBanner(id) {
            if (!confirm('Are you sure you want to delete this banner?')) return;

            try {
                const response = await fetch('api/hero_banners.php?action=delete', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({id})
                });

                const result = await response.json();

                if (result.success) {
                    showSuccess('Banner deleted successfully');
                    loadBanners();
                } else {
                    showError(result.message || 'Failed to delete banner');
                }
            } catch (error) {
                showError('Error deleting banner: ' + error.message);
            }
        }

        // Toggle status
        async function toggleStatus(id) {
            try {
                const response = await fetch('api/hero_banners.php?action=toggle_status', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({id})
                });

                const result = await response.json();

                if (result.success) {
                    showSuccess('Banner status updated');
                    loadBanners();
                } else {
                    showError(result.message || 'Failed to update status');
                }
            } catch (error) {
                showError('Error updating status: ' + error.message);
            }
        }

        // Reset dismissals
        async function resetDismissals(bannerId) {
            if (!confirm('Reset all dismissals for this banner? Users will see it again.')) return;

            try {
                const response = await fetch('api/hero_banners.php?action=reset_dismissals', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({banner_id: bannerId})
                });

                const result = await response.json();

                if (result.success) {
                    showSuccess(`Reset ${result.deleted_count} dismissals`);
                    loadBanners();
                } else {
                    showError(result.message || 'Failed to reset dismissals');
                }
            } catch (error) {
                showError('Error resetting dismissals: ' + error.message);
            }
        }

        // Update preview
        function updatePreview() {
            const title = document.getElementById('title').value || 'Banner Title';
            const description = document.getElementById('description').value || 'Banner description goes here...';
            const icon = getIconEmoji(document.getElementById('icon').value);
            const gradientStart = document.getElementById('gradient_start').value;
            const gradientEnd = document.getElementById('gradient_end').value;
            const textColor = document.getElementById('text_color').value;
            const imageMode = document.querySelector('input[name="image_mode"]:checked').value;
            const imageUrl = document.getElementById('image_url').value;
            const overlayOpacity = document.getElementById('image_overlay_opacity').value;

            let style = `background: linear-gradient(135deg, ${gradientStart}, ${gradientEnd}); color: ${textColor};`;
            let overlayHtml = '';

            if (imageMode === 'background' && imageUrl) {
                style = `background: url('${imageUrl}') center/cover; color: ${textColor};`;
                overlayHtml = `<div style="position: absolute; inset: 0; background: rgba(0,0,0,${overlayOpacity});"></div>`;
            }

            const previewHtml = `
                <div class="banner-preview" style="${style}">
                    ${overlayHtml}
                    <div style="position: relative; z-index: 1;">
                        <div class="icon-preview">${icon}</div>
                        <strong>${title}</strong><br>
                        <small>${description}</small>
                    </div>
                </div>
            `;

            document.getElementById('banner-preview-container').innerHTML = previewHtml;
        }

        // Update overlay value display
        function updateOverlayValue() {
            const value = document.getElementById('image_overlay_opacity').value;
            document.getElementById('overlay_value').textContent = Math.round(value * 100) + '%';
        }

        // Show/hide fields based on selections
        document.querySelectorAll('input[name="image_mode"]').forEach(radio => {
            radio.addEventListener('change', function() {
                const imageField = document.getElementById('image_url_field');
                const overlayField = document.getElementById('overlay_field');
                
                if (this.value === 'background' || this.value === 'side') {
                    imageField.style.display = 'block';
                } else {
                    imageField.style.display = 'none';
                }
                
                if (this.value === 'background') {
                    overlayField.style.display = 'block';
                } else {
                    overlayField.style.display = 'none';
                }
                updatePreview();
            });
        });

        document.getElementById('action_type').addEventListener('change', function() {
            const valueField = document.getElementById('action_value_field');
            const textField = document.getElementById('action_text_field');
            const label = document.getElementById('action_value_label');

            if (this.value === 'none') {
                valueField.style.display = 'none';
                textField.style.display = 'none';
            } else {
                valueField.style.display = 'block';
                textField.style.display = 'block';
                label.textContent = this.value === 'web_url' ? 'URL' : 'App Route';
                document.getElementById('action_value').placeholder = this.value === 'web_url' 
                    ? 'https://ensi.lk/pricing' 
                    : '/phonetics';
            }
        });

        document.getElementById('image_overlay_opacity').addEventListener('input', updateOverlayValue);

        // Update preview on any input change
        document.getElementById('bannerForm').addEventListener('input', updatePreview);
        document.getElementById('bannerForm').addEventListener('change', updatePreview);

        // Utility functions
        function showSuccess(message) {
            alert(message); // Replace with toast notification
        }

        function showError(message) {
            alert('Error: ' + message); // Replace with toast notification
        }
    </script>
</body>
</html>
