<?php
include "../includes/header2.php";

// CORREÇÃO: Verificar se o JSON existe antes de ler
$jsonFilex = "../a/rtx/logo_filenames_$seller_name.json";
$imageDatax = [];
$filenamex = '';
$uploadmethord = '';

// CORREÇÃO: Variáveis para controle de upload recente
$justUploaded = false;
$newImagePath = '';

// CORREÇÃO: Handle file upload - PRIMEIRO processar o upload
if (isset($_POST['upload'])) {
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['image'];
        $fileType = $file['type'];
        $fileTemp = $file['tmp_name'];

        // Validate the file type
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (in_array($fileType, $allowedTypes)) {
            // Define the path to store the uploaded image
            $folderPath = "../rtx/logo/$seller_name/";
            
            // Create directory if it doesn't exist
            if (!file_exists($folderPath)) {
                mkdir($folderPath, 0777, true);
            }

            // Clean up old files
            $selectedFiles = ['logo.png', 'index.php', 'iimg.json', 'filenames.json', 'binding_dark.webp', 'bg.jpg', 'api.php', 'favicon.ico', 'logo_ne.png', '.htaccess'];
            
            if (file_exists($folderPath)) {
                $files = scandir($folderPath);
                foreach ($files as $fileItem) {
                    if ($fileItem !== '.' && $fileItem !== '..' && !in_array($fileItem, $selectedFiles)) {
                        $filePath = $folderPath . $fileItem;
                        if (is_file($filePath)) {
                            unlink($filePath);
                        }
                    }
                }
            }

            // Generate unique filename
            $fileName = uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
            $destination = $folderPath . $fileName;

            // Move the uploaded file to the destination
            if (move_uploaded_file($fileTemp, $destination)) {
                // Save to JSON
                $jsonData = json_encode([["ImageName" => "../rtx/logo/$seller_name/" . $fileName, 'Upload_type' => 'by_file']]);
                file_put_contents($jsonFilex, $jsonData);
                
                // CORREÇÃO: Marcar que acabou de fazer upload e salvar o novo caminho
                $justUploaded = true;
                $newImagePath = "../rtx/logo/$seller_name/" . $fileName;
                $uploadSuccess = true;
            }
        }
    }
}

// CORREÇÃO: Image by URL handling
if (isset($_POST['url-submit'])) {
    $imageUrl = $_POST['image-url'];

    // CORREÇÃO: Caminho correto do JSON
    $jsonFilePath = "../a/rtx/logo_filenames_$seller_name.json";

    // Validate the URL
    if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
        $jsonData = json_encode([[
            'ImageName' => $imageUrl,
            'Upload_type' => 'by_url'
        ]]);

        if (file_put_contents($jsonFilePath, $jsonData)) {
            // CORREÇÃO: Marcar que acabou de fazer upload por URL
            $justUploaded = true;
            $newImagePath = $imageUrl;
            $uploadSuccess = true;
        }
    }
}

// CORREÇÃO: AGORA ler os dados atualizados do JSON
if (file_exists($jsonFilex)) {
    $jsonDatax = file_get_contents($jsonFilex);
    $imageDatax = json_decode($jsonDatax, true);
    
    if ($imageDatax && isset($imageDatax[0])) {
        $filenamex = $imageDatax[0]['ImageName'] ?? '';
        $uploadmethord = $imageDatax[0]['Upload_type'] ?? '';
    }
}

// CORREÇÃO: Se acabou de fazer upload, usar os novos dados diretamente
if ($justUploaded) {
    $filenamex = $newImagePath;
    $uploadmethord = isset($_POST['upload']) ? "by_file" : "by_url";
}

// CORREÇÃO: Processamento do caminho da imagem
if ($uploadmethord == "by_file") {
    $imageFilex = preg_replace('/^\.\.\//', '', $filenamex);
    $methord = "Upload Method";
} elseif ($uploadmethord == "by_url") {
    $imageFilex = $filenamex;
    $methord = "URL Method";
} else {
    $imageFilex = "https://c4.wallpaperflare.com/wallpaper/159/71/731/errors-minimalism-typography-red-wallpaper-preview.jpg";
    $methord = "Nenhum método";
}

// CORREÇÃO: Verificar se o arquivo existe para exibição
$displayPath = $uploadmethord == "by_file" ? "../" . $imageFilex : $imageFilex;
$fileExists = $uploadmethord == "by_file" ? file_exists("../" . $imageFilex) : true;

// CORREÇÃO: Se acabou de fazer upload e é arquivo, forçar que existe
if ($justUploaded && $uploadmethord == "by_file") {
    $fileExists = true;
}
?>

<style>
:root {
    --primary: #FF6B9D;
    --primary-dark: #D94A7E;
    --secondary: #00D4FF;
    --accent: #FFD166;
    --surface: #0A0F1C;
    --surface-light: #1A1F2C;
    --surface-lighter: #2A2F3C;
    --text-primary: #FFFFFF;
    --text-secondary: #B0B7C3;
    --text-muted: #6B7280;
    --border: rgba(255,255,255,0.1);
    --glow: 0 0 20px rgba(255, 107, 157, 0.3);
}

body {
    background: radial-gradient(1200px 600px at 30% -10%, rgba(255, 107, 157, 0.15), transparent),
                radial-gradient(1000px 500px at 80% 120%, rgba(0, 212, 255, 0.12), transparent),
                var(--surface);
    color: var(--text-primary);
    font-family: 'Inter', sans-serif;
}

.container-fluid {
    background: transparent !important;
    padding: 20px;
}

.h3 {
    color: var(--text-primary) !important;
    font-weight: 700;
    margin-bottom: 24px;
    text-align: center;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.card {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 20px !important;
    box-shadow: var(--glow) !important;
    backdrop-filter: blur(10px);
    margin-bottom: 24px;
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 40px rgba(255, 107, 157, 0.4);
}

.card-header {
    background: linear-gradient(135deg, var(--surface-lighter), var(--surface-light)) !important;
    border-bottom: 1px solid var(--border) !important;
    border-radius: 20px 20px 0 0 !important;
    padding: 20px 24px !important;
}

.text-primary2 {
    color: var(--text-primary) !important;
    font-weight: 600;
    font-size: 1.2rem;
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 0;
}

.card-body {
    padding: 30px !important;
}

.preview-image {
    max-width: 100%;
    height: auto;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    border: 3px solid var(--border);
    transition: all 0.3s ease;
    max-height: 200px;
    object-fit: contain;
    background: var(--surface-lighter);
    padding: 20px;
}

.preview-image:hover {
    transform: scale(1.05);
    border-color: var(--primary);
    box-shadow: 0 12px 40px rgba(255, 107, 157, 0.4);
}

.upload-options {
    display: flex;
    gap: 30px;
    margin: 30px 0;
    justify-content: center;
    flex-wrap: wrap;
}

.radio-option {
    position: relative;
    cursor: pointer;
}

.radio-option input[type="radio"] {
    display: none;
}

.radio-label {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 15px 20px;
    background: var(--surface-lighter);
    border: 2px solid var(--border);
    border-radius: 12px;
    color: var(--text-secondary);
    font-weight: 600;
    transition: all 0.3s ease;
}

.radio-option input[type="radio"]:checked + .radio-label {
    background: linear-gradient(135deg, var(--surface-lighter), rgba(255, 107, 157, 0.15));
    border-color: var(--primary);
    color: var(--text-primary);
    box-shadow: var(--glow);
    transform: translateY(-2px);
}

.radio-option:hover .radio-label {
    border-color: var(--secondary);
    transform: translateY(-2px);
}

.form-group {
    margin-bottom: 25px;
}

.form-group label {
    color: var(--text-primary);
    font-weight: 600;
    margin-bottom: 12px;
    display: block;
    font-size: 1.1rem;
}

.custom-button {
    background: var(--surface-lighter) !important;
    border: 2px solid var(--border) !important;
    border-radius: 10px !important;
    color: var(--text-primary) !important;
    padding: 12px 16px !important;
    transition: all 0.3s ease;
    width: 100%;
}

.custom-button:focus {
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 0.2rem rgba(255, 107, 157, 0.25) !important;
    outline: none;
}

.btn-success {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important;
    border: none !important;
    border-radius: 10px !important;
    padding: 12px 24px !important;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: var(--glow);
}

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(255, 107, 157, 0.5);
}

#url-form {
    display: none;
}

.current-method {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: var(--text-primary);
    padding: 10px 20px;
    border-radius: 25px;
    font-size: 1rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    margin: 15px 0;
    box-shadow: var(--glow);
}

.info-box {
    background: rgba(0, 212, 255, 0.1);
    border: 1px solid var(--secondary);
    border-radius: 12px;
    padding: 20px;
    margin: 25px 0;
    color: var(--text-secondary);
}

.info-box strong {
    color: var(--text-primary);
}

/* === TOAST NOTIFICATION MODERNO === */
.toast-notification {
    position: fixed;
    top: 20px;
    right: 20px;
    background: var(--surface-lighter);
    color: var(--text-primary);
    padding: 16px 20px;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    border: 1px solid var(--border);
    z-index: 10000;
    transform: translateX(400px);
    opacity: 0;
    transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    max-width: 350px;
    backdrop-filter: blur(10px);
}

.toast-notification.show {
    transform: translateX(0);
    opacity: 1;
}

.toast-notification.success {
    border-left: 4px solid #00D4FF;
    background: rgba(0, 212, 255, 0.1);
}

.toast-notification.error {
    border-left: 4px solid #FF4757;
    background: rgba(255, 71, 87, 0.1);
}

.toast-notification .toast-content {
    display: flex;
    align-items: center;
    gap: 12px;
}

.toast-notification .toast-icon {
    font-size: 1.2rem;
    flex-shrink: 0;
}

.toast-notification .toast-message {
    flex: 1;
    font-weight: 500;
    line-height: 1.4;
}

.toast-progress {
    position: absolute;
    bottom: 0;
    left: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--primary), var(--accent));
    border-radius: 0 0 12px 12px;
    animation: progress 3s linear forwards;
}

@keyframes progress {
    0% { width: 100%; }
    100% { width: 0%; }
}
</style>

<!-- Toast Notification Container -->
<div id="toastContainer"></div>

<script>
// Sistema de Toast Notification
function showToast(message, type = 'success') {
    const toastContainer = document.getElementById('toastContainer');
    const toastId = 'toast-' + Date.now();
    
    const toast = document.createElement('div');
    toast.className = `toast-notification ${type}`;
    toast.id = toastId;
    toast.innerHTML = `
        <div class="toast-content">
            <div class="toast-icon">${type === 'success' ? '✅' : '❌'}</div>
            <div class="toast-message">${message}</div>
        </div>
        <div class="toast-progress"></div>
    `;
    
    toastContainer.appendChild(toast);
    
    // Mostrar toast
    setTimeout(() => {
        toast.classList.add('show');
    }, 100);
    
    // Remover toast após 3 segundos
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 400);
    }, 3000);
}

// Mostrar toast de sucesso se houve upload
<?php if (isset($uploadSuccess) && $uploadSuccess): ?>
    document.addEventListener('DOMContentLoaded', function() {
        showToast('✅ Logotipo atualizado com sucesso!', 'success');
        
        // CORREÇÃO: Forçar atualização da imagem com timestamp
        setTimeout(() => {
            const previewImg = document.querySelector('.preview-image');
            if (previewImg) {
                const currentSrc = previewImg.src;
                const newSrc = currentSrc.split('?')[0] + '?t=' + new Date().getTime();
                previewImg.src = newSrc;
            }
        }, 500);
    });
<?php endif; ?>

// Validação de arquivo com toast
document.getElementById('image').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const maxSize = 10 * 1024 * 1024; // 10MB
        if (file.size > maxSize) {
            showToast('❌ Arquivo muito grande! Máximo 10MB permitido.', 'error');
            e.target.value = '';
        } else {
            showToast('✅ Arquivo válido! Clique em Upload para continuar.', 'success');
        }
    }
});

// Validação de URL com toast
document.getElementById('url-form').addEventListener('submit', function(e) {
    const url = document.getElementById('image-url').value;
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
        e.preventDefault();
        showToast('❌ URL deve começar com http:// ou https://', 'error');
    }
});

// Feedback visual para upload
document.getElementById('upload-form').addEventListener('submit', function(e) {
    const fileInput = document.getElementById('image');
    if (!fileInput.value) {
        e.preventDefault();
        showToast('❌ Selecione um arquivo antes de enviar!', 'error');
        return false;
    }
    showToast('⏳ Enviando logotipo, aguarde...', 'success');
    return true;
});
</script>

<div class="container-fluid">
    <!-- Page Heading -->
    <h1 class="h3 mb-4 text-gray-800"> 
        <i class="fas fa-crown"></i> Alterar Logotipo
    </h1>
    
    <!-- Custom codes -->
    <div class="card border-left-primary shadow h-100 card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary2">
                <i class="fas fa-cogs"></i> Gerenciar Logotipo
            </h6>
        </div>
        <div class="card-body">
            <!-- Exibição do logotipo atual -->
            <div style="text-align: center; margin-bottom: 30px;">
                <h3 style="color: var(--text-primary); margin-bottom: 10px;">
                    Logotipo Atual:
                </h3>
                <div class="current-method">
                    <i class="fas fa-info-circle"></i>
                    <?php echo $methord; ?>
                </div>
                <br>
                <?php if (!$fileExists && $uploadmethord == "by_file" && !$justUploaded): ?>
                    <div style="color: var(--accent); margin: 10px 0;">
                        <i class="fas fa-exclamation-triangle"></i> Arquivo não encontrado no servidor
                    </div>
                <?php endif; ?>
                <img class="preview-image" 
                     src="<?php echo $fileExists ? $displayPath : 'https://c4.wallpaperflare.com/wallpaper/159/71/731/errors-minimalism-typography-red-wallpaper-preview.jpg'; ?>" 
                     alt="Logotipo Atual" 
                     onerror="this.src='https://c4.wallpaperflare.com/wallpaper/159/71/731/errors-minimalism-typography-red-wallpaper-preview.jpg'"
                     style="max-width: 400px; max-height: 200px;">
            </div>

            <!-- Informações -->
            <div class="info-box">
                <strong><i class="fas fa-info-circle"></i> Informações:</strong><br>
                • Formatos suportados: JPG, PNG, GIF, WEBP<br>
                • Tamanho máximo: 10MB<br>
                • Para URLs: Use links diretos para imagens
            </div>

            <!-- Opções de Upload -->
            <div class="upload-options">
                <div class="radio-option">
                    <input type="radio" name="upload-type" id="upload-radio" checked>
                    <label for="upload-radio" class="radio-label">
                        <i class="fas fa-upload"></i>
                        <span>Definir logotipo usando arquivo</span>
                    </label>
                </div>
                <div class="radio-option">
                    <input type="radio" name="upload-type" id="url-radio">
                    <label for="url-radio" class="radio-label">
                        <i class="fas fa-link"></i>
                        <span>Definir logotipo usando URL</span>
                    </label>
                </div>
            </div>

            <!-- Formulário de Upload por Arquivo -->
            <form method="post" enctype="multipart/form-data" id="upload-form">
                <div class="form-group">
                    <label for="image">
                        <i class="fas fa-file-image"></i> Selecione uma imagem para carregar:
                    </label>
                    <input class="custom-button" type="file" name="image" id="image" 
                           accept="image/jpeg, image/png, image/gif, image/webp" required>
                    <small style="color: var(--text-muted); display: block; margin-top: 8px;">
                        Formatos: JPG, PNG, GIF, WEBP | Máx: 10MB
                    </small>
                </div>
                <button class="btn btn-success btn-icon-split" type="submit" name="upload">
                    <span class="icon text-white-50">
                        <i class="fas fa-cloud-upload-alt"></i>
                    </span>
                    <span class="text">Upload</span>
                </button>
            </form>
            
            <!-- Formulário de Upload por URL -->
            <form method="post" id="url-form">
                <div class="form-group">
                    <label for="image-url">
                        <i class="fas fa-link"></i> Selecione um URL de imagem:
                    </label>
                    <input class="custom-button" type="text" name="image-url" id="image-url" 
                           placeholder="https://example.com/image.jpg" required>
                    <small style="color: var(--text-muted); display: block; margin-top: 8px;">
                        Use URLs diretas para imagens
                    </small>
                </div>
                <button class="btn btn-success btn-icon-split" type="submit" name="url-submit">
                    <span class="icon text-white-50">
                        <i class="fas fa-check"></i>
                    </span>
                    <span class="text">Submit URL</span>
                </button>
            </form>
            
            <script>
                const uploadRadio = document.getElementById('upload-radio');
                const urlRadio = document.getElementById('url-radio');
                const uploadForm = document.getElementById('upload-form');
                const urlForm = document.getElementById('url-form');
            
                uploadRadio.addEventListener('change', () => {
                    uploadForm.style.display = 'block';
                    urlForm.style.display = 'none';
                });
            
                urlRadio.addEventListener('change', () => {
                    uploadForm.style.display = 'none';
                    urlForm.style.display = 'block';
                });

                // Prevenir reenvio do formulário
                if (window.history.replaceState) {
                    window.history.replaceState(null, null, window.location.href);
                }
            </script>
        </div>
    </div>
</div>

<?php
include "../includes/footer2.php";
?>
</body>
</html>