/**
 * Admin Modal JavaScript
 * Handles modal creation, image upload, and form submission
 */

class AdminModal {
    constructor() {
        this.currentModal = null;
        this.init();
    }

    init() {
        // Create modal container if it doesn't exist
        if (!document.getElementById('admin-modal-container')) {
            const container = document.createElement('div');
            container.id = 'admin-modal-container';
            document.body.appendChild(container);
        }

        // Bind event listeners
        this.bindEvents();
    }

    bindEvents() {
        // Close modal on escape key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.currentModal) {
                this.close();
            }
        });

        // Close modal on backdrop click
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('admin-modal')) {
                this.close();
            }
        });
    }

    create(options = {}) {
        const defaults = {
            title: 'Modal',
            size: 'medium', // small, medium, large
            showFooter: true,
            closable: true
        };

        const config = { ...defaults, ...options };
        
        const modalHTML = `
            <div class="admin-modal" id="admin-modal">
                <div class="admin-modal-content ${config.size}">
                    <div class="admin-modal-header">
                        <h3 class="admin-modal-title">${config.title}</h3>
                        ${config.closable ? '<button type="button" class="admin-modal-close" onclick="adminModal.close()">&times;</button>' : ''}
                    </div>
                    <div class="admin-modal-body" id="admin-modal-body">
                        ${config.content || ''}
                    </div>
                    ${config.showFooter ? '<div class="admin-modal-footer" id="admin-modal-footer"></div>' : ''}
                </div>
            </div>
        `;

        document.getElementById('admin-modal-container').innerHTML = modalHTML;
        this.currentModal = document.getElementById('admin-modal');
        
        return this;
    }

    show() {
        if (this.currentModal) {
            this.currentModal.classList.add('show');
            document.body.style.overflow = 'hidden';
        }
        return this;
    }

    close() {
        if (this.currentModal) {
            this.currentModal.classList.remove('show');
            document.body.style.overflow = '';
            setTimeout(() => {
                document.getElementById('admin-modal-container').innerHTML = '';
                this.currentModal = null;
            }, 300);
        }
        return this;
    }

    setContent(content) {
        if (this.currentModal) {
            document.getElementById('admin-modal-body').innerHTML = content;
        }
        return this;
    }

    setFooter(footerHTML) {
        if (this.currentModal) {
            const footer = document.getElementById('admin-modal-footer');
            if (footer) {
                footer.innerHTML = footerHTML;
            }
        }
        return this;
    }

    // Create a content modal with image, description, and link
    createContentModal(data = {}) {
        const modalContent = `
            <form id="content-modal-form" enctype="multipart/form-data">
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" value="${data.id || ''}">
                
                <div class="modal-form-group">
                    <label class="modal-form-label">Title *</label>
                    <input type="text" name="title" class="modal-form-control" value="${data.title || ''}" required placeholder="Enter title...">
                </div>

                <div class="modal-form-group">
                    <label class="modal-form-label">Description *</label>
                    <textarea name="description" class="modal-form-control modal-textarea" required placeholder="Enter description...">${data.description || ''}</textarea>
                </div>

                <div class="modal-form-group">
                    <label class="modal-form-label">Link URL</label>
                    <input type="url" name="link_url" class="modal-form-control" value="${data.link_url || ''}" placeholder="https://example.com">
                </div>

                <div class="modal-form-group">
                    <label class="modal-form-label">Link Text</label>
                    <input type="text" name="link_text" class="modal-form-control" value="${data.link_text || ''}" placeholder="Read More, Learn More, etc.">
                </div>

                <div class="modal-form-group">
                    <label class="modal-form-label">Image</label>
                    <div class="modal-image-upload" onclick="document.getElementById('modal-image-input').click()">
                        <input type="file" id="modal-image-input" name="image" accept="image/*" style="display: none;">
                        <div class="upload-text">
                            <i class="bi bi-cloud-upload" style="font-size: 2rem; color: #6b7280;"></i>
                            <p>Click to upload image or drag and drop</p>
                            <p class="modal-file-info">PNG, JPG, GIF up to 5MB</p>
                        </div>
                        <div class="modal-image-preview" id="modal-image-preview" style="display: none;">
                            <img id="modal-preview-img" src="" alt="Preview">
                            <p class="modal-file-info" id="modal-file-info"></p>
                        </div>
                    </div>
                </div>

                <div class="modal-form-group">
                    <label class="modal-form-label">Status</label>
                    <select name="status" class="modal-form-control">
                        <option value="active" ${data.status === 'active' ? 'selected' : ''}>Active</option>
                        <option value="inactive" ${data.status === 'inactive' ? 'selected' : ''}>Inactive</option>
                    </select>
                </div>

                <div class="modal-form-group">
                    <label class="modal-form-label">Display Order</label>
                    <input type="number" name="display_order" class="modal-form-control" value="${data.display_order || 0}" min="0">
                </div>
            </form>
        `;

        const footerHTML = `
            <button type="button" class="modal-btn modal-btn-secondary" onclick="adminModal.close()">
                Cancel
            </button>
            <button type="button" class="modal-btn modal-btn-primary" onclick="adminModal.submitContentForm()">
                <span class="btn-text">${data.id ? 'Update' : 'Create'}</span>
                <span class="modal-loading" style="display: none;"></span>
            </button>
        `;

        this.create({
            title: data.id ? 'Edit Content' : 'Add New Content',
            content: modalContent
        }).setFooter(footerHTML).show();

        // Setup image upload functionality
        this.setupImageUpload();

        // If editing, show existing image
        if (data.image_url) {
            this.showImagePreview(data.image_url, 'Current Image');
        }

        return this;
    }

    setupImageUpload() {
        const fileInput = document.getElementById('modal-image-input');
        const uploadArea = document.querySelector('.modal-image-upload');
        const preview = document.getElementById('modal-image-preview');
        const previewImg = document.getElementById('modal-preview-img');
        const fileInfo = document.getElementById('modal-file-info');

        // File input change event
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                this.handleImageFile(file);
            }
        });

        // Drag and drop functionality
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                const file = files[0];
                if (file.type.startsWith('image/')) {
                    fileInput.files = files;
                    this.handleImageFile(file);
                }
            }
        });
    }

    handleImageFile(file) {
        // Validate file size (5MB)
        if (file.size > 5 * 1024 * 1024) {
            alert('File size must be less than 5MB');
            return;
        }

        // Show preview
        const reader = new FileReader();
        reader.onload = (e) => {
            this.showImagePreview(e.target.result, file.name);
        };
        reader.readAsDataURL(file);
    }

    showImagePreview(src, filename) {
        const preview = document.getElementById('modal-image-preview');
        const previewImg = document.getElementById('modal-preview-img');
        const fileInfo = document.getElementById('modal-file-info');
        const uploadText = document.querySelector('.upload-text');

        previewImg.src = src;
        fileInfo.textContent = filename;
        preview.style.display = 'block';
        uploadText.style.display = 'none';
    }

    async submitContentForm() {
        const form = document.getElementById('content-modal-form');
        const formData = new FormData(form);
        
        // Show loading state
        const submitBtn = document.querySelector('.modal-btn-primary');
        const btnText = submitBtn.querySelector('.btn-text');
        const loading = submitBtn.querySelector('.modal-loading');
        
        btnText.style.display = 'none';
        loading.style.display = 'inline-block';
        submitBtn.disabled = true;

        try {
            const response = await fetch('admin/ajax/save_content.php', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (result.success) {
                // Show success message
                this.showSuccessMessage('Content saved successfully!');
                // Reload page or update table
                setTimeout(() => {
                    window.location.reload();
                }, 1500);
            } else {
                throw new Error(result.message || 'Failed to save content');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('Error: ' + error.message);
        } finally {
            // Reset button state
            btnText.style.display = 'inline';
            loading.style.display = 'none';
            submitBtn.disabled = false;
        }
    }

    showSuccessMessage(message) {
        const successHTML = `
            <div style="text-align: center; padding: 20px;">
                <i class="bi bi-check-circle-fill" style="font-size: 3rem; color: #10b981; margin-bottom: 15px;"></i>
                <h4 style="color: #10b981; margin-bottom: 10px;">Success!</h4>
                <p>${message}</p>
            </div>
        `;

        this.setContent(successHTML);
        document.getElementById('admin-modal-footer').style.display = 'none';
    }

    // Confirmation modal
    confirm(message, callback) {
        const modalContent = `
            <div style="text-align: center; padding: 20px;">
                <i class="bi bi-question-circle-fill" style="font-size: 3rem; color: #f59e0b; margin-bottom: 15px;"></i>
                <h4 style="margin-bottom: 15px;">Confirm Action</h4>
                <p>${message}</p>
            </div>
        `;

        const footerHTML = `
            <button type="button" class="modal-btn modal-btn-secondary" onclick="adminModal.close()">
                Cancel
            </button>
            <button type="button" class="modal-btn modal-btn-danger" onclick="adminModal.handleConfirm()">
                Confirm
            </button>
        `;

        this.confirmCallback = callback;

        this.create({
            title: 'Confirmation',
            content: modalContent
        }).setFooter(footerHTML).show();

        return this;
    }

    handleConfirm() {
        if (this.confirmCallback) {
            this.confirmCallback();
            this.confirmCallback = null;
        }
        this.close();
    }
}

// Initialize modal system
const adminModal = new AdminModal();

// Helper functions for easy use
function openContentModal(data = {}) {
    adminModal.createContentModal(data);
}

function confirmDelete(message, callback) {
    adminModal.confirm(message, callback);
}
