<?php
/**
 * Galeria de Mídia - MontaLoja
 * Componente reutilizável para seleção de imagens
 */

// Buscar imagens existentes da loja se $storeId estiver disponível
$storeMediaImages = [];
if (isset($storeId) && isset($pdo)) {
    try {
        // Buscar imagens dos produtos da loja (tabela products)
        $mediaStmt = $pdo->prepare("
            SELECT DISTINCT 
                p.image_url,
                p.images,
                p.name as product_name, 
                p.id as product_id,
                p.created_at
            FROM products p 
            WHERE p.store_id = ? 
                AND (p.image_url IS NOT NULL AND p.image_url != '')
            ORDER BY p.created_at DESC 
            LIMIT 50
        ");
        $mediaStmt->execute([$storeId]);
        $products = $mediaStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Processar imagens principais e adicionais
        foreach ($products as $product) {
            // Adicionar imagem principal
            if (!empty($product['image_url'])) {
                $storeMediaImages[] = [
                    'image_url' => $product['image_url'],
                    'product_name' => $product['product_name'],
                    'product_id' => $product['product_id']
                ];
            }
            
            // Adicionar imagens adicionais do JSON
            if (!empty($product['images'])) {
                $additionalImages = json_decode($product['images'], true);
                if (is_array($additionalImages)) {
                    foreach ($additionalImages as $imgUrl) {
                        if (!empty($imgUrl)) {
                            $storeMediaImages[] = [
                                'image_url' => $imgUrl,
                                'product_name' => $product['product_name'],
                                'product_id' => $product['product_id']
                            ];
                        }
                    }
                }
            }
        }
        
        // Também buscar da tabela product_images se existir
        $piStmt = $pdo->prepare("
            SELECT DISTINCT pi.image_url, p.name as product_name, p.id as product_id
            FROM product_images pi 
            INNER JOIN products p ON pi.product_id = p.id 
            WHERE p.store_id = ? 
            ORDER BY pi.created_at DESC 
            LIMIT 50
        ");
        $piStmt->execute([$storeId]);
        $piImages = $piStmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($piImages as $img) {
            $storeMediaImages[] = $img;
        }
        
        // Remover duplicatas por URL
        $uniqueImages = [];
        $seenUrls = [];
        foreach ($storeMediaImages as $img) {
            if (!in_array($img['image_url'], $seenUrls)) {
                $seenUrls[] = $img['image_url'];
                $uniqueImages[] = $img;
            }
        }
        $storeMediaImages = $uniqueImages;
        
    } catch (Exception $e) {
        // Silenciar erros
    }
}
?>

<!-- Modal Galeria de Mídia -->
<div class="media-gallery-overlay" id="mediaGalleryOverlay" onclick="closeMediaGallery(event)">
    <div class="media-gallery-modal" onclick="event.stopPropagation()">
        <div class="media-gallery-header">
            <h3>Selecionar arquivo</h3>
            <button type="button" class="media-gallery-close" onclick="closeMediaGallery()">
                <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
            </button>
        </div>
        
        <div class="media-gallery-toolbar">
            <div class="media-search">
                <iconify-icon icon="solar:magnifer-linear"></iconify-icon>
                <input type="text" id="mediaSearchInput" placeholder="Pesquisar arquivos" oninput="filterMediaGallery(this.value)">
            </div>
            <div class="media-filters">
                <button type="button" class="media-filter-btn" onclick="sortMediaGallery()">
                    <iconify-icon icon="solar:sort-vertical-linear"></iconify-icon>
                    Classificar
                </button>
                <button type="button" class="media-view-btn active" onclick="setMediaView('grid')">
                    <iconify-icon icon="solar:widget-4-linear"></iconify-icon>
                </button>
            </div>
        </div>
        
        <div class="media-gallery-content">
            <!-- Zona de Upload -->
            <div class="media-upload-zone" id="mediaUploadZone" 
                 ondragover="handleMediaDragOver(event)" 
                 ondragleave="handleMediaDragLeave(event)"
                 ondrop="handleMediaDrop(event)">
                <div class="media-upload-inner">
                    <button type="button" class="media-upload-btn" onclick="document.getElementById('mediaFileInput').click()">
                        Adicionar mídia <iconify-icon icon="solar:alt-arrow-down-linear"></iconify-icon>
                    </button>
                    <p>Arraste e solte imagens, vídeos, modelos 3D e arquivos</p>
                </div>
            </div>
            
            <input type="file" id="mediaFileInput" multiple accept="image/*" style="display:none" onchange="handleMediaUpload(this)">
            
            <!-- Grid de Imagens -->
            <div class="media-gallery-grid" id="mediaGalleryGrid">
                <?php if (!empty($storeMediaImages)): ?>
                    <?php foreach ($storeMediaImages as $img): ?>
                    <div class="media-gallery-item" data-url="<?php echo htmlspecialchars($img['image_url']); ?>" data-name="<?php echo htmlspecialchars($img['product_name'] ?? 'Imagem'); ?>">
                        <div class="media-item-checkbox">
                            <input type="checkbox" class="media-checkbox" onchange="toggleMediaSelection(this)">
                        </div>
                        <img src="<?php echo htmlspecialchars($img['image_url']); ?>" alt="<?php echo htmlspecialchars($img['product_name'] ?? 'Imagem'); ?>">
                        <span class="media-item-name"><?php echo htmlspecialchars(basename($img['image_url'])); ?></span>
                    </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="media-gallery-empty" id="mediaGalleryEmpty">
                        <iconify-icon icon="solar:gallery-minimalistic-outline" style="font-size: 3rem; opacity: 0.4;"></iconify-icon>
                        <p>Nenhuma imagem encontrada</p>
                        <small>Faça upload de imagens para começar</small>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Preview de novos uploads -->
            <div class="media-new-uploads" id="mediaNewUploads" style="display: none;">
                <h4>Novos uploads</h4>
                <div class="media-new-uploads-grid" id="mediaNewUploadsGrid"></div>
            </div>
        </div>
        
        <div class="media-gallery-footer">
            <button type="button" class="btn btn-secondary" onclick="closeMediaGallery()">Cancelar</button>
            <button type="button" class="btn btn-primary" onclick="confirmMediaSelection()">Concluído</button>
        </div>
    </div>
</div>

<style>
/* Media Gallery Overlay */
.media-gallery-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    z-index: 99999;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 1rem;
}

.media-gallery-overlay.active {
    display: flex;
}

/* Modal */
.media-gallery-modal {
    background: #fff;
    border-radius: 12px;
    width: 100%;
    max-width: 900px;
    max-height: 85vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

/* Header */
.media-gallery-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #e5e7eb;
}

.media-gallery-header h3 {
    margin: 0;
    font-size: 1.1rem;
    font-weight: 600;
    color: #1a1a1a;
}

.media-gallery-close {
    background: none;
    border: none;
    cursor: pointer;
    color: #6b7280;
    font-size: 1.5rem;
    display: flex;
    align-items: center;
    padding: 0.25rem;
    transition: color 0.2s;
}

.media-gallery-close:hover {
    color: #1a1a1a;
}

/* Toolbar */
.media-gallery-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.75rem 1.5rem;
    border-bottom: 1px solid #e5e7eb;
    background: #f9fafb;
    gap: 1rem;
    flex-wrap: wrap;
}

.media-search {
    display: flex;
    align-items: center;
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 0.5rem 0.75rem;
    flex: 1;
    max-width: 300px;
    gap: 0.5rem;
}

.media-search iconify-icon {
    color: #9ca3af;
    font-size: 1.1rem;
}

.media-search input {
    border: none;
    outline: none;
    flex: 1;
    font-size: 0.9rem;
    background: transparent;
}

.media-filters {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.media-filter-btn, .media-view-btn {
    display: flex;
    align-items: center;
    gap: 0.4rem;
    padding: 0.5rem 0.75rem;
    border: 1px solid #e5e7eb;
    background: #fff;
    border-radius: 8px;
    cursor: pointer;
    font-size: 0.85rem;
    color: #374151;
    transition: all 0.2s;
}

.media-filter-btn:hover, .media-view-btn:hover {
    background: #f3f4f6;
}

.media-view-btn.active {
    background: #e5e7eb;
}

/* Content */
.media-gallery-content {
    flex: 1;
    overflow-y: auto;
    padding: 1.5rem;
}

/* Upload Zone */
.media-upload-zone {
    border: 2px dashed #d1d5db;
    border-radius: 12px;
    padding: 2rem;
    text-align: center;
    margin-bottom: 1.5rem;
    transition: all 0.2s;
    background: #fafafa;
}

.media-upload-zone.dragover {
    border-color: var(--primary, #7c3aed);
    background: rgba(124, 58, 237, 0.05);
}

.media-upload-inner p {
    margin: 0.75rem 0 0;
    color: #6b7280;
    font-size: 0.9rem;
}

.media-upload-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.6rem 1rem;
    background: #fff;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    cursor: pointer;
    font-size: 0.9rem;
    font-weight: 500;
    color: #374151;
    transition: all 0.2s;
}

.media-upload-btn:hover {
    background: #f3f4f6;
    border-color: #9ca3af;
}

/* Grid */
.media-gallery-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
    gap: 1rem;
}

.media-gallery-item {
    position: relative;
    aspect-ratio: 1;
    border: 2px solid #e5e7eb;
    border-radius: 10px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.2s;
    background: #f9fafb;
}

.media-gallery-item:hover {
    border-color: #9ca3af;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.media-gallery-item.selected {
    border-color: var(--primary, #7c3aed);
    box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.2);
}

.media-gallery-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.media-item-checkbox {
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 2;
}

.media-item-checkbox input {
    width: 18px;
    height: 18px;
    cursor: pointer;
    accent-color: var(--primary, #7c3aed);
}

.media-item-name {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 0.5rem;
    background: linear-gradient(transparent, rgba(0,0,0,0.7));
    color: #fff;
    font-size: 0.7rem;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}

.media-gallery-empty {
    grid-column: 1 / -1;
    text-align: center;
    padding: 3rem;
    color: #6b7280;
}

.media-gallery-empty p {
    margin: 0.5rem 0 0.25rem;
    font-size: 1rem;
}

.media-gallery-empty small {
    color: #9ca3af;
}

/* New Uploads */
.media-new-uploads {
    margin-top: 1.5rem;
    padding-top: 1.5rem;
    border-top: 1px solid #e5e7eb;
}

.media-new-uploads h4 {
    margin: 0 0 1rem;
    font-size: 0.9rem;
    color: #374151;
}

.media-new-uploads-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 0.75rem;
}

.media-new-upload-item {
    position: relative;
    aspect-ratio: 1;
    border: 2px solid var(--primary, #7c3aed);
    border-radius: 8px;
    overflow: hidden;
    background: #f9fafb;
}

.media-new-upload-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.media-new-upload-item .remove-btn {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: rgba(239, 68, 68, 0.9);
    color: #fff;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.7rem;
}

/* Footer */
.media-gallery-footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 0.75rem;
    padding: 1rem 1.5rem;
    border-top: 1px solid #e5e7eb;
    background: #f9fafb;
}

.media-gallery-footer .btn {
    padding: 0.6rem 1.25rem;
    border-radius: 8px;
    font-size: 0.9rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
}

.media-gallery-footer .btn-secondary {
    background: #fff;
    border: 1px solid #d1d5db;
    color: #374151;
}

.media-gallery-footer .btn-secondary:hover {
    background: #f3f4f6;
}

.media-gallery-footer .btn-primary {
    background: #1a1a1a;
    border: 1px solid #1a1a1a;
    color: #fff;
}

.media-gallery-footer .btn-primary:hover {
    background: #333;
}

/* Responsive */
@media (max-width: 640px) {
    .media-gallery-modal {
        max-height: 95vh;
    }
    
    .media-gallery-toolbar {
        flex-direction: column;
        align-items: stretch;
    }
    
    .media-search {
        max-width: 100%;
    }
    
    .media-gallery-grid {
        grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    }
}
</style>

<script>
// ============================================
// GALERIA DE MÍDIA - MontaLoja
// ============================================

var mediaGalleryCallback = null;
var selectedMediaFiles = [];
var newUploadedFiles = [];

function openMediaGallery(callback) {
    mediaGalleryCallback = callback;
    selectedMediaFiles = [];
    newUploadedFiles = [];
    
    // Limpar seleções anteriores
    document.querySelectorAll('.media-gallery-item').forEach(item => {
        item.classList.remove('selected');
        var checkbox = item.querySelector('.media-checkbox');
        if (checkbox) checkbox.checked = false;
    });
    
    // Limpar novos uploads
    document.getElementById('mediaNewUploads').style.display = 'none';
    document.getElementById('mediaNewUploadsGrid').innerHTML = '';
    
    document.getElementById('mediaGalleryOverlay').classList.add('active');
    document.body.style.overflow = 'hidden';
}

function closeMediaGallery(event) {
    if (event && event.target !== document.getElementById('mediaGalleryOverlay')) {
        return;
    }
    document.getElementById('mediaGalleryOverlay').classList.remove('active');
    document.body.style.overflow = '';
}

function toggleMediaSelection(checkbox) {
    var item = checkbox.closest('.media-gallery-item');
    var url = item.dataset.url;
    
    if (checkbox.checked) {
        item.classList.add('selected');
        if (!selectedMediaFiles.includes(url)) {
            selectedMediaFiles.push(url);
        }
    } else {
        item.classList.remove('selected');
        var idx = selectedMediaFiles.indexOf(url);
        if (idx > -1) selectedMediaFiles.splice(idx, 1);
    }
}

function handleMediaDragOver(event) {
    event.preventDefault();
    event.currentTarget.classList.add('dragover');
}

function handleMediaDragLeave(event) {
    event.currentTarget.classList.remove('dragover');
}

function handleMediaDrop(event) {
    event.preventDefault();
    event.currentTarget.classList.remove('dragover');
    
    var files = event.dataTransfer.files;
    processMediaFiles(files);
}

function handleMediaUpload(input) {
    processMediaFiles(input.files);
    input.value = '';
}

function processMediaFiles(files) {
    var validTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
    var maxSize = 5 * 1024 * 1024; // 5MB
    
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        
        if (!validTypes.includes(file.type)) {
            alert('Tipo de arquivo não suportado: ' + file.name);
            continue;
        }
        
        if (file.size > maxSize) {
            alert('Arquivo muito grande (máx 5MB): ' + file.name);
            continue;
        }
        
        newUploadedFiles.push({
            file: file,
            url: URL.createObjectURL(file)
        });
    }
    
    renderNewUploads();
}

function renderNewUploads() {
    var container = document.getElementById('mediaNewUploads');
    var grid = document.getElementById('mediaNewUploadsGrid');
    
    if (newUploadedFiles.length === 0) {
        container.style.display = 'none';
        return;
    }
    
    container.style.display = 'block';
    grid.innerHTML = newUploadedFiles.map((item, index) => `
        <div class="media-new-upload-item" data-index="${index}">
            <img src="${item.url}" alt="Upload">
            <button type="button" class="remove-btn" onclick="removeNewUpload(${index})">×</button>
        </div>
    `).join('');
}

function removeNewUpload(index) {
    URL.revokeObjectURL(newUploadedFiles[index].url);
    newUploadedFiles.splice(index, 1);
    renderNewUploads();
}

function confirmMediaSelection() {
    // Combinar seleções existentes com novos uploads
    var result = {
        existingUrls: selectedMediaFiles,
        newFiles: newUploadedFiles.map(f => f.file)
    }
    
    if (mediaGalleryCallback && typeof mediaGalleryCallback === 'function') {
        mediaGalleryCallback(result);
    }
    
    closeMediaGallery();
}

function filterMediaGallery(query) {
    query = query.toLowerCase();
    document.querySelectorAll('.media-gallery-item').forEach(item => {
        var name = (item.dataset.name || '').toLowerCase();
        var url = (item.dataset.url || '').toLowerCase();
        if (name.includes(query) || url.includes(query)) {
            item.style.display = '';
        } else {
            item.style.display = 'none';
        }
    });
}

function sortMediaGallery() {
    // TODO: Implementar ordenação
    alert('Funcionalidade de ordenação em breve!');
}

function setMediaView(view) {
    // TODO: Implementar troca de visualização
}
</script>
