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

// Configurações
$table_name = "ads";
$base_file = "ads.php";

// Verificar se foi passado um ID para editar
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
    $id = (int)$_GET['id'];
    $filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
    
    // Buscar dados do anúncio para preencher o formulário
    $result = $adb->query("SELECT * FROM {$table_name} WHERE id = {$id}");
    $row = $result->fetchArray();
    
    if(!$row) {
        header("Location: {$base_file}?filter={$filter}");
        exit;
    }

    // Processar atualização se o formulário foi enviado
    if(isset($_POST['submit'])) {
        $title = $_POST['title'];
        $upload_type = $_POST['upload_type'];
        $url = $row['url']; // Manter a URL atual por padrão
        
        if ($upload_type == 'file' && isset($_FILES['image_file']) && $_FILES['image_file']['size'] > 0) {
            $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)) {
                // Se o anúncio anterior tinha um arquivo físico, vamos removê-lo
                if (strpos($url, 'rtx/ads/ADM/') !== false && file_exists($url)) {
                    unlink($url);
                }
                
                $uploadPath = 'rtx/ads/ADM/';
                $fileName = uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
                $destination = $uploadPath . $fileName;
                
                if (move_uploaded_file($fileTemp, $destination)) {
                    $url = $destination;
                }
            }
        } elseif ($upload_type == 'url') {
            $new_url = $_POST['url'];
            // Se mudou de arquivo físico para URL, remove o arquivo antigo
            if ($new_url != $url && strpos($url, 'rtx/ads/ADM/') !== false && file_exists($url)) {
                unlink($url);
            }
            $url = $new_url;
        }
        
        // Usar escape para evitar SQL injection
        $title = $adb->escapeString($title);
        $url = $adb->escapeString($url);
        
        // Atualizar no banco de dados
        $result = $adb->exec("UPDATE {$table_name} SET title = '{$title}', url = '{$url}' WHERE id = {$id}");
        
        if($result !== false) {
            ?>
            <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); padding: 50px 40px; text-align: center; max-width: 500px; width: 90%; position: relative; }
            .success-icon { font-size: 80px; color: var(--primary); margin-bottom: 25px; }
            .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; }
            .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-radius: 14px; text-decoration: none; font-weight: 600; }
            </style>
            <div class="success-container">
                <div class="success-card">
                    <i class="fas fa-check-circle success-icon"></i>
                    <h1 class="success-title">Atualizado!</h1>
                    <p style="color: var(--text-secondary); margin: 20px 0;">O anúncio foi atualizado com sucesso.</p>
                    <div id="countdown" style="color: var(--primary); font-weight: bold; margin-bottom: 20px;">Redirecionando em 2s...</div>
                    <a href="<?= $base_file ?>?filter=<?= $filter ?>" class="neon-btn">Voltar agora</a>
                </div>
            </div>
            <script>
            let t = 2; setInterval(() => { t--; document.getElementById('countdown').innerText = `Redirecionando em ${t}s...`; if(t<=0) window.location.href='<?= $base_file ?>?filter=<?= $filter ?>'; }, 1000);
            </script>
            <?php
            include ('includes/footer.php');
            exit;
        }
    }
} else {
    header("Location: {$base_file}");
    exit;
}

$is_local_file = strpos($row['url'], 'rtx/ads/ADM/') !== false;
?>

<style>
:root {
    --primary: #6366f1; --primary-dark: #4f46e5; --secondary: #10b981; --dark-bg: #0f172a; --dark-surface: #1e293b;
    --text-primary: #f1f5f9; --text-secondary: #94a3b8; --border: rgba(255, 255, 255, 0.1);
}
.neon-container { max-width: 1000px; margin: 0 auto; }
.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 rgba(255, 255, 255, 0.05); padding: 40px; 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)); }
.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); outline: none; transition: 0.3s; }
.neon-input:focus { border-color: var(--primary); }
.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: 0.3s; font-weight: 600; }
.method-btn.active { background: rgba(99, 102, 241, 0.1); border-color: var(--primary); color: var(--primary); }
.preview-box { width: 100%; height: 250px; border-radius: 12px; border: 2px solid rgba(99, 102, 241, 0.3); background: rgba(15, 23, 42, 0.8); display: flex; align-items: center; justify-content: center; overflow: hidden; margin-top: 15px; }
.preview-media { 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-weight: 600; cursor: pointer; text-decoration: none; }
.neon-btn.secondary { background: linear-gradient(135deg, #334155, #1e293b); }
</style>

<div class="neon-container">
    <div style="text-align: center; margin-bottom: 40px;">
        <h1 style="font-size: 2.5rem; font-weight: 800; background: linear-gradient(135deg, var(--primary), var(--secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">Editar Banner</h1>
    </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" value="<?= htmlspecialchars($row['title']) ?>" required>
            </div>

            <div class="form-group">
                <label>Método de Mídia</label>
                <div class="method-selector">
                    <div class="method-btn <?= $is_local_file ? 'active' : '' ?>" id="btn-file" onclick="setMethod('file')">
                        <i class="fas fa-file-upload"></i> Upload de Arquivo
                    </div>
                    <div class="method-btn <?= !$is_local_file ? 'active' : '' ?>" 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="<?= $is_local_file ? 'file' : 'url' ?>">
            </div>

            <div id="section-file" class="form-group" style="display: <?= $is_local_file ? 'block' : 'none' ?>;">
                <label for="image_file">Alterar Arquivo (deixe vazio para manter atual)</label>
                <input type="file" name="image_file" id="image_file" class="neon-input" accept="image/*,video/*" onchange="previewFile(this)">
                <?php if($is_local_file): ?>
                    <p style="color: var(--secondary); font-size: 12px; margin-top: 5px;">Arquivo atual: <?= basename($row['url']) ?></p>
                <?php endif; ?>
            </div>

            <div id="section-url" class="form-group" style="display: <?= !$is_local_file ? 'block' : 'none' ?>;">
                <label for="url">URL da Mídia</label>
                <input type="text" name="url" id="url" class="neon-input" value="<?= !$is_local_file ? htmlspecialchars($row['url']) : '' ?>" oninput="previewUrl(this.value)">
            </div>

            <div class="form-group">
                <label>Pré-visualização Atual</label>
                <div class="preview-box" id="preview-container">
                    <?php 
                    $url = $row['url'];
                    $isVideo = preg_match(/\.(mp4|webm|ogg)/i, $url);
                    if ($isVideo): ?>
                        <video src="<?= $url ?>" class="preview-media" controls autoplay muted loop></video>
                    <?php else: ?>
                        <img src="<?= $url ?>" class="preview-media">
                    <?php endif; ?>
                </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 Alterações
                </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';
}

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 = (e) => {
            if (file.type.startsWith('image/')) container.innerHTML = `<img src="${e.target.result}" class="preview-media">`;
            else if (file.type.startsWith('video/')) container.innerHTML = `<video src="${e.target.result}" class="preview-media" controls autoplay muted loop></video>`;
        }
        reader.readAsDataURL(file);
    }
}

function previewUrl(url) {
    const container = document.getElementById('preview-container');
    if (!url) return;
    const isVideo = url.match(/\.(mp4|webm|ogg)/i);
    if (isVideo) container.innerHTML = `<video src="${url}" class="preview-media" controls autoplay muted loop></video>`;
    else container.innerHTML = `<img src="${url}" class="preview-media">`;
}
</script>

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