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

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

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: Processamento do caminho da imagem
if ($uploadmethord == "by_file") {
    // Remove apenas o "../" do início se existir
    $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 COMPLETA: Handle file 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'];
        $fileSize = $file['size'];

        // Validate the file type - CORREÇÃO: Adicionar webp
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (in_array($fileType, $allowedTypes)) {
            // CORREÇÃO: Definir caminho correto
            $folderPath = "../rtx/Img/$seller_name/";
            
            // CORREÇÃO: Criar pasta se não existir
            if (!file_exists($folderPath)) {
                if (!mkdir($folderPath, 0777, true)) {
                    $toastMessage = "Erro ao criar pasta!";
                    $toastType = "error";
                }
            }

            // CORREÇÃO: Limpar arquivos antigos ANTES do upload
            $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);
                        }
                    }
                }
            }

            // CORREÇÃO: Gerar nome único
            $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $fileName = uniqid() . '.' . $fileExtension;
            $destination = $folderPath . $fileName;

            // CORREÇÃO: Mover arquivo com verificação
            if (move_uploaded_file($fileTemp, $destination)) {
                // CORREÇÃO: Salvar caminho relativo correto no JSON
                $jsonData = json_encode([[
                    "ImageName" => "../rtx/Img/$seller_name/" . $fileName,
                    'Upload_type' => 'by_file'
                ]]);
                
                if (file_put_contents($jsonFilex, $jsonData)) {
                    $toastMessage = "✅ Upload realizado com sucesso!";
                    $toastType = "success";
                    // CORREÇÃO: Redirecionar após 2 segundos
                    echo "<script>
                        setTimeout(() => {
                            window.location.href = 'Image.php';
                        }, 2000);
                    </script>";
                } else {
                    $toastMessage = "❌ Erro ao salvar configurações!";
                    $toastType = "error";
                }
            } else {
                $toastMessage = "❌ Erro ao mover arquivo!";
                $toastType = "error";
            }
        } else {
            $toastMessage = "❌ Tipo de arquivo inválido! Use JPEG, PNG, GIF ou WEBP.";
            $toastType = "error";
        }
    } else {
        $uploadError = $_FILES['image']['error'] ?? 'Unknown error';
        $toastMessage = "❌ Erro no upload: $uploadError";
        $toastType = "error";
    }
}

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

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

        if (file_put_contents($jsonFilex, $jsonData)) {
            $toastMessage = "✅ URL salva com sucesso!";
            $toastType = "success";
            // CORREÇÃO: Redirecionar após 2 segundos
            echo "<script>
                setTimeout(() => {
                    window.location.href = 'Image.php';
                }, 2000);
            </script>";
        } else {
            $toastMessage = "❌ Erro ao salvar URL!";
            $toastType = "error";
        }
    } else {
        $toastMessage = "❌ URL inválida!";
        $toastType = "error";
    }
}
?>

<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: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    border: 2px solid var(--border);
    transition: all 0.3s ease;
    max-height: 300px;
    object-fit: cover;
}

.preview-image:hover {
    transform: scale(1.02);
    border-color: var(--primary);
}

.upload-options {
    display: flex;
    gap: 20px;
    margin: 20px 0;
    flex-wrap: wrap;
}

.radio-option {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--text-primary);
    font-weight: 500;
}

.radio-option input[type="radio"] {
    accent-color: var(--primary);
}

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

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

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

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(255, 107, 157, 0.4);
}

#url-form {
    display: none;
}

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

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

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

.info-box {
    background: rgba(0, 212, 255, 0.1);
    border: 1px solid var(--secondary);
    border-radius: 12px;
    padding: 16px;
    margin: 20px 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%; }
}

/* === RESPONSIVIDADE === */
@media (max-width: 768px) {
    .toast-notification {
        top: 10px;
        right: 10px;
        left: 10px;
        max-width: none;
    }
}
</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 se houver mensagem do PHP
<?php if (isset($toastMessage)): ?>
    document.addEventListener('DOMContentLoaded', function() {
        showToast('<?php echo $toastMessage; ?>', '<?php echo $toastType ?? 'success'; ?>');
    });
<?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 imagem, aguarde...', 'success');
    return true;
});
</script>

<div class="container-fluid">
    <!-- Page Heading -->
    <h1 class="h3 mb-4 text-gray-800"> 
        <i class="fas fa-image"></i> Image Background
    </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="fa fa-cogs"></i> Escolher Banner
            </h6>
        </div>
        <div class="card-body">
            <!-- CORREÇÃO: Exibição da imagem atual -->
            <div style="text-align: center; margin-bottom: 30px;">
                <h3 style="color: var(--text-primary); margin-bottom: 10px;">
                    Atualmente em uso:
                </h3>
                <div class="current-method">
                    <i class="fas fa-info-circle"></i>
                    <?php echo $methord; ?>
                </div>
                <br>
                <?php
                // CORREÇÃO: Verificar se o arquivo existe
                $displayPath = $uploadmethord == "by_file" ? "../" . $imageFilex : $imageFilex;
                $fileExists = $uploadmethord == "by_file" ? file_exists("../" . $imageFilex) : true;
                
                if (!$fileExists && $uploadmethord == "by_file") {
                    echo '<div style="color: var(--accent); margin: 10px 0;">';
                    echo '<i class="fas fa-exclamation-triangle"></i> Arquivo não encontrado no servidor';
                    echo '</div>';
                }
                ?>
                <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="Uploaded Image" 
                     onerror="this.src='https://c4.wallpaperflare.com/wallpaper/159/71/731/errors-minimalism-typography-red-wallpaper-preview.jpg'"
                     style="max-width: 600px; max-height: 300px;">
            </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">Definir plano de fundo usando arquivo</label>
                </div>
                <div class="radio-option">
                    <input type="radio" name="upload-type" id="url-radio">
                    <label for="url-radio">Definir plano de fundo usando URL</label>
                </div>
            </div>

            <!-- Formulários -->
            <form method="post" enctype="multipart/form-data" id="upload-form">
                <div class="form-group">
                    <label for="image">
                        <i class="fas fa-upload"></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
                           style="width: 100%; padding: 12px;">
                    <small style="color: var(--text-muted); display: block; margin-top: 5px;">
                        Formatos: JPG, PNG, GIF, WEBP | Máx: 10MB
                    </small>
                </div>
                <button class="btn btn-success btn-icon-split" type="submit" name="upload" style="padding: 12px 24px;">
                    <span class="icon text-white-50">
                        <i class="fas fa-cloud-upload-alt"></i>
                    </span>
                    <span class="text">Upload</span>
                </button>
            </form>
            
            <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
                           style="width: 100%; padding: 12px;">
                    <small style="color: var(--text-muted); display: block; margin-top: 5px;">
                        Use URLs diretas para imagens (https://...)
                    </small>
                </div>
                <button class="btn btn-success btn-icon-split" type="submit" name="url-submit" style="padding: 12px 24px;">
                    <span class="icon text-white-50">
                        <i class="fas fa-check"></i>
                    </span>
                    <span class="text">Enviar 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';
                });
            </script>
        </div>
    </div>
</div>

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