<?php


//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->


include ('includes/header.php');

//table name
$table_name = "ads";

//current file var
$base_file = basename($_SERVER["SCRIPT_NAME"]);

//create if not
$adb->exec("CREATE TABLE IF NOT EXISTS {$table_name}(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title VARCHAR(100), url TEXT)");

//table call
$res = $adb->query("SELECT * FROM {$table_name}");

//update call
@$resU = $adb->query("SELECT * FROM {$table_name} WHERE id='{$_GET['update']}'");
@$rowU=$resU->fetchArray();

// Função para validar se a URL é uma imagem
function isImageUrl($url) {
    $image_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $path_info = pathinfo(parse_url($url, PHP_URL_PATH));

    return isset($path_info['extension']) && in_array(strtolower($path_info['extension']), $image_extensions);
}

// Atualizar registro
if (isset($_POST['submitU'])) {
    if (isImageUrl($_POST['url'])) {
        $adb->exec("UPDATE {$table_name} SET title='{$_POST['title']}', url='{$_POST['url']}' WHERE id='{$_POST['id']}'");
        $adb->close();
        echo "<script>window.location.href='mRTXBGads.php';</script>";
        exit;
    } else {
        echo "<script>alert('Por favor, insira um link válido de imagem!');</script>";
    }
}

// Inserir novo registro
if (isset($_POST['submit'])) {
    if (isImageUrl($_POST['url'])) {
        $adb->exec("INSERT INTO {$table_name}(title, url, owner) VALUES('{$_POST['title']}', '{$_POST['url']}', '$admin_name')");
        echo "<script>window.location.href='mRTXBGads.php';</script>";
        exit;
    } else {
        echo "<script>alert('Por favor, insira um link válido de imagem!');</script>";
    }
}

// Deletar registro
if (isset($_GET['delete'])) {
    $adb->exec("DELETE FROM {$table_name} WHERE id={$_GET['delete']}");
    echo "<script>window.location.href='mRTXBGads.php';</script>";
    exit;
}

?>

<style>
/* === ESTILOS ESPECÍFICOS PARA ANÚNCIOS FUTURISTA === */
.main-content {
    background: transparent !important;
    padding: 20px;
}

.card {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 20px !important;
    box-shadow: 0 8px 40px rgba(0,0,0,0.4) !important;
    color: var(--text-primary) !important;
    overflow: hidden;
    position: relative;
}

.card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--primary), var(--accent), var(--secondary));
    animation: borderGlow 3s ease-in-out infinite;
}

@keyframes borderGlow {
    0%, 100% { opacity: 0.7; }
    50% { opacity: 1; }
}

.card-header {
    background: linear-gradient(135deg, var(--surface-light), var(--surface-lighter)) !important;
    border-bottom: 1px solid var(--border) !important;
    color: var(--text-primary) !important;
    font-weight: 700 !important;
    padding: 20px !important;
}

.card-body {
    background: transparent !important;
    color: var(--text-primary) !important;
    padding: 30px !important;
}

/* Formulários futuristas */
.form-control {
    background: var(--surface-lighter) !important;
    border: 1px solid var(--border) !important;
    color: var(--text-primary) !important;
    border-radius: 12px !important;
    padding: 14px 18px !important;
    font-size: 1rem;
    transition: all 0.3s ease;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.form-control:focus {
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 0.3rem rgba(0, 212, 255, 0.25) !important;
    background: var(--surface-lighter) !important;
    color: var(--text-primary) !important;
    transform: translateY(-2px);
}

.form-control::placeholder {
    color: var(--text-muted) !important;
}

/* Botões futuristas */
.btn-primary {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important;
    border: none !important;
    border-radius: 12px !important;
    box-shadow: var(--glow) !important;
    padding: 12px 24px !important;
    font-weight: 600 !important;
    transition: all 0.3s ease !important;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.btn-primary:hover {
    transform: translateY(-3px) !important;
    box-shadow: 0 8px 25px rgba(0, 212, 255, 0.5) !important;
}

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

.btn-info:hover {
    transform: translateY(-3px) !important;
    box-shadow: 0 8px 25px rgba(0, 255, 136, 0.5) !important;
}

/* Botão deletar específico */
.delete-btn {
    background: linear-gradient(135deg, var(--secondary), #FF416C) !important;
    border: none !important;
    border-radius: 10px !important;
    padding: 10px 14px !important;
    color: white !important;
    transition: all 0.3s ease !important;
    box-shadow: 0 4px 12px rgba(255, 107, 157, 0.3) !important;
}

.delete-btn:hover {
    background: linear-gradient(135deg, #ff5470, #ff3860) !important;
    transform: translateY(-2px) scale(1.05) !important;
    box-shadow: 0 6px 20px rgba(255, 107, 157, 0.5) !important;
}

/* Tabela futurista */
.table {
    background: var(--surface-light) !important;
    color: var(--text-primary) !important;
    border: 1px solid var(--border) !important;
    border-radius: 16px !important;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}

.table thead {
    background: linear-gradient(135deg, var(--surface-lighter), var(--surface-light)) !important;
}

.table th {
    border-bottom: 2px solid var(--primary) !important;
    color: var(--text-primary) !important;
    font-weight: 700 !important;
    padding: 18px 12px !important;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-size: 0.85rem;
}

.table td {
    border-bottom: 1px solid var(--border) !important;
    color: var(--text-secondary) !important;
    padding: 16px 12px !important;
    vertical-align: middle !important;
    transition: all 0.3s ease;
}

.table tbody tr:hover {
    background: rgba(0, 212, 255, 0.15) !important;
    transform: translateX(8px);
}

.table tbody tr:hover td {
    color: var(--text-primary) !important;
}

/* Modal futurista */
.modal-content {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 20px !important;
    box-shadow: 0 20px 60px rgba(0,0,0,0.5) !important;
    color: var(--text-primary) !important;
}

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

.modal-body {
    background: transparent !important;
    color: var(--text-primary) !important;
    padding: 25px !important;
}

.modal-footer {
    background: transparent !important;
    border-top: 1px solid var(--border) !important;
    border-radius: 0 0 20px 20px !important;
}

/* Preview de mídia */
.preview-media {
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.3);
    transition: all 0.3s ease;
    max-width: 120px;
    max-height: 80px;
    object-fit: cover;
}

.preview-media:hover {
    transform: scale(1.1);
}

/* Títulos */
.h1, .h2 {
    color: var(--text-primary) !important;
    font-weight: 700;
}

.text-primary2 {
    color: var(--primary) !important;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-size: 1.3rem !important;
}

/* Efeito de partículas */
@keyframes moveParticles {
    from { transform: translateY(0); opacity: 0.7; }
    to { transform: translateY(-1000px); opacity: 0; }
}

.particle {
    position: fixed;
    bottom: 0;
    width: 2px;
    height: 2px;
    background: var(--primary);
    opacity: 0.5;
    animation: moveParticles linear infinite;
    z-index: -1;
}

.particle:nth-child(odd) { background: var(--accent); }

/* Responsividade */
@media (max-width: 768px) {
    .main-content {
        padding: 10px !important;
    }
    
    .table-responsive {
        border: 1px solid var(--border) !important;
        border-radius: 12px !important;
    }
    
    .table th, .table td {
        padding: 12px 8px !important;
        font-size: 0.8rem !important;
    }
    
    .btn {
        padding: 10px 15px !important;
        font-size: 0.85rem !important;
    }
    
    .card-body {
        padding: 20px !important;
    }
    
    .preview-media {
        max-width: 80px;
        max-height: 60px;
    }
}
</style>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Partículas animadas
        const numParticles = 25;
        const particlesContainer = document.createElement('div');
        particlesContainer.style.position = 'fixed';
        particlesContainer.style.top = '0';
        particlesContainer.style.left = '0';
        particlesContainer.style.width = '100%';
        particlesContainer.style.height = '100%';
        particlesContainer.style.pointerEvents = 'none';
        particlesContainer.style.zIndex = '-1';
        
        for (let i = 0; i < numParticles; i++) {
            const particle = document.createElement('div');
            particle.classList.add('particle');
            particle.style.left = Math.random() * 100 + 'vw';
            particle.style.animationDuration = (2 + Math.random() * 8) + 's';
            particle.style.animationDelay = Math.random() * 10 + 's';
            particle.style.width = particle.style.height = (1 + Math.random() * 3) + 'px';
            particlesContainer.appendChild(particle);
        }
        
        document.body.appendChild(particlesContainer);

        // Configuração do modal de confirmação
        $('#confirm-delete').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
        });

        // Efeitos nas linhas da tabela
        const tableRows = document.querySelectorAll('.table tbody tr');
        tableRows.forEach(row => {
            row.style.transition = 'all 0.3s ease';
        });

        // Auto-hide alert
        const successAlert = document.getElementById('success-alert');
        if (successAlert) {
            setTimeout(() => {
                successAlert.style.opacity = '0';
                successAlert.style.transition = 'opacity 0.5s ease';
                setTimeout(() => successAlert.remove(), 500);
            }, 2000);
        }
    });
</script>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h2 class="m-0 font-weight-bold text-primary2">Confirmar Exclusão</h2>
			</div>
			<div class="modal-body">
				<p>Você realmente deseja excluir este anúncio?</p>
				<p class="text-muted">Esta ação não pode ser desfeita.</p>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
				<a class="btn btn-danger btn-ok">Deletar</a>
			</div>
		</div>
	</div>
</div>

<main role="main" class="col-12 pt-4 px-4 main-content">
    <div class="container-fluid">
        <?php
        if (isset($_GET['create'])){

        //create form
        ?>
        <div class="row">
            <div class="col-lg-8 mx-auto">
                <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-plus-circle me-2"></i>Novo Anúncio
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info" style="background: rgba(0, 212, 255, 0.1); border-color: var(--primary);">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>Dimensões Recomendadas:</strong> 3295x2337 pixels
                        </div>
        				<form method="post">
                            <div class="form-group">
                                <label class="control-label"><i class="fas fa-heading me-2"></i><strong>Título do Anúncio</strong></label>
                                <input class="form-control" type="text" name="title" placeholder="Digite o título do anúncio" required>
                            </div>
                            <div class="form-group">
                                <label class="control-label"><i class="fas fa-link me-2"></i><strong>URL da Imagem</strong></label>
                                <input class="form-control" type="text" name="url" placeholder="Cole a URL da imagem (GIF, PNG, JPG, WEBP)" required>
                                <small class="text-muted">Formatos suportados: GIF, PNG, JPG, WEBP</small>
                            </div>  
                            <div class="form-group mt-4">
                                <button type="submit" name="submit" class="btn btn-info btn-lg">
                                    <i class="fas fa-save me-2"></i>Criar Anúncio
                                </button>
                                <a href="./<?php echo $base_file ?>" class="btn btn-secondary btn-lg ml-2">
                                    <i class="fas fa-arrow-left me-2"></i>Voltar
                                </a>
                            </div>
                        </form>
					</div>
				</div>
			</div>
        </div>

        <?php 
        }else if (isset($_GET['update'])){ 

        //update form
        ?>
        <div class="row">
            <div class="col-lg-8 mx-auto">
                <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-edit me-2"></i>Editar Anúncio
                        </h6>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <input type="hidden" class="form-control" name="id" value="<?=$_GET['update'] ?>">
                            <div class="form-group">
                                <label class="control-label"><i class="fas fa-heading me-2"></i><strong>Título do Anúncio</strong></label>
                                <input type="text" name="title" class="form-control" value="<?=$rowU['title'] ?>" placeholder="Digite o título do anúncio" required>
                            </div>
                            <div class="form-group">
                                <label class="control-label"><i class="fas fa-link me-2"></i><strong>URL da Imagem</strong></label>
                                <input type="text" class="form-control" name="url" value="<?=$rowU['url'] ?>" placeholder="Cole a URL da imagem" required>
                                <small class="text-muted">Formatos suportados: GIF, PNG, JPG, WEBP</small>
                            </div>  
                            <div class="form-group mt-4">
                                <button type="submit" name="submitU" class="btn btn-info btn-lg">
                                    <i class="fas fa-sync-alt me-2"></i>Atualizar Anúncio
                                </button>
                                <a href="./<?php echo $base_file ?>" class="btn btn-secondary btn-lg ml-2">
                                    <i class="fas fa-arrow-left me-2"></i>Voltar
                                </a>
                            </div>
                        </form>
					</div>
				</div>
			</div>
        </div>
        <?php
         }else{
        //main table/form
        ?>
        <div class="row">
            <div class="col-lg-12">
                <div class="card border-left-primary shadow h-100 card shadow mb-4">
                    <div class="card-header py-3 d-flex justify-content-between align-items-center">
                        <h6 class="m-0 font-weight-bold text-primary2">
                            <i class="fas fa-ad me-2"></i>Gerenciar Anúncios
                        </h6>
                        <a href="./<?php echo $base_file ?>?create" class="btn btn-primary btn-icon-split">
                            <span class="icon text-white-50">
                                <i class="fas fa-plus"></i>
                            </span>
                            <span class="text">Novo Anúncio</span>
                        </a>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-sm">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Título</th>
                                        <th>URL</th>
                                        <th>Registrado Por</th>
                                        <th>Pré-visualização</th>
                                        <th>Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($row = $res->fetchArray()) {?>
                                    <tr>
                                        <td><span class="code-text"><?=$row['id'] ?></span></td>
                                        <td>
                                            <strong><?=$row['title'] ?></strong>
                                            <?php if (strpos($row['url'], '.mp4') !== false || strpos($row['url'], '.webm') !== false || strpos($row['url'], '.gif') !== false || strpos($row['url'], '.ogg') !== false): ?>
                                                <span class="badge badge-warning ml-2">Mídia</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><span class="code-text" style="max-width: 200px; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"><?=$row['url'] ?></span></td>
                                        <td><?=$row['owner'] ?></td>
                                        <td>
                                            <?php if (strpos($row['url'], '.mp4') !== false || strpos($row['url'], '.webm') !== false || strpos($row['url'], '.ogg') !== false) {?>
                                                <video src="<?=$row['url']?>" controls width="100" class="preview-media" muted loop></video>
                                            <?php } else if (strpos($row['url'], '.jpg') !== false || strpos($row['url'], '.jpeg') !== false || strpos($row['url'], '.png') !== false|| strpos($row['url'], '.gif') !== false) {?>
                                                <img src="<?=$row['url']?>" class="preview-media" alt="Preview"/>
                                            <?php }?>
                                        </td>
                                        <td>
                                            <div class="btn-group" role="group">
                                                <a class="btn btn-info btn-sm" href="<?php echo $base_file ?>?update=<?=$row['id'] ?>">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a class="btn delete-btn btn-sm ml-2" href="#" data-href="<?php echo $base_file ?>?delete=<?=$row['id'] ?>" data-toggle="modal" data-target="#confirm-delete">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php }?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php }?>
    </div>
</main>

<?php include ('includes/footer.php');?>
<script type="text/javascript">
//update alert
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
    $("#success-alert").alert('close');
});

//delete modal
$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>
</body>
</html>