<?php
// OneLauncher - propaganda.php
require_once 'includes/auth.php';
require_once 'db.php';

global $active_theme_id;

// Manipulação AJAX para troca de ordem
if (isset($_POST['action']) && $_POST['action'] === 'reorder') {
    ob_start();
    $id = (int) $_POST['id'];
    $direction = $_POST['direction'];

    // Obter o atual
    $stmt = $conn->prepare("SELECT item_order FROM propaganda WHERE id = ? AND theme_id = ?");
    $stmt->bind_param("ii", $id, $active_theme_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $current = $res->fetch_assoc();

    if ($current) {
        $current_order = (int) $current['item_order'];

        if ($direction === 'up') {
            $stmt = $conn->prepare("SELECT id, item_order FROM propaganda WHERE theme_id = ? AND item_order < ? ORDER BY item_order DESC LIMIT 1");
        } else {
            $stmt = $conn->prepare("SELECT id, item_order FROM propaganda WHERE theme_id = ? AND item_order > ? ORDER BY item_order ASC LIMIT 1");
        }
        $stmt->bind_param("ii", $active_theme_id, $current_order);
        $stmt->execute();
        $res = $stmt->get_result();
        $swap = $res->fetch_assoc();

        if ($swap) {
            $swap_id = (int) $swap['id'];
            $swap_order = (int) $swap['item_order'];

            $conn->query("UPDATE propaganda SET item_order = $swap_order WHERE id = $id");
            $conn->query("UPDATE propaganda SET item_order = $current_order WHERE id = $swap_id");

            ob_end_clean();
            header('Content-Type: application/json');
            echo json_encode(['success' => true]);
            exit;
        }
    }
    ob_end_clean();
    header('Content-Type: application/json');
    echo json_encode(['success' => false]);
    exit;
}

// AJAX: Bulk Delete Propaganda
if (isset($_POST['bulk_delete']) && !empty($_POST['selected_banners'])) {
    $ids = array_map('intval', $_POST['selected_banners']);
    $ids_string = implode(',', $ids);
    if (!empty($ids_string)) {
        $conn->query("DELETE FROM propaganda WHERE id IN ($ids_string) AND theme_id = $active_theme_id");
        header('Content-Type: application/json');
        echo json_encode(['success' => true]);
        exit;
    }
}

$pageTitle = 'Propagandas';
$nav = 'propaganda';
$msg = '';

// Adicionar Propaganda
if (isset($_POST['add_propaganda']) || isset($_POST['save_propaganda_hidden'])) {
    $image_url = $_POST['image_url'];
    $errors = [];

    if (isset($_FILES['prop_file']) && $_FILES['prop_file']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = __DIR__ . '/uploads';
        if (!file_exists($upload_dir))
            mkdir($upload_dir, 0777, true);

        $ext = strtolower(pathinfo($_FILES['prop_file']['name'], PATHINFO_EXTENSION));
        $allowed_exts = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        if (in_array($ext, $allowed_exts)) {
            $new_name = "prop_" . time() . "_" . bin2hex(random_bytes(4)) . "." . $ext;
            if (move_uploaded_file($_FILES['prop_file']['tmp_name'], "$upload_dir/$new_name")) {
                $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://";
                $image_url = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/uploads/$new_name";
            }
        } else {
            $errors[] = "A extensão do arquivo não é permitida. Use JPG, PNG ou WEBP.";
        }
    }

    if (empty($errors) && !empty($image_url)) {
        $res_order = $conn->query("SELECT MAX(item_order) as max_order FROM propaganda WHERE theme_id = $active_theme_id");
        $row_order = $res_order->fetch_assoc();
        $order = ($row_order && $row_order['max_order'] !== null) ? (int) $row_order['max_order'] + 1 : 1;

        $stmt = $conn->prepare("INSERT INTO propaganda (theme_id, image_url, item_order) VALUES (?, ?, ?)");
        $stmt->bind_param("isi", $active_theme_id, $image_url, $order);
        $stmt->execute();
        $msg = 'Propaganda adicionada com sucesso!';
    } elseif (!empty($errors)) {
        $msg_error = implode('<br>', array_map('htmlspecialchars', $errors));
    }
}

// Remover Propaganda
if (isset($_GET['delete'])) {
    $id = (int) $_GET['delete'];
    $conn->query("DELETE FROM propaganda WHERE id = $id AND theme_id = $active_theme_id");
    header("Location: propaganda.php?msg=deleted");
    exit;
}
if (isset($_GET['msg']) && $_GET['msg'] === 'deleted') {
    $msg = 'Propaganda removida com sucesso!';
}

$res = $conn->query("SELECT * FROM propaganda WHERE theme_id = $active_theme_id ORDER BY item_order ASC");
$banners = [];
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $banners[] = $row;
    }
}

include 'includes/head.php';
include 'includes/sidebar.php';
include 'includes/topbar.php';
include 'includes/layout-open.php';
?>

<style>
    /* ========== DESIGN SYSTEM ========== */
    :root {
        --bg-primary: #0a0e17;
        --bg-secondary: #111827;
        --bg-tertiary: #1a2235;
        --accent: #3b82f6;
        --accent-hover: #2563eb;
        --accent-glow: rgba(59, 130, 246, 0.15);
        --danger: #ef4444;
        --danger-hover: #dc2626;
        --success: #10b981;
        --text-primary: #f1f5f9;
        --text-secondary: #94a3b8;
        --text-muted: #64748b;
        --border: rgba(255, 255, 255, 0.08);
        --border-light: rgba(255, 255, 255, 0.05);
        --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.3);
        --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.4);
        --shadow-lg: 0 10px 40px rgba(0, 0, 0, 0.5);
        --radius-sm: 10px;
        --radius-md: 14px;
        --radius-lg: 18px;
        --transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    }

    /* ========== PAGE HEADER ========== */
    .page-header {
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(139, 92, 246, 0.05) 100%);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        padding: 1.75rem 2rem;
        margin-bottom: 2rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
        flex-wrap: wrap;
        box-shadow: var(--shadow-md);
    }

    .page-header-content h2 {
        font-size: 1.5rem;
        font-weight: 700;
        color: var(--text-primary);
        margin-bottom: 0.25rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .page-header-content h2 i {
        font-size: 1.35rem;
        background: linear-gradient(135deg, var(--accent), #8b5cf6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .page-header-content p {
        color: var(--text-muted);
        font-size: 0.875rem;
        margin: 0;
    }

    .btn-primary-custom {
        background: linear-gradient(135deg, var(--accent), #4f46e5);
        border: none;
        color: white;
        padding: 0.75rem 1.5rem;
        border-radius: 50px;
        font-weight: 600;
        font-size: 0.9rem;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
        cursor: pointer;
        text-decoration: none;
    }

    .btn-primary-custom:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        color: white;
    }

    .btn-primary-custom:active {
        transform: translateY(0);
    }

    /* ========== ALERTS ========== */
    .alert-custom {
        border-radius: var(--radius-md);
        padding: 1rem 1.5rem;
        margin-bottom: 1.5rem;
        border: none;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        animation: slideDown 0.4s ease;
    }

    .alert-success-custom {
        background: rgba(16, 185, 129, 0.1);
        color: #34d399;
        border-left: 4px solid var(--success);
    }

    .alert-danger-custom {
        background: rgba(239, 68, 68, 0.1);
        color: #f87171;
        border-left: 4px solid var(--danger);
    }

    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateY(-15px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* ========== TABLE CONTAINER ========== */
    .table-container {
        background: var(--bg-secondary);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        overflow: hidden;
        box-shadow: var(--shadow-lg);
    }

    .table-header {
        background: var(--bg-tertiary);
        padding: 1rem 1.5rem;
        border-bottom: 1px solid var(--border);
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .table-header-title {
        color: var(--text-secondary);
        font-size: 0.8rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .table-custom {
        width: 100%;
        border-collapse: collapse;
    }

    .table-custom thead th {
        background: rgba(255, 255, 255, 0.02);
        color: var(--text-muted);
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        padding: 1rem 1.5rem;
        border-bottom: 2px solid var(--border-light);
        white-space: nowrap;
    }

    .table-custom tbody td {
        padding: 1rem 1.5rem;
        border-bottom: 1px solid var(--border-light);
        color: var(--text-secondary);
        vertical-align: middle;
        transition: var(--transition);
    }

    .table-custom tbody tr {
        transition: var(--transition);
    }

    .table-custom tbody tr:hover {
        background: rgba(59, 130, 246, 0.03);
    }

    .table-custom tbody tr:last-child td {
        border-bottom: none;
    }

    /* ========== BANNER PREVIEW ========== */
    .banner-preview-wrapper {
        display: flex;
        align-items: center;
        gap: 1rem;
    }

    .banner-thumbnail {
        width: 140px;
        height: 78px;
        border-radius: var(--radius-sm);
        overflow: hidden;
        position: relative;
        flex-shrink: 0;
        background: var(--bg-primary);
        border: 1px solid var(--border);
        box-shadow: var(--shadow-sm);
    }

    .banner-thumbnail img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
    }

    .banner-thumbnail:hover img {
        transform: scale(1.05);
    }

    .banner-thumbnail::after {
        content: '';
        position: absolute;
        inset: 0;
        border-radius: inherit;
        box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.05);
    }

    .banner-url-text {
        font-size: 0.8rem;
        color: var(--text-muted);
        max-width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .banner-url-text i {
        color: var(--accent);
        font-size: 0.75rem;
    }

    /* ========== ORDER CONTROLS ========== */
    .order-controls {
        display: inline-flex;
        align-items: center;
        background: var(--bg-primary);
        border: 1px solid var(--border);
        border-radius: 50px;
        padding: 0.25rem;
        gap: 0.25rem;
    }

    .btn-order {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        border: none;
        background: transparent;
        color: var(--text-muted);
        cursor: pointer;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 0.9rem;
    }

    .btn-order:hover:not(:disabled) {
        background: rgba(59, 130, 246, 0.15);
        color: var(--accent);
    }

    .btn-order:disabled {
        opacity: 0.3;
        cursor: not-allowed;
    }

    .order-number {
        min-width: 32px;
        text-align: center;
        font-weight: 700;
        color: var(--text-primary);
        font-size: 0.95rem;
    }

    /* ========== ACTION BUTTONS ========== */
    .btn-action-custom {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        border: 1px solid rgba(239, 68, 68, 0.3);
        background: transparent;
        color: var(--danger);
        cursor: pointer;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }

    .btn-action-custom:hover {
        background: rgba(239, 68, 68, 0.15);
        border-color: var(--danger);
        transform: scale(1.1);
    }

    /* ========== EMPTY STATE ========== */
    .empty-state {
        text-align: center;
        padding: 4rem 2rem;
    }

    .empty-state-icon {
        font-size: 4rem;
        background: linear-gradient(135deg, var(--accent), #8b5cf6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        opacity: 0.5;
        margin-bottom: 1rem;
    }

    .empty-state-text {
        color: var(--text-muted);
        font-size: 1rem;
        font-style: italic;
    }

    /* ========== MODAL ========== */
    .modal-content-custom {
        background: var(--bg-secondary);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-lg);
    }

    .modal-header-custom {
        padding: 1.5rem;
        border-bottom: 1px solid var(--border);
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .modal-title-custom {
        color: var(--text-primary);
        font-weight: 700;
        font-size: 1.15rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .modal-title-custom i {
        font-size: 1.1rem;
        background: linear-gradient(135deg, var(--accent), #8b5cf6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .modal-body-custom {
        padding: 1.5rem;
    }

    .modal-footer-custom {
        padding: 1rem 1.5rem 1.5rem;
        border-top: 1px solid var(--border);
        display: flex;
        gap: 0.75rem;
    }

    .btn-close-custom {
        background: none;
        border: none;
        color: var(--text-muted);
        font-size: 1.25rem;
        cursor: pointer;
        transition: var(--transition);
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .btn-close-custom:hover {
        background: rgba(255, 255, 255, 0.05);
        color: var(--text-primary);
    }

    /* ========== FORM ELEMENTS ========== */
    .form-label-custom {
        color: var(--text-muted);
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.5rem;
        display: block;
    }

    .form-control-custom {
        background: var(--bg-primary);
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        padding: 0.75rem 1rem;
        color: var(--text-primary);
        width: 100%;
        transition: var(--transition);
        font-size: 0.9rem;
    }

    .form-control-custom:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 4px var(--accent-glow);
        background: var(--bg-primary);
    }

    .form-control-custom::placeholder {
        color: var(--text-muted);
        opacity: 0.6;
    }

    /* ========== UPLOAD ZONE ========== */
    .upload-zone {
        background: var(--bg-primary);
        border: 2px dashed rgba(59, 130, 246, 0.3);
        border-radius: var(--radius-md);
        padding: 2rem;
        text-align: center;
        cursor: pointer;
        transition: var(--transition);
        position: relative;
        overflow: hidden;
    }

    .upload-zone:hover,
    .upload-zone.drag-over {
        border-color: var(--accent);
        background: rgba(59, 130, 246, 0.05);
    }

    .upload-zone-icon {
        font-size: 2.5rem;
        color: var(--accent);
        opacity: 0.7;
        margin-bottom: 0.5rem;
    }

    .upload-zone-text {
        color: var(--text-muted);
        font-size: 0.85rem;
    }

    .upload-zone-hint {
        color: var(--text-muted);
        font-size: 0.75rem;
        opacity: 0.7;
        margin-top: 0.5rem;
    }

    .preview-image {
        max-width: 100%;
        max-height: 160px;
        border-radius: var(--radius-sm);
        border: 1px solid var(--border);
        object-fit: contain;
    }

    .divider-text {
        display: flex;
        align-items: center;
        gap: 1rem;
        color: var(--text-muted);
        font-size: 0.8rem;
        font-weight: 600;
        text-transform: uppercase;
        margin: 1.5rem 0;
    }

    .divider-text::before,
    .divider-text::after {
        content: '';
        flex: 1;
        height: 1px;
        background: var(--border);
    }

    .btn-outline-custom {
        background: transparent;
        border: 1px solid var(--border);
        color: var(--text-secondary);
        padding: 0.75rem 1.5rem;
        border-radius: 50px;
        font-weight: 600;
        font-size: 0.85rem;
        cursor: pointer;
        transition: var(--transition);
        flex: 1;
    }

    .btn-outline-custom:hover {
        background: rgba(255, 255, 255, 0.03);
        border-color: rgba(255, 255, 255, 0.15);
        color: var(--text-primary);
    }

    .btn-submit-custom {
        background: linear-gradient(135deg, var(--accent), #4f46e5);
        border: none;
        color: white;
        padding: 0.75rem 1.5rem;
        border-radius: 50px;
        font-weight: 600;
        font-size: 0.85rem;
        cursor: pointer;
        transition: var(--transition);
        flex: 1;
        box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
    }

    .btn-submit-custom:hover {
        box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        transform: translateY(-1px);
    }

    .btn-remove-image {
        background: none;
        border: none;
        color: var(--danger);
        font-size: 0.8rem;
        cursor: pointer;
        margin-top: 0.5rem;
        text-decoration: underline;
    }

    .error-message {
        color: var(--danger);
        font-size: 0.8rem;
        margin-top: 0.5rem;
        display: none;
    }

    /* ========== RESPONSIVIDADE E AJUSTES PARA MOBILE ========== */
    @media (max-width: 768px) {
        .page-header {
            flex-direction: column;
            align-items: stretch;
            padding: 1.25rem;
            gap: 1rem;
        }

        .btn-primary-custom {
            width: 100%;
            justify-content: center;
        }

        .banner-preview-wrapper {
            flex-direction: column;
            align-items: center;
            width: 100%;
            gap: 0.5rem;
        }

        .banner-thumbnail {
            width: 100% !important;
            max-width: 280px;
            height: 157px;
        }

        .banner-url-text {
            width: 100%;
            max-width: 100%;
            justify-content: center;
            word-break: break-all;
            white-space: normal;
            text-align: center;
        }

        /* Ajuste do wrapper responsivo da tabela */
        .table-responsive {
            overflow-x: visible !important;
            padding: 0 !important;
            margin: 0 !important;
            border: none !important;
            width: 100% !important;
        }

        /* Configurar tabela para se comportar como blocos */
        #propagandaTable,
        #propagandaTable tbody {
            display: block;
            width: 100% !important;
        }

        /* Esconder cabeçalho da tabela no mobile */
        #propagandaTable thead {
            display: none;
        }

        /* Cada linha vira um card */
        #propagandaTable tbody tr {
            display: block;
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: var(--radius-md);
            margin-bottom: 0.75rem;
            padding: 0.85rem 1rem;
            width: 100% !important;
            box-sizing: border-box;
        }

        #propagandaTable tbody tr:hover {
            background: rgba(59, 130, 246, 0.05);
        }

        /* Cada célula vira uma linha com label */
        #propagandaTable tbody td {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid var(--border-light);
            font-size: 0.82rem;
            width: 100% !important;
            box-sizing: border-box;
        }

        #propagandaTable tbody td:last-child {
            border-bottom: none;
            padding-top: 0.6rem;
            justify-content: flex-end;
            gap: 0.4rem;
        }

        /* Label gerado pelo data-label */
        #propagandaTable tbody td::before {
            content: attr(data-label);
            font-size: 0.7rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: var(--text-muted);
            flex-shrink: 0;
            margin-right: 0.75rem;
        }

        /* Célula de checkbox no mobile: sem label, centralizada */
        #propagandaTable tbody td.checkbox-cell {
            justify-content: flex-start;
            gap: 0.5rem;
        }

        #propagandaTable tbody td.checkbox-cell::before {
            content: 'Selecionar';
        }

        #bulkActions {
            flex-direction: column;
            align-items: stretch;
            gap: 0.75rem;
            padding: 1rem;
        }

        #bulkActions button {
            width: 100%;
            justify-content: center;
        }
    }
</style>

<div class="container-fluid">

    <!-- Header da Página -->
    <div class="page-header">
        <div class="page-header-content">
            <h2>
                <i class="bi bi-megaphone"></i>
                Propagandas
            </h2>
            <p>Gerencie os banners exibidos em carrossel no seu aplicativo</p>
        </div>
        <button type="button" class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#addBannerModal">
            <i class="bi bi-plus-lg"></i>
            Adicionar Banner
        </button>
    </div>

    <!-- Tabela de Banners -->
    <div class="table-container">
        <div class="table-header">
            <span class="table-header-title">
                <i class="bi bi-list-ol me-2"></i>Banners Cadastrados
            </span>
            <span class="badge bg-primary bg-opacity-10 text-primary rounded-pill px-3 py-1" style="font-size: 0.8rem;">
                <?php echo count($banners); ?> banner(s)
            </span>
        </div>

        <!-- Ações em Massa -->
        <div id="bulkActions" style="display: none; background: var(--bg-tertiary); padding: 0.75rem 1.5rem; border-bottom: 1px solid var(--border); align-items: center; justify-content: space-between;">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-check-square text-warning"></i>
                <span style="color: var(--warning); font-weight: 600; font-size: 0.85rem;">
                    <span id="bulkCount">0</span> selecionado(s)
                </span>
            </div>
            <button type="button" class="btn btn-sm btn-outline-danger" onclick="confirmBulkDelete()" style="border-radius: 50px; padding: 4px 16px;">
                <i class="bi bi-trash"></i> Remover Selecionados
            </button>
        </div>

        <form id="bulkDeleteForm">
        <div class="table-responsive">
            <table id="propagandaTable" class="table-custom">
                <thead>
                    <tr>
                        <th style="width: 40px;" class="text-center">
                            <input type="checkbox" class="form-check-input" id="selectAll">
                        </th>
                        <th style="width: 50%;">Preview do Banner</th>
                        <th style="width: 20%;" class="text-center">Posição</th>
                        <th style="width: 15%;" class="text-end"><i class="bi bi-lightning-charge me-2"></i>Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($banners) === 0): ?>
                        <tr>
                            <td colspan="4">
                                <div class="empty-state">
                                    <div class="empty-state-icon" style="font-size: 4rem; opacity: 0.5; margin-bottom: 1rem; color: var(--accent);">
                                        <i class="bi bi-images"></i>
                                    </div>
                                    <p class="empty-state-text">
                                        Nenhum banner cadastrado para este tema.<br>
                                        Clique em "Adicionar Banner" para começar.
                                    </p>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($banners as $index => $row): ?>
                            <tr>
                                <td class="text-center checkbox-cell">
                                    <input type="checkbox" name="selected_banners[]" value="<?php echo $row['id']; ?>" class="form-check-input banner-checkbox">
                                </td>
                                <td data-label="Preview do Banner">
                                    <div class="banner-preview-wrapper">
                                        <div class="banner-thumbnail">
                                            <img src="<?php echo htmlspecialchars($row['image_url']); ?>"
                                                alt="Banner <?php echo $index + 1; ?>" loading="lazy">
                                        </div>
                                        <div class="banner-url-text" title="<?php echo htmlspecialchars($row['image_url']); ?>">
                                            <i class="bi bi-link-45deg"></i>
                                            <?php echo htmlspecialchars($row['image_url']); ?>
                                        </div>
                                    </div>
                                </td>
                                <td data-label="Posição" class="text-center">
                                    <div class="order-controls">
                                        <button class="btn-order" onclick="moveBanner(<?php echo $row['id']; ?>, 'up')" <?php echo $index === 0 ? 'disabled' : ''; ?> title="Mover para cima">
                                            <i class="bi bi-chevron-up"></i>
                                        </button>
                                        <span class="order-number"><?php echo $index + 1; ?></span>
                                        <button class="btn-order" onclick="moveBanner(<?php echo $row['id']; ?>, 'down')" <?php echo $index === count($banners) - 1 ? 'disabled' : ''; ?> title="Mover para baixo">
                                            <i class="bi bi-chevron-down"></i>
                                        </button>
                                    </div>
                                </td>
                                <td class="text-end">
                                    <button type="button" class="btn-action-custom"
                                        onclick="confirmDelete(<?php echo $row['id']; ?>)" title="Excluir banner">
                                        <i class="bi bi-trash3"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        </form>
    </div>
</div>

<!-- Modal Adicionar Banner -->
<div class="modal fade" id="addBannerModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-content-custom">
            <div class="modal-header-custom">
                <h5 class="modal-title-custom">
                    <i class="bi bi-cloud-arrow-up"></i>
                    Novo Banner
                </h5>
                <button type="button" class="btn-close-custom" data-bs-dismiss="modal">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            <form method="POST" enctype="multipart/form-data" id="addBannerForm">
                <div class="modal-body-custom">
                    <label class="form-label-custom">Upload da Imagem</label>
                    <p style="color: var(--text-muted); font-size: 0.8rem; margin-bottom: 0.75rem;">
                        Recomendado: Proporção 16:9 (ex: 1920x1080px). Máx. 5MB.
                    </p>

                    <div class="upload-zone" id="imageDropzone">
                        <div id="uploadPlaceholder">
                            <div class="upload-zone-icon" style="font-size: 2.5rem; color: var(--accent); opacity: 0.7; margin-bottom: 0.5rem;">
                                <i class="bi bi-images"></i>
                            </div>
                            <p class="upload-zone-text">Arraste uma imagem ou clique para selecionar</p>
                            <p class="upload-zone-hint">Formatos aceitos: JPG, PNG, WEBP</p>
                        </div>
                        <div id="imagePreviewArea" style="display: none;">
                            <img id="imagePreview" class="preview-image" alt="Preview">
                            <br>
                            <button type="button" class="btn-remove-image" id="clearImageBtn">
                                <i class="bi bi-trash me-1"></i> Remover imagem
                            </button>
                        </div>
                        <input type="file" name="prop_file" id="propFileInput" style="display: none;"
                            accept="image/jpeg,image/png,image/webp">
                    </div>
                    <div class="error-message" id="imageError">Selecione um formato válido (JPG, PNG, WEBP) de até 5MB.
                    </div>

                    <div class="divider-text">OU</div>

                    <div>
                        <label class="form-label-custom">URL Externa</label>
                        <input type="url" name="image_url" id="imageUrlInput" class="form-control-custom"
                            placeholder="https://exemplo.com/banner.jpg">
                    </div>
                </div>

                <div class="modal-footer-custom">
                    <button type="button" class="btn-outline-custom" data-bs-dismiss="modal">
                        Cancelar
                    </button>
                    <button type="submit" name="add_propaganda" class="btn-submit-custom" id="submitBannerBtn">
                        <i class="bi bi-plus-lg me-2"></i> Adicionar à Fila
                    </button>
                </div>
                <input type="hidden" name="save_propaganda_hidden" value="1">
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    // ========== DRAG & DROP ==========
    const dropzone = document.getElementById('imageDropzone');
    const fileInput = document.getElementById('propFileInput');
    const previewArea = document.getElementById('imagePreviewArea');
    const uploadPlaceholder = document.getElementById('uploadPlaceholder');
    const previewImg = document.getElementById('imagePreview');
    const clearBtn = document.getElementById('clearImageBtn');
    const urlInput = document.getElementById('imageUrlInput');
    const imageError = document.getElementById('imageError');

    dropzone.addEventListener('click', (e) => {
        if (e.target !== clearBtn && !clearBtn.contains(e.target)) {
            fileInput.click();
        }
    });

    dropzone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropzone.classList.add('drag-over');
    });

    dropzone.addEventListener('dragleave', () => dropzone.classList.remove('drag-over'));

    dropzone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropzone.classList.remove('drag-over');
        if (e.dataTransfer.files.length) handleImageFile(e.dataTransfer.files[0]);
    });

    fileInput.addEventListener('change', () => {
        if (fileInput.files.length) handleImageFile(fileInput.files[0]);
    });

    function handleImageFile(file) {
        const validTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (!validTypes.includes(file.type) || file.size > 5 * 1024 * 1024) {
            imageError.style.display = 'block';
            fileInput.value = '';
            return;
        }
        imageError.style.display = 'none';
        const reader = new FileReader();
        reader.onload = (ev) => {
            previewImg.src = ev.target.result;
            uploadPlaceholder.style.display = 'none';
            previewArea.style.display = 'block';
            urlInput.value = '';
        };
        reader.readAsDataURL(file);
    }

    clearBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        fileInput.value = '';
        uploadPlaceholder.style.display = 'block';
        previewArea.style.display = 'none';
        urlInput.value = '';
        imageError.style.display = 'none';
    });

    urlInput.addEventListener('input', function () {
        if (this.value.trim()) {
            previewImg.src = this.value;
            uploadPlaceholder.style.display = 'none';
            previewArea.style.display = 'block';
            fileInput.value = '';
            imageError.style.display = 'none';
        } else {
            clearBtn.click();
        }
    });

    document.getElementById('addBannerForm').addEventListener('submit', function (e) {
        if (!fileInput.files.length && !urlInput.value.trim()) {
            e.preventDefault();
            imageError.style.display = 'block';
            imageError.innerText = 'Forneça uma imagem via Upload ou URL.';
            return;
        }
    });

    <?php if ($msg): ?>
    Swal.fire({
        title: 'Sucesso!',
        text: '<?php echo htmlspecialchars($msg); ?>',
        icon: 'success',
        background: '#111827',
        color: '#f1f5f9',
        confirmButtonColor: '#3b82f6'
    });
    <?php endif; ?>

    <?php if (isset($msg_error)): ?>
    Swal.fire({
        title: 'Erro!',
        html: '<?php echo $msg_error; ?>',
        icon: 'error',
        background: '#111827',
        color: '#f1f5f9',
        confirmButtonColor: '#ef4444'
    });
    <?php endif; ?>

    // ========== REORDENAÇÃO AJAX ==========
    function moveBanner(id, direction) {
        fetch('propaganda.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=reorder&id=${id}&direction=${direction}`
        })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    window.location.reload();
                } else {
                    Swal.fire('Erro', 'Não foi possível mover o banner.', 'error');
                }
            })
            .catch(() => Swal.fire('Erro', 'Ocorreu um problema de conexão.', 'error'));
    }

    // ========== EXCLUSÃO ==========
    function confirmDelete(id) {
        Swal.fire({
            title: 'Remover banner?',
            text: "Ele não será mais exibido neste tema da TV Box.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#3b82f6',
            confirmButtonText: 'Sim, excluir',
            cancelButtonText: 'Cancelar',
            background: '#111827',
            color: '#f1f5f9'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'propaganda.php?delete=' + id;
            }
        });
    }

    // ========== SELEÇÃO EM MASSA ==========
    const selectAll = document.getElementById('selectAll');
    const bulkActions = document.getElementById('bulkActions');
    const bulkCount = document.getElementById('bulkCount');
    const bannerCheckboxes = document.querySelectorAll('.banner-checkbox');

    function updateBulkUI() {
        const selected = document.querySelectorAll('.banner-checkbox:checked').length;
        if (selected > 0) {
            bulkActions.style.display = 'flex';
            bulkCount.textContent = selected;
        } else {
            bulkActions.style.display = 'none';
            if (selectAll) selectAll.checked = false;
        }
    }

    if (selectAll) {
        selectAll.addEventListener('change', function() {
            bannerCheckboxes.forEach(cb => {
                cb.checked = this.checked;
            });
            updateBulkUI();
        });
    }

    bannerCheckboxes.forEach(cb => {
        cb.addEventListener('change', updateBulkUI);
    });

    window.confirmBulkDelete = function() {
        Swal.fire({
            title: 'Remover banners selecionados?',
            text: "Eles não serão mais exibidos neste tema da TV Box.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#3b82f6',
            confirmButtonText: 'Sim, excluir todos',
            cancelButtonText: 'Cancelar',
            background: '#111827',
            color: '#f1f5f9'
        }).then((result) => {
            if (result.isConfirmed) {
                const formData = new FormData(document.getElementById('bulkDeleteForm'));
                formData.append('bulk_delete', '1');
                
                fetch('propaganda.php', {
                    method: 'POST',
                    body: formData
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire({
                            title: 'Excluído!',
                            text: 'Os banners selecionados foram removidos.',
                            icon: 'success',
                            background: '#111827',
                            color: '#f1f5f9',
                            confirmButtonColor: '#3b82f6'
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Erro',
                            text: 'Não foi possível excluir os banners.',
                            icon: 'error',
                            background: '#111827',
                            color: '#f1f5f9'
                        });
                    }
                })
                .catch(() => {
                    Swal.fire({
                        title: 'Erro',
                        text: 'Erro de conexão.',
                        icon: 'error',
                        background: '#111827',
                        color: '#f1f5f9'
                    });
                });
            }
        });
    };
</script>

<?php
include 'includes/layout-close.php';
include 'includes/footer.php';
?>