<?php 
include ('../includes/header3.php');

//table name
$table_name = "ads";

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

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

// blindagem: se a tabela foi criada antiga sem owner, adiciona a coluna
@$adb->exec("ALTER TABLE {$table_name} ADD COLUMN 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']}' AND owner = '$seller_name'");
@$rowU = $resU->fetchArray();

// Função para validar se a URL é uma imagem ou vídeo (igual ao header2 do print)
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-cyan: #00f2ff;
        --neon-purple: #bc13fe;
        --neon-pink: #ff2bd6;
        --danger: #ff4b2b;
        --dark-bg: #050a0e;
        --glass-bg: rgba(255, 255, 255, 0.02);
        --glass-border: rgba(0, 242, 255, 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: linear-gradient(90deg, rgba(0,242,255,.10), rgba(188,19,254,.08), rgba(255,43,214,.06)) !important;
        border-bottom: 1px solid var(--glass-border) !important;
        padding: 1.25rem !important;
    }

    .card-header-futuristic h2, .card-header-futuristic h6 {
        font-family: 'Orbitron', sans-serif;
        color: var(--neon-cyan) !important;
        text-shadow: 0 0 10px rgba(0,242,255,.35);
        text-transform: uppercase;
        margin: 0;
        letter-spacing: .08em;
    }

    /* 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-cyan); text-transform: uppercase; font-size: 0.75rem; letter-spacing: 1px; font-family:'Orbitron',sans-serif; }
    .table-modern tbody tr { background: rgba(255, 255, 255, 0.02); transition: 0.3s; }
    .table-modern tbody tr:hover { background: rgba(0, 242, 255, 0.06); }
    .table-modern td { border: none !important; padding: 15px !important; vertical-align: middle !important; }

    /* Links Clicáveis (FUNÇÃO PEDIDA) */
    .url-link {
        color: rgba(255,255,255,.65);
        text-decoration: none;
        transition: 0.3s;
        font-size: 0.82rem;
        max-width: 360px;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        cursor: pointer;
    }
    .url-link:hover {
        color: var(--neon-cyan);
        text-shadow: 0 0 8px rgba(0,242,255,.25);
        text-decoration: underline;
    }

    /* Preview maior (FUNÇÃO PEDIDA) */
    .media-preview {
        border-radius: 10px;
        border: 1px solid rgba(0,242,255,.22);
        box-shadow: 0 0 18px rgba(0,242,255, 0.10);
        object-fit: cover;
        width: 180px;
        transition: transform 0.35s ease, border-color 0.35s ease;
        background: rgba(0,0,0,.25);
    }
    .media-preview:hover {
        transform: scale(1.08);
        border-color: var(--neon-cyan);
        z-index: 10;
        position: relative;
    }

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

    .btn-neon {
        background: transparent !important;
        border: 1px solid rgba(0,242,255,.55) !important;
        color: rgba(0,242,255,.95) !important;
        font-family: 'Orbitron', sans-serif;
        padding: 10px 18px;
        border-radius: 12px;
        transition: 0.25s;
        text-transform: uppercase;
        letter-spacing: .06em;
    }
    .btn-neon:hover {
        background: rgba(0,242,255,.10) !important;
        box-shadow: 0 0 18px rgba(0,242,255,.15);
        transform: translateY(-1px);
    }
</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-cyan); font-family:'Orbitron'; letter-spacing:.08em; text-transform:uppercase;">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-cyan); font-family:'Orbitron';">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-cyan); font-family:'Orbitron';">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-neon 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-cyan); font-family:'Orbitron';">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-cyan); font-family:'Orbitron';">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-neon 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-neon 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-cyan); font-family:'Orbitron';"><?=$row['id'] ?></td>
                                <td class="font-weight-bold"><?=$row['title'] ?></td>

                                <!-- LINK CLICÁVEL + ABRE EM NOVA ABA + HOVER COM A FRASE EXATA -->
                                <td>
                                    <a href="<?=$row['url']?>"
                                       target="_blank"
                                       rel="noopener noreferrer"
                                       class="url-link"
                                       title="Clique no link para abrir em uma nova aba">
                                        <i class="fas fa-external-link-alt mr-2" style="font-size: 0.75rem; color: var(--neon-purple);"></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 playsinline 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-cyan); 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: var(--danger); font-size: 1.1rem;"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

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

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