<?php
// create_ads.php
include ('includes/header.php');

// Configurações
$table_name = "ads";
$base_file = "ads.php";
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';

// Processar criação se o formulário foi enviado
if(isset($_POST['submit'])) {
    $title = $_POST['title'];
    $upload_type = $_POST['upload_type']; // 'url' ou 'file'
    $url = "";
    
    if ($upload_type == 'file' && isset($_FILES['image_file'])) {
        $file = $_FILES['image_file'];
        $fileType = $file['type'];
        $fileTemp = $file['tmp_name'];
        
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'video/mp4', 'video/webm', 'video/ogg'];
        if (in_array($fileType, $allowedTypes)) {
            $uploadPath = 'rtx/ads/ADM/';
            $fileName = uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
            $destination = $uploadPath . $fileName;
            
            if (move_uploaded_file($fileTemp, $destination)) {
                $url = $destination;
            } else {
                $error_msg = "Falha ao mover o arquivo enviado.";
            }
        } else {
            $error_msg = "Tipo de arquivo inválido.";
        }
    } else {
        $url = $_POST['url'];
    }
    
    if ($url != "") {
        // Usar escape para evitar SQL injection
        $title = $adb->escapeString($title);
        $url = $adb->escapeString($url);
        
        // Inserir no banco de dados
        $result = $adb->exec("INSERT INTO {$table_name}(title, url, owner) VALUES('{$title}', '{$url}', '{$admin_name}')");
        
        if($result !== false) {
            // Mostrar mensagem de sucesso
            ?>
            <style>
            .success-container {
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 80vh;
            }
            
            .success-card {
                background: linear-gradient(145deg, rgba(30, 41, 59, 0.9), rgba(15, 23, 42, 0.95));
                backdrop-filter: blur(20px);
                border-radius: 24px;
                border: 1px solid rgba(99, 102, 241, 0.3);
                box-shadow: 0 0 40px rgba(99, 102, 241, 0.2);
                padding: 50px 40px;
                text-align: center;
                max-width: 500px;
                width: 90%;
                position: relative;
                overflow: hidden;
            }
            
            .success-card::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                height: 4px;
                background: linear-gradient(90deg, var(--primary), var(--secondary));
                border-radius: 24px 24px 0 0;
            }
            
            .success-icon {
                font-size: 80px;
                color: var(--primary);
                margin-bottom: 25px;
                text-shadow: 0 0 20px rgba(99, 102, 241, 0.5);
            }
            
            .success-title {
                font-size: 2rem;
                font-weight: 800;
                background: linear-gradient(135deg, var(--primary), var(--primary-dark));
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                margin-bottom: 15px;
            }
            
            .success-message {
                color: var(--text-secondary);
                font-size: 1.1rem;
                margin-bottom: 30px;
                line-height: 1.5;
            }
            
            .countdown {
                color: var(--primary);
                font-weight: 700;
                font-size: 1.2rem;
                margin-top: 20px;
            }
            
            .loading-bar {
                width: 100%;
                height: 4px;
                background: rgba(30, 41, 59, 0.5);
                border-radius: 2px;
                margin-top: 30px;
                overflow: hidden;
            }
            
            .loading-progress {
                width: 0%;
                height: 100%;
                background: linear-gradient(90deg, var(--primary), var(--secondary));
                border-radius: 2px;
                animation: loading 2s linear forwards;
            }
            
            @keyframes loading {
                from { width: 0%; }
                to { width: 100%; }
            }
            </style>
            
            <div class="success-container">
                <div class="success-card">
                    <i class="fas fa-check-circle success-icon"></i>
                    <h1 class="success-title">Anúncio criado!</h1>
                    
                    <div class="success-message">
                        O anúncio <strong>"<?= htmlspecialchars($title) ?>"</strong><br>
                        foi criado com sucesso.
                    </div>
                    
                    <div class="loading-bar">
                        <div class="loading-progress"></div>
                    </div>
                    
                    <div class="countdown">
                        Redirecionando em <span id="countdown-number">2</span> segundos...
                    </div>
                    
                    <div style="margin-top: 30px;">
                        <a href="<?= $base_file ?>?filter=<?= $filter ?>" class="neon-btn" style="background: linear-gradient(135deg, var(--primary), var(--primary-dark));">
                            <i class="fas fa-arrow-left"></i> Voltar agora
                        </a>
                    </div>
                </div>
            </div>
            
            <script>
            let countdown = 2;
            const countdownElement = document.getElementById('countdown-number');
            const interval = setInterval(function() {
                countdown--;
                countdownElement.textContent = countdown;
                if (countdown <= 0) {
                    clearInterval(interval);
                    window.location.href = '<?= $base_file ?>?filter=<?= $filter ?>';
                }
            }, 1000);
            </script>
            <?php
            include ('includes/footer.php');
            exit;
        }
    }
}

// Exibir formulário de criação
?>
<style>
:root {
    --primary: #6366f1;
    --primary-dark: #4f46e5;
    --secondary: #10b981;
    --accent: #f59e0b;
    --danger: #ef4444;
    --dark-bg: #0f172a;
    --dark-surface: #1e293b;
    --dark-surface-light: #334155;
    --text-primary: #f1f5f9;
    --text-secondary: #94a3b8;
    --text-muted: #64748b;
    --border: rgba(255, 255, 255, 0.1);
    --glow: 0 0 20px rgba(99, 102, 241, 0.3);
    --glass-bg: rgba(30, 41, 59, 0.7);
    --glass-border: rgba(255, 255, 255, 0.05);
}

.neon-container {
    max-width: 1000px;
    margin: 0 auto;
}

.neon-header {
    text-align: center;
    margin-bottom: 40px;
    position: relative;
    padding-bottom: 20px;
}

.neon-header::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 25%;
    right: 25%;
    height: 3px;
    background: linear-gradient(90deg, transparent, var(--primary), var(--secondary), transparent);
    border-radius: 3px;
}

.neon-title {
    font-size: 2.5rem;
    font-weight: 800;
    background: linear-gradient(135deg, var(--primary), var(--secondary));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-bottom: 10px;
}

.neon-card {
    background: linear-gradient(145deg, rgba(30, 41, 59, 0.8), rgba(15, 23, 42, 0.9));
    backdrop-filter: blur(20px);
    border-radius: 24px;
    border: 1px solid var(--glass-border);
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
    padding: 40px;
    margin-bottom: 30px;
    position: relative;
    overflow: hidden;
}

.neon-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--primary), var(--secondary));
    border-radius: 24px 24px 0 0;
}

.preview-section {
    background: rgba(15, 23, 42, 0.6);
    border-radius: 16px;
    padding: 25px;
    margin-top: 25px;
    border: 1px solid var(--glass-border);
}

.preview-box-large {
    width: 100%;
    height: 250px;
    border-radius: 12px;
    overflow: hidden;
    position: relative;
    border: 2px solid rgba(99, 102, 241, 0.3);
    background: rgba(15, 23, 42, 0.8);
    margin-top: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.preview-media-large {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

.neon-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    padding: 14px 28px;
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    border: none;
    border-radius: 14px;
    font-size: 15px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    box-shadow: var(--glow);
}

.neon-btn:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 25px rgba(99, 102, 241, 0.4);
    color: white;
}

.neon-btn.secondary {
    background: linear-gradient(135deg, var(--dark-surface-light), var(--dark-surface));
    border: 1px solid var(--border);
}

.neon-input {
    width: 100%;
    padding: 16px 20px;
    background: rgba(15, 23, 42, 0.6);
    border: 2px solid rgba(99, 102, 241, 0.2);
    border-radius: 14px;
    color: var(--text-primary);
    font-size: 15px;
    font-weight: 500;
    transition: all 0.3s ease;
    outline: none;
}

.neon-input:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

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

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

.method-selector {
    display: flex;
    gap: 15px;
    margin-bottom: 25px;
}

.method-btn {
    flex: 1;
    padding: 15px;
    background: rgba(30, 41, 59, 0.5);
    border: 2px solid rgba(99, 102, 241, 0.2);
    border-radius: 14px;
    color: var(--text-secondary);
    cursor: pointer;
    text-align: center;
    transition: all 0.3s ease;
    font-weight: 600;
}

.method-btn.active {
    background: rgba(99, 102, 241, 0.1);
    border-color: var(--primary);
    color: var(--primary);
    box-shadow: 0 0 15px rgba(99, 102, 241, 0.2);
}
</style>

<div class="neon-container">
    <div class="neon-header">
        <h1 class="neon-title">Novo Banner</h1>
        <p style="color: var(--text-secondary);">Crie um novo anúncio para o seu aplicativo</p>
    </div>

    <div class="neon-card">
        <form action="" method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <label for="title">Título do Anúncio</label>
                <input type="text" name="title" id="title" class="neon-input" placeholder="Ex: Promoção de Verão" required>
            </div>

            <div class="form-group">
                <label>Método de Adição</label>
                <div class="method-selector">
                    <div class="method-btn active" id="btn-file" onclick="setMethod('file')">
                        <i class="fas fa-file-upload"></i> Upload de Arquivo
                    </div>
                    <div class="method-btn" id="btn-url" onclick="setMethod('url')">
                        <i class="fas fa-link"></i> Link Externo (URL)
                    </div>
                </div>
                <input type="hidden" name="upload_type" id="upload_type" value="file">
            </div>

            <div id="section-file" class="form-group">
                <label for="image_file">Selecione a Imagem ou Vídeo</label>
                <input type="file" name="image_file" id="image_file" class="neon-input" accept="image/*,video/*" onchange="previewFile(this)">
                <p style="color: var(--text-muted); font-size: 12px; mt-2;">Formatos aceitos: JPG, PNG, GIF, SVG, MP4, WEBM</p>
            </div>

            <div id="section-url" class="form-group" style="display: none;">
                <label for="url">URL da Mídia</label>
                <input type="text" name="url" id="url" class="neon-input" placeholder="https://exemplo.com/banner.jpg" oninput="previewUrl(this.value)">
            </div>

            <div class="preview-section">
                <label>Pré-visualização</label>
                <div class="preview-box-large" id="preview-container">
                    <div id="preview-placeholder" style="color: var(--text-muted); text-align: center;">
                        <i class="fas fa-image" style="font-size: 40px; margin-bottom: 10px;"></i>
                        <p>Nenhuma mídia selecionada</p>
                    </div>
                </div>
            </div>

            <div style="display: flex; gap: 15px; margin-top: 40px;">
                <button type="submit" name="submit" class="neon-btn" style="flex: 2;">
                    <i class="fas fa-save"></i> Salvar Anúncio
                </button>
                <a href="<?= $base_file ?>?filter=<?= $filter ?>" class="neon-btn secondary" style="flex: 1;">
                    Cancelar
                </a>
            </div>
        </form>
    </div>
</div>

<script>
function setMethod(method) {
    document.getElementById('upload_type').value = method;
    document.getElementById('btn-file').classList.toggle('active', method === 'file');
    document.getElementById('btn-url').classList.toggle('active', method === 'url');
    document.getElementById('section-file').style.display = method === 'file' ? 'block' : 'none';
    document.getElementById('section-url').style.display = method === 'url' ? 'block' : 'none';
    
    // Reset preview when switching
    document.getElementById('preview-container').innerHTML = '<div id="preview-placeholder" style="color: var(--text-muted); text-align: center;"><i class="fas fa-image" style="font-size: 40px; margin-bottom: 10px;"></i><p>Nenhuma mídia selecionada</p></div>';
}

function previewFile(input) {
    const container = document.getElementById('preview-container');
    if (input.files && input.files[0]) {
        const file = input.files[0];
        const reader = new FileReader();
        
        reader.onload = function(e) {
            if (file.type.startsWith('image/')) {
                container.innerHTML = `<img src="${e.target.result}" class="preview-media-large">`;
            } else if (file.type.startsWith('video/')) {
                container.innerHTML = `<video src="${e.target.result}" class="preview-media-large" controls autoplay muted loop></video>`;
            }
        }
        reader.readAsDataURL(file);
    }
}

function previewUrl(url) {
    const container = document.getElementById('preview-container');
    if (!url) {
        container.innerHTML = '<div id="preview-placeholder" style="color: var(--text-muted); text-align: center;"><i class="fas fa-image" style="font-size: 40px; margin-bottom: 10px;"></i><p>Nenhuma mídia selecionada</p></div>';
        return;
    }
    
    const isVideo = url.match(/\.(mp4|webm|ogg)/i);
    if (isVideo) {
        container.innerHTML = `<video src="${url}" class="preview-media-large" controls autoplay muted loop></video>`;
    } else {
        container.innerHTML = `<img src="${url}" class="preview-media-large" onerror="this.parentElement.innerHTML='<p style=\'color: var(--danger)\'>Erro ao carregar mídia da URL</p>'">`;
    }
}
</script>

<?php
include ('includes/footer.php');
?>
