<?php 
include ('../includes/header2.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, owner VARCHAR(100))");

//table call
$res = $adb->query("SELECT * FROM {$table_name} WHERE owner = '$seller_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 ou vídeo
function isImageUrl($url) {
    $image_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'webm', 'ogg'];
    $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']}' AND owner = '$seller_name'");
        echo "<script>window.location.href='$base_file';</script>";
        exit;
    } else {
        echo "<script>alert('Por favor, insira um link válido!');</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']}', '$seller_name')");
        echo "<script>window.location.href='$base_file';</script>";
        exit;
    } else {
        echo "<script>alert('Por favor, insira um link válido!');</script>";
    }
}

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

<style>
    :root {
        --neon-emerald: #00ff88;
        --dark-bg: #050a0e;
        --glass-bg: rgba(255, 255, 255, 0.02);
        --glass-border: rgba(0, 255, 136, 0.15);
    }

    /* Blindagem contra fundo branco */
    html, body, #wrapper, #content-wrapper, #content, .bg-white, .container-fluid {
        background-color: var(--dark-bg) !important;
        color: #e0e0e0 !important;
        font-family: 'Poppins', sans-serif;
    }

    .card-futuristic {
        background: var(--glass-bg) !important;
        backdrop-filter: blur(15px);
        border: 1px solid var(--glass-border) !important;
        border-radius: 15px !important;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
    }

    .card-header-futuristic {
        background: rgba(0, 255, 136, 0.03) !important;
        border-bottom: 1px solid var(--glass-border) !important;
        padding: 1.5rem !important;
    }

    .card-header-futuristic h2, .card-header-futuristic h6 {
        font-family: 'Orbitron', sans-serif;
        color: var(--neon-emerald) !important;
        text-shadow: 0 0 10px var(--neon-emerald);
        text-transform: uppercase;
        margin: 0;
    }

    /* Tabela */
    .table-modern { color: #e0e0e0 !important; border-collapse: separate; border-spacing: 0 10px; width: 100%; }
    .table-modern thead th { border: none !important; color: var(--neon-emerald); text-transform: uppercase; font-size: 0.75rem; letter-spacing: 1px; }
    .table-modern tbody tr { background: rgba(255, 255, 255, 0.02); transition: 0.3s; }
    .table-modern tbody tr:hover { background: rgba(0, 255, 136, 0.05); }
    .table-modern td { border: none !important; padding: 15px !important; vertical-align: middle !important; }

    /* Links Clicáveis */
    .url-link {
        color: #888;
        text-decoration: none;
        transition: 0.3s;
        font-size: 0.8rem;
        max-width: 200px;
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        cursor: pointer;
    }
    .url-link:hover { color: var(--neon-emerald); text-shadow: 0 0 5px var(--neon-emerald); }

    /* Estilo da Mídia Ampliada */
    .media-preview {
        border-radius: 8px;
        border: 2px solid var(--glass-border);
        box-shadow: 0 0 15px rgba(0, 255, 136, 0.1);
        object-fit: cover;
        width: 150px; /* Aumentado conforme solicitado */
        transition: transform 0.4s ease, border-color 0.4s ease;
    }
    .media-preview:hover {
        transform: scale(1.1);
        border-color: var(--neon-emerald);
        z-index: 10;
    }

    .form-control-futuristic {
        background: rgba(0, 0, 0, 0.5) !important;
        border: 1px solid var(--glass-border) !important;
        color: #fff !important;
        padding: 12px;
        border-radius: 8px;
    }

    .btn-emerald {
        background: transparent;
        border: 1px solid var(--neon-emerald);
        color: var(--neon-emerald) !important;
        font-family: 'Orbitron', sans-serif;
        padding: 10px 20px;
        border-radius: 8px;
        transition: 0.4s;
        text-transform: uppercase;
    }
    .btn-emerald:hover { background: var(--neon-emerald); color: #000 !important; box-shadow: 0 0 20px var(--neon-emerald); }
</style>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content card-futuristic">
            <div class="modal-header border-0"><h2 style="color:var(--neon-emerald); font-family: 'Orbitron';">Confirmar</h2></div>
            <div class="modal-body">Você realmente deseja excluir este anúncio?</div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-sm btn-ok">Deletar</a>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid pt-4 px-5">
    <?php if (isset($_GET['create'])): ?>
        <div class="col-md-8 mx-auto">
            <div class="card card-futuristic shadow">
                <div class="card-header-futuristic text-center">
                    <h2><i class="fa fa-plus-circle mr-2"></i>Novo Anúncio</h2>
                </div>
                <div class="card-body p-4">
                    <form method="post">
                        <div class="form-group mb-4">
                            <label class="small text-uppercase" style="color:var(--neon-emerald)">Título</label>
                            <input class="form-control form-control-futuristic" type="text" name="title" required>
                        </div>
                        <div class="form-group mb-4">
                            <label class="small text-uppercase" style="color:var(--neon-emerald)">URL da Mídia (Imagem ou Vídeo)</label>
                            <input class="form-control form-control-futuristic" type="text" name="url" required>
                        </div>
                        <button type="submit" name="submit" class="btn btn-emerald btn-block">CRIAR ANÚNCIO</button>
                        <a href="<?=$base_file?>" class="btn btn-link btn-block text-white-50 mt-2">Voltar</a>
                    </form>
                </div>
            </div>
        </div>

    <?php elseif (isset($_GET['update'])): ?>
        <div class="col-md-8 mx-auto">
            <div class="card card-futuristic shadow">
                <div class="card-header-futuristic text-center">
                    <h2><i class="fa fa-edit mr-2"></i>Editar Anúncio</h2>
                </div>
                <div class="card-body p-4">
                    <form method="post">
                        <input type="hidden" name="id" value="<?=$_GET['update'] ?>">
                        <div class="form-group mb-4">
                            <label class="small text-uppercase" style="color:var(--neon-emerald)">Título</label>
                            <input type="text" name="title" class="form-control form-control-futuristic" value="<?=$rowU['title'] ?>" required>
                        </div>
                        <div class="form-group mb-4">
                            <label class="small text-uppercase" style="color:var(--neon-emerald)">URL da Mídia</label>
                            <input type="text" class="form-control form-control-futuristic" name="url" value="<?=$rowU['url'] ?>" required>
                        </div>
                        <button type="submit" name="submitU" class="btn btn-emerald btn-block">SALVAR ALTERAÇÕES</button>
                        <a href="<?=$base_file?>" class="btn btn-link btn-block text-white-50 mt-2">Cancelar</a>
                    </form>
                </div>
            </div>
        </div>

    <?php else: ?>
        <div class="card card-futuristic shadow mb-4">
            <div class="card-header-futuristic d-flex justify-content-between align-items-center">
                <h6><i class="fas fa-broadcast-tower mr-2"></i> Central de Anúncios</h6>
                <a href="?create" class="btn btn-emerald btn-sm"><i class="fa fa-plus mr-1"></i> NOVO ANÚNCIO</a>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-modern">
                        <thead>
                            <tr>
                                <th>Id</th>
                                <th>Titulo</th>
                                <th>URL / Link</th>
                                <th>Preview</th>
                                <th class="text-center">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = $res->fetchArray()): ?>
                            <tr>
                                <td style="color: var(--neon-emerald)"><?=$row['id'] ?></td>
                                <td class="font-weight-bold"><?=$row['title'] ?></td>
                                <td>
                                    <a href="<?=$row['url'] ?>" target="_blank" class="url-link" title="Clique para abrir este link em uma nova janela">
                                        <i class="fas fa-external-link-alt mr-2" style="font-size: 0.7rem;"></i><?=$row['url'] ?>
                                    </a>
                                </td>
                                <td>
                                    <?php if (strpos($row['url'], '.mp4') !== false || strpos($row['url'], '.webm') !== false || strpos($row['url'], '.ogg') !== false): ?>
                                        <video src="<?=$row['url']?>" class="media-preview" muted loop onmouseover="this.play()" onmouseout="this.pause()"></video>
                                    <?php else: ?>
                                        <img src="<?=$row['url']?>" class="media-preview" onerror="this.src='../img/logo.png'"/>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <a href="<?=$base_file?>?update=<?=$row['id'] ?>" class="btn btn-sm" title="Editar"><i class="fas fa-edit" style="color: var(--neon-emerald); font-size: 1.1rem;"></i></a>
                                    <a href="#" data-href="<?=$base_file?>?delete=<?=$row['id'] ?>" data-toggle="modal" data-target="#confirm-delete" class="btn btn-sm" title="Deletar"><i class="fas fa-trash-alt" style="color: #ff4b2b; font-size: 1.1rem;"></i></a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

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

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