<?php if (!function_exists('avatar_img')) { @include_once '../../helpers.php'; } ?>


<!-- Restored Admin Styles -->
<style>

        :root {
            --primary: #4361ee;
            --primary-dark: #3a56d4;
            --secondary: #6c757d;
            --success: #28a745;
            --danger: #dc3545;
            --warning: #ffc107;
            --info: #17a2b8;
            --light: #f8f9fa;
            --dark: #343a40;
            --bg-main: #f5f7f9;
            --bg-card: #ffffff;
            --text-main: #212529;
            --text-muted: #6c757d;
            --border: #dee2e6;
            --radius: 8px;
            --radius-sm: 4px;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
            --purple: #6f42c1;
            --purple-dark: #5a32a3;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: var(--bg-main);
            color: var(--text-main);
            line-height: 1.6;
            padding: 20px;
        }

        .admin-container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .admin-header {
            display: flex;
            align-items: center;
            margin-bottom: 24px;
            gap: 16px;
        }

        .back-button {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--bg-card);
            color: var(--primary);
            border: 1px solid var(--border);
            cursor: pointer;
            transition: var(--transition);
            text-decoration: none;
        }

        .back-button:hover {
            background: var(--primary);
            color: white;
        }

        .admin-header h1 {
            font-size: 28px;
            font-weight: 700;
            color: var(--dark);
            margin-bottom: 0;
        }

        .admin-header p {
            color: var(--text-muted);
            font-size: 16px;
        }

        .admin-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: var(--bg-card);
            border-radius: var(--radius);
            padding: 20px;
            box-shadow: var(--shadow);
            transition: var(--transition);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        .stat-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }

        .stat-title {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .stat-icon.ads {
            background: rgba(111, 66, 193, 0.1);
            color: var(--purple);
        }

        .stat-icon.budget {
            background: rgba(40, 167, 69, 0.1);
            color: var(--success);
        }

        .stat-icon.impressions {
            background: rgba(255, 193, 7, 0.1);
            color: var(--warning);
        }

        .stat-icon.clicks {
            background: rgba(220, 53, 69, 0.1);
            color: var(--danger);
        }

        .stat-value {
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 12px;
            color: var(--dark);
        }

        .stat-desc {
            font-size: 14px;
            color: var(--text-muted);
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .trend {
            font-size: 12px;
            font-weight: 600;
            padding: 4px 8px;
            border-radius: 20px;
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }

        .trend.positive {
            background: rgba(40, 199, 111, 0.2);
            color: #28c76f;
        }

        .trend.negative {
            background: rgba(255, 77, 77, 0.2);
            color: #ff4d4d;
        }

        .filters {
            background: var(--bg-card);
            border-radius: var(--radius);
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: var(--shadow);
        }

        .filter-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
        }

        .filter-label {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
            color: var(--text-muted);
        }

        .filter-input, .filter-select {
            padding: 10px 12px;
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            font-size: 14px;
            transition: var(--transition);
        }

        .filter-input:focus, .filter-select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
        }

        .filter-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .btn {
            padding: 10px 20px;
            border-radius: var(--radius-sm);
            font-size: 14px;
            font-weight: 600;
            text-decoration: none;
            cursor: pointer;
            transition: var(--transition);
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
        }

        .btn-purple {
            background: var(--purple);
            color: white;
        }

        .btn-purple:hover {
            background: var(--purple-dark);
        }

        .btn-success {
            background: var(--success);
            color: white;
        }

        .btn-success:hover {
            background: #218838;
        }

        .btn-warning {
            background: var(--warning);
            color: var(--dark);
        }

        .btn-warning:hover {
            background: #e0a800;
        }

        .btn-danger {
            background: var(--danger);
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .btn-outline {
            background: transparent;
            border: 1px solid var(--border);
            color: var(--text-muted);
        }

        .btn-outline:hover {
            background: var(--bg-main);
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }

        .ads-table {
            width: 100%;
            background: var(--bg-card);
            border-radius: var(--radius);
            overflow: hidden;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
        }

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

        .ads-table th {
            background: var(--bg-main);
            padding: 16px;
            text-align: left;
            font-weight: 600;
            color: var(--text-muted);
            font-size: 14px;
        }

        .ads-table td {
            padding: 16px;
            border-top: 1px solid var(--border);
        }

        .ads-table tr:hover {
            background: var(--bg-main);
        }

        .ad-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .ad-image {
            width: 60px;
            height: 40px;
            border-radius: 6px;
            object-fit: cover;
            background: var(--bg-main);
        }

        .ad-details {
            display: flex;
            flex-direction: column;
        }

        .ad-title {
            font-weight: 600;
            margin-bottom: 4px;
        }

        .ad-advertiser {
            font-size: 14px;
            color: var(--text-muted);
        }

        .badge {
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: inline-block;
        }

        .badge-success {
            background: rgba(40, 167, 69, 0.1);
            color: var(--success);
        }

        .badge-warning {
            background: rgba(255, 193, 7, 0.1);
            color: var(--warning);
        }

        .badge-danger {
            background: rgba(220, 53, 69, 0.1);
            color: var(--danger);
        }

        .badge-info {
            background: rgba(23, 162, 184, 0.1);
            color: var(--info);
        }

        .badge-secondary {
            background: rgba(108, 117, 125, 0.1);
            color: var(--secondary);
        }

        .badge-purple {
            background: rgba(111, 66, 193, 0.1);
            color: var(--purple);
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-icon {
            width: 32px;
            height: 32px;
            border-radius: var(--radius-sm);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: var(--transition);
            border: none;
        }

        .btn-view {
            background: rgba(23, 162, 184, 0.1);
            color: var(--info);
        }

        .btn-view:hover {
            background: rgba(23, 162, 184, 0.2);
        }

        .btn-edit {
            background: rgba(255, 193, 7, 0.1);
            color: var(--warning);
        }

        .btn-edit:hover {
            background: rgba(255, 193, 7, 0.2);
        }

        .btn-delete {
            background: rgba(220, 53, 69, 0.1);
            color: var(--danger);
        }

        .btn-delete:hover {
            background: rgba(220, 53, 69, 0.2);
        }

        .btn-pause {
            background: rgba(108, 117, 125, 0.1);
            color: var(--secondary);
        }

        .btn-pause:hover {
            background: rgba(108, 117, 125, 0.2);
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 12px;
            margin-top: 20px;
        }

        .pagination-info {
            font-size: 14px;
            color: var(--text-muted);
        }

        .pagination-button {
            padding: 8px 16px;
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            background: var(--bg-card);
            color: var(--text-main);
            cursor: pointer;
            transition: var(--transition);
        }

        .pagination-button:hover:not(:disabled) {
            background: var(--bg-main);
        }

        .pagination-button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .pagination-active {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: var(--bg-card);
            border-radius: var(--radius);
            width: 100%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
        }

        .modal-header {
            padding: 20px;
            border-bottom: 1px solid var(--border);
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: var(--bg-main);
        }

        .modal-title {
            font-size: 18px;
            font-weight: 600;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: var(--text-muted);
        }

        .modal-body {
            padding: 20px;
        }

        .modal-form-group {
            margin-bottom: 16px;
        }

        .modal-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            font-size: 14px;
        }

        .modal-input, .modal-select, .modal-textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            font-size: 14px;
            transition: var(--transition);
        }

        .modal-input:focus, .modal-select:focus, .modal-textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
        }

        .modal-textarea {
            min-height: 80px;
            resize: vertical;
        }

        .modal-footer {
            padding: 20px;
            border-top: 1px solid var(--border);
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            background: var(--bg-main);
        }

        .ad-preview {
            border: 2px dashed var(--border);
            border-radius: var(--radius);
            padding: 20px;
            margin: 15px 0;
            text-align: center;
            background: var(--bg-main);
        }

        .ad-preview img {
            max-width: 100%;
            height: 120px;
            object-fit: cover;
            border-radius: 6px;
            margin-bottom: 10px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin-top: 10px;
        }

        .stat-item {
            background: var(--bg-main);
            padding: 8px;
            border-radius: var(--radius-sm);
            text-align: center;
        }

        .stat-value-small {
            font-weight: 600;
            font-size: 14px;
        }

        .stat-label {
            font-size: 12px;
            color: var(--text-muted);
        }

        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .image-upload-container {
            border: 2px dashed var(--border);
            border-radius: var(--radius-sm);
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: var(--transition);
        }

        .image-upload-container:hover {
            border-color: var(--primary);
            background: rgba(67, 97, 238, 0.05);
        }

        .image-upload-container.dragover {
            border-color: var(--success);
            background: rgba(40, 167, 69, 0.1);
        }

        .upload-icon {
            font-size: 48px;
            color: var(--text-muted);
            margin-bottom: 10px;
        }

        .upload-text {
            color: var(--text-muted);
            margin-bottom: 10px;
        }

        .image-preview {
            max-width: 100%;
            max-height: 200px;
            border-radius: 6px;
            display: none;
        }

        /* Responsive */
        @media (max-width: 1024px) {
            .ads-table {
                overflow-x: auto;
            }
            
            .ads-table table {
                min-width: 1000px;
            }
            
            .filter-row {
                grid-template-columns: 1fr;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .admin-stats {
                grid-template-columns: 1fr;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .btn-icon {
                width: 28px;
                height: 28px;
            }
            
            .admin-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .modal-content {
                margin: 20px;
                width: calc(100% - 40px);
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    
</style>
<div class="admin-container">
        <div class="admin-header">
            <a href="./?r=admin/dashboard" class="back-button" title="Volver al dashboard">
                <i class="fas fa-arrow-left"></i>
            </a>
            <div>
                <h1><?= h($pageTitle) ?></h1>
                <p><?= h($pageSubtitle) ?></p>
            </div>
        </div>

        <!-- Estadísticas de anuncios -->
        <div class="admin-stats">
            <div class="stat-card">
                <div class="stat-header">
                    <div class="stat-title">Anuncios Activos</div>
                    <div class="stat-icon ads">
                        <i class="fas fa-bullhorn"></i>
                    </div>
                </div>
                <div class="stat-value"><?= h($adStats['active_ads'] ?? 0) ?></div>
                <div class="stat-desc">
                    <span class="trend positive">
                        <i class="fas fa-arrow-up"></i> 
                        <?= h(($adStats['total_ads'] ?? 0) > 0 ? round((($adStats['active_ads'] ?? 0) / ($adStats['total_ads'] ?? 1)) * 100) : 0) ?>%
                    </span>
                    del total
                </div>
                <div style="margin-top: auto;">
                    <a href="?r=admin/ads&status=active" class="btn btn-purple btn-sm" style="width: 100%; text-align: center;">
                        Ver Activos
                    </a>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <div class="stat-title">Presupuesto Total</div>
                    <div class="stat-icon budget">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
                <div class="stat-value">$<?= h(number_format($adStats['total_budget'] ?? 0, 2)) ?></div>
                <div class="stat-desc">
                    <span class="trend positive"><i class="fas fa-chart-line"></i> Ingresos</span>
                    por publicidad
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <div class="stat-title">Impresiones</div>
                    <div class="stat-icon impressions">
                        <i class="fas fa-eye"></i>
                    </div>
                </div>
                <div class="stat-value"><?= h(number_format($adStats['total_impressions'] ?? 0)) ?></div>
                <div class="stat-desc">
                    <span class="trend positive">
                        <i class="fas fa-mouse-pointer"></i> 
                        <?= h($adStats['ctr'] ?? 0) ?>% CTR
                    </span>
                    tasa de clics
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <div class="stat-title">Clics Totales</div>
                    <div class="stat-icon clicks">
                        <i class="fas fa-hand-pointer"></i>
                    </div>
                </div>
                <div class="stat-value"><?= h(number_format($adStats['total_clicks'] ?? 0)) ?></div>
                <div class="stat-desc">
                    <span class="trend positive"><i class="fas fa-arrow-up"></i> Engagement</span>
                    interacciones
                </div>
            </div>
        </div>

        <!-- Filtros y acciones -->
        <div class="filters">
            <div class="filter-row">
                <div class="filter-group">
                    <label class="filter-label">Buscar anuncio</label>
                    <input type="text" class="filter-input" placeholder="Título o anunciante" id="searchInput">
                </div>
                
                <div class="filter-group">
                    <label class="filter-label">Estado</label>
                    <select class="filter-select" id="statusFilter">
                        <option value="">Todos los estados</option>
                        <option value="active">Activo</option>
                        <option value="pending">Pendiente</option>
                        <option value="paused">Pausado</option>
                        <option value="expired">Expirado</option>
                    </select>
                </div>
                
                <div class="filter-group">
                    <label class="filter-label">Ordenar por</label>
                    <select class="filter-select" id="sortFilter">
                        <option value="newest">Más recientes</option>
                        <option value="oldest">Más antiguos</option>
                        <option value="budget">Mayor presupuesto</option>
                        <option value="clicks">Más clics</option>
                    </select>
                </div>
            </div>
            
            <div class="filter-actions">
                <button onclick="showCreateAdModal()" class="btn btn-purple">
                    <i class="fas fa-plus"></i> Crear Anuncio
                </button>
                <button onclick="applyFilters()" class="btn btn-primary">
                    <i class="fas fa-filter"></i> Aplicar Filtros
                </button>
                <button onclick="clearFilters()" class="btn btn-outline">
                    <i class="fas fa-times"></i> Limpiar
                </button>
            </div>
        </div>

        <!-- Lista de anuncios -->
        <div class="ads-table">
<div class="totals-bar" style="display:flex;gap:16px;align-items:center;margin:10px 0;padding:10px;border:1px dashed #e0e0e0;border-radius:8px;background:#fafbff">
  <div><strong>Impresiones (visibles):</strong> <span id="tImpr">0</span></div>
  <div><strong>Clics (visibles):</strong> <span id="tClicks">0</span></div>
  <div><strong>CTR (visible):</strong> <span id="tCtr">0%</span></div>
  <div style="margin-left:auto;display:flex;gap:8px;align-items:center">
    <label style="font-size:.9rem">Densidad</label>
    <select id="densitySel">
      <option value="comfortable">Cómoda</option>
      <option value="compact">Compacta</option>
    </select>
  </div>
</div>

            
<div class="table-tools" style="display:flex; gap:12px; align-items:center; margin: 8px 0 12px;">
  <input id="tableFilter" type="search" placeholder="Buscar…" style="padding:.5rem .75rem;border:1px solid #ddd;border-radius:8px;min-width:220px">
  <button id="exportCsvBtn" type="button" class="btn" style="padding:.5rem .75rem;border:1px solid #ddd;border-radius:8px;background:#f8f9fa;cursor:pointer">Exportar CSV</button>
</div>

<table>
                <thead>
                    <tr>
                        <th>Anuncio</th>
                        <th data-sort="advertiser">Anunciante <i class="fas fa-sort"></i></th>
                        <th data-sort="budget">Presupuesto <i class="fas fa-sort"></i></th>
                        <th data-sort="stats">Estadísticas <i class="fas fa-sort"></i></th>
                        <th>Estado</th>
                        <th>Vigencia</th>
                        <th>Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($ads)): ?>
                        <?php foreach($ads as $ad): ?>
                        <tr data-impressions=\"<?= (int)($ad['impressions'] ?? 0) ?>\" data-clicks=\"<?= (int)($ad['clicks'] ?? 0) ?>\" data-ctr=\"<?= (($ad['impressions'] ?? 0) > 0 ? round(($ad['clicks'] ?? 0)/$ad['impressions']*100,2) : 0) ?>\" data-budget=\"<?= (float)($ad['budget'] ?? 0) ?>\">
                            <td>
                                <div class="ad-info">
                                    <img src="<?= h(media_url($ad['image_url'])) ?>" alt="<?= h($ad['title']) ?>" class="ad-image" onerror="this.src='https://via.placeholder.com/60x40?text=Ad'">
                                    <div class="ad-details">
                                        <div class="ad-title"><?= h($ad['title']) ?></div>
                                        <div class="ad-advertiser">ID: <?= h($ad['id'] ?: 'N/A') ?></div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <strong><?= h($ad['advertiser']) ?></strong>
                            </td>
                            <td>
                                <strong>$<?= h(number_format($ad['budget'], 2)) ?></strong>
                            </td>
                            <td>
                                <div class="stats-grid">
                                    <div class="stat-item">
                                        <div class="stat-value-small"><?= h($ad['impressions'] ?? 0) ?></div>
                                        <div class="stat-label">Impresiones</div>
                                    </div>
                                    <div class="stat-item">
                                        <div class="stat-value-small"><?= h($ad['clicks'] ?? 0) ?></div>
                                        <div class="stat-label">Clics</div>
                                    </div>
                                    <div class="stat-item">
                                        <div class="stat-value-small"><?= h(($ad['impressions'] ?? 0) > 0 ? round((($ad['clicks'] ?? 0) / ($ad['impressions'] ?? 1)) * 100, 1) : 0) ?>%</div>
                                        <div class="stat-label">CTR</div>
                                    </div>
                                    <div class="stat-item">
                                        <div class="stat-value-small">$<?= h(($ad['clicks'] ?? 0) > 0 ? number_format(($ad['budget'] ?? 0) / ($ad['clicks'] ?? 1), 2) : 0) ?></div>
                                        <div class="stat-label">Costo por clic</div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="badge badge-<?= 
                                    $ad['status'] === 'active' ? 'success' : 
                                    ($ad['status'] === 'pending' ? 'warning' : 
                                    ($ad['status'] === 'paused' ? 'secondary' : 'danger'))
                                ?>">
                                    <?= h(ucfirst($ad['status'])) ?>
                                </span>
                                <?php if ($ad['status'] === 'active' && strtotime($ad['end_date']) < time()): ?>
                                    <div class="badge badge-danger" style="margin-top: 4px; font-size: 10px;" style="overflow:hidden;border-radius:50%;padding:0;background:none;">EXPIRADO</div>
                                <?php elseif ($ad['status'] === 'active' && strtotime($ad['start_date']) > time()): ?>
                                    <div class="badge badge-warning" style="margin-top: 4px; font-size: 10px;" style="overflow:hidden;border-radius:50%;padding:0;background:none;">PROGRAMADO</div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div style="font-size: 14px;">
                                    <div><strong>Inicio:</strong> <?= h(fdt($ad['start_date'], 'd/m/Y H:i')) ?></div>
                                    <div><strong>Fin:</strong> <?= h(fdt($ad['end_date'], 'd/m/Y H:i')) ?></div>
                                    <?php if (strtotime($ad['end_date']) < time()): ?>
                                        <div class="badge badge-danger" style="margin-top: 4px;" style="overflow:hidden;border-radius:50%;padding:0;background:none;">Expirado</div>
                                    <?php elseif (strtotime($ad['start_date']) > time()): ?>
                                        <div class="badge badge-warning" style="margin-top: 4px;" style="overflow:hidden;border-radius:50%;padding:0;background:none;">Programado</div>
                                    <?php else: ?>
                                        <div class="badge badge-success" style="margin-top: 4px;" style="overflow:hidden;border-radius:50%;padding:0;background:none;">En curso</div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn-icon btn-view" title="Vista previa" onclick="previewAd('<?= h($ad['id']) ?>')">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button class="btn-icon btn-edit" title="Editar anuncio" onclick="editAd('<?= h($ad['id']) ?>')">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <?php if ($ad['status'] === 'active' && strtotime($ad['start_date']) <= time() && strtotime($ad['end_date']) >= time()): ?>
                                        <button class="btn-icon btn-pause" title="Pausar anuncio" onclick="pauseAd('<?= h($ad['id']) ?>')">
                                            <i class="fas fa-pause"></i>
                                        </button>
                                    <?php elseif ($ad['status'] === 'paused'): ?>
                                        <button class="btn-icon btn-success" title="Activar anuncio" onclick="activateAd('<?= h($ad['id']) ?>')">
                                            <i class="fas fa-play"></i>
                                        </button>
                                    <?php endif; ?>
                                    <button class="btn-icon btn-delete" title="Eliminar anuncio" onclick="deleteAd('<?= h($ad['id']) ?>', '<?= h($ad['title']) ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" style="text-align: center; padding: 40px; color: var(--text-muted);">
                                <i class="fas fa-bullhorn" style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;"></i>
                                <p>No hay anuncios creados</p>
                                <button onclick="showCreateAdModal()" class="btn btn-purple" style="margin-top: 16px;">
                                    <i class="fas fa-plus"></i> Crear primer anuncio
                                </button>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Paginación -->
        <?php if ($pagination['totalPages'] > 1): ?>
        <div class="pagination">
            <button class="pagination-button" <?= $pagination['page'] <= 1 ? 'disabled' : '' ?> onclick="changePage(<?= $pagination['page'] - 1 ?>)">
                <i class="fas fa-chevron-left"></i> Anterior
            </button>
            
            <span class="pagination-info">
                Página <?= $pagination['page'] ?> de <?= $pagination['totalPages'] ?>
                (<?= $pagination['totalItems'] ?> anuncios)
            </span>
            
            <button class="pagination-button" <?= $pagination['page'] >= $pagination['totalPages'] ? 'disabled' : '' ?> onclick="changePage(<?= $pagination['page'] + 1 ?>)">
                Siguiente <i class="fas fa-chevron-right"></i>
            </button>
        </div>
        <?php endif; ?>
    </div>

    <!-- Modal para crear anuncio -->
    <div class="modal" id="createAdModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Crear Nuevo Anuncio</h3>
                <button class="modal-close" onclick="closeModal('createAdModal')">&times;</button>
            </div>
            
            <form method="post" action="./?r=admin/create-ad" id="createAdForm" enctype="multipart/form-data">
                <?= csrf_field() ?>
                
                <div class="modal-body">
                    <div class="form-grid">
                        <div class="modal-form-group">
                            <label class="modal-label">Título del Anuncio *</label>
                            <input type="text" name="title" class="modal-input" required placeholder="Ej: Oferta Especial de Verano">
                        </div>
                        
                        <div class="modal-form-group">
                            <label class="modal-label">Anunciante *</label>
                            <input type="text" name="advertiser" class="modal-input" required placeholder="Nombre de la empresa">
                        </div>
                    </div>
                    
                    <div class="modal-form-group">
                        <label class="modal-label">Descripción</label>
                        <textarea name="description" class="modal-textarea" placeholder="Descripción del anuncio..."></textarea>
                    </div>
                    
                    <!-- Upload de imagen mejorado -->
                    <div class="modal-form-group">
                        <label class="modal-label">Imagen del Anuncio *</label>
                        <div class="image-upload-container" id="imageUploadContainer">
                            <div class="upload-icon">
                                <i class="fas fa-cloud-upload-alt"></i>
                            </div>
                            <div class="upload-text">
                                <p>Haz clic para seleccionar una imagen o arrastra y suelta aquí</p>
                                <small>Formatos: JPG, PNG, GIF, WebP. Tamaño máximo: 2MB</small>
                            </div>
                            <img id="imagePreview" class="image-preview" alt="Vista previa">
                            <input type="file" name="ad_image" id="adImageInput" accept="image/*" required style="display: none;">
                        </div>
                    </div>
                    
                    <div class="modal-form-group">
                        <label class="modal-label">URL de Destino *</label>
                        <input type="url" name="target_url" class="modal-input" required placeholder="https://tu-sitio.com">
                    </div>
                    
                    <div class="form-grid">
                        <div class="modal-form-group">
                            <label class="modal-label">Presupuesto ($) *</label>
                            <input type="number" name="budget" step="0.01" min="0" class="modal-input" required placeholder="100.00">
                        </div>
                        
                        <div class="modal-form-group">
                            <label class="modal-label">Máximo de Impresiones</label>
                            <input type="number" name="max_impressions" min="0" class="modal-input" placeholder="Ilimitado">
                        </div>
                    </div>
                    
                    <div class="form-grid">
                        <div class="modal-form-group">
                            <label class="modal-label">Fecha de Inicio *</label>
                            <input type="datetime-local" name="start_date" class="modal-input" required>
                        </div>
                        
                        <div class="modal-form-group">
                            <label class="modal-label">Fecha de Fin *</label>
                            <input type="datetime-local" name="end_date" class="modal-input" required>
                        </div>
                    </div>
                    
                    <div class="modal-form-group">
                        <label class="modal-label">Audiencia Objetivo</label>
                        <select name="target_audience" class="modal-select">
                            <option value="all">Todos los usuarios</option>
                            <option value="verified">Solo verificados</option>
                            <option value="new_users">Usuarios nuevos (últimos 30 días)</option>
                        </select>
                    </div>
                    
                    <!-- Vista previa -->
                    <div class="ad-preview" id="adPreview">
                        <p style="color: var(--text-muted); margin-bottom: 10px;">Vista previa del anuncio</p>
                        <div id="previewContent">
                            <img src="https://via.placeholder.com/300x150?text=Imagen+del+anuncio" alt="Vista previa" style="max-width: 100%; height: 120px; object-fit: cover; border-radius: 6px; margin-bottom: 10px;">
                            <h4 style="margin: 10px 0 5px 0;">Título del anuncio</h4>
                            <p style="color: var(--text-muted); margin-bottom: 5px;">Descripción del anuncio...</p>
                            <small style="color: var(--text-muted);">Patrocinado por: Anunciante</small>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline" onclick="closeModal('createAdModal')">Cancelar</button>
                    <button type="submit" class="btn btn-purple">Crear Anuncio</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal para eliminar anuncio -->
    <div class="modal" id="deleteAdModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Eliminar Anuncio</h3>
                <button class="modal-close" onclick="closeModal('deleteAdModal')">&times;</button>
            </div>
            
            <form method="post" action="./?r=admin/delete-ad" id="deleteAdForm">
                <?= csrf_field() ?>
                <input type="hidden" name="ad_id" id="deleteAdId">
                
                <div class="modal-body">
                    <div class="modal-form-group">
                        <label class="modal-label">Anuncio a eliminar</label>
                        <input type="text" id="deleteAdTitle" class="modal-input" readonly>
                    </div>
                    
                    <div class="modal-form-group">
                        <label class="modal-label">Razón de la eliminación *</label>
                        <textarea name="reason" class="modal-textarea" required placeholder="Explica por qué se elimina este anuncio..."></textarea>
                    </div>
                    
                    <div style="background: rgba(220, 53, 69, 0.1); padding: 15px; border-radius: var(--radius-sm); margin-top: 15px;">
                        <p style="color: var(--danger); margin: 0; font-size: 14px;">
                            <i class="fas fa-exclamation-triangle"></i> 
                            <strong>Advertencia:</strong> Esta acción no se puede deshacer. Se perderán todas las estadísticas del anuncio.
                        </p>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline" onclick="closeModal('deleteAdModal')">Cancelar</button>
                    <button type="submit" class="btn btn-danger">Eliminar Anuncio</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal para vista previa -->
    <div class="modal" id="previewAdModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Vista Previa del Anuncio</h3>
                <button class="modal-close" onclick="closeModal('previewAdModal')">&times;</button>
            </div>
            <div class="modal-body">
                <div id="previewAdContent"></div>
            </div>
        </div>
    </div>

    <script>
    function changePage(page) {
        const url = new URL(window.location.href);
        url.searchParams.set('page', page);
        window.location.href = url.toString();
    }
    
    function showCreateAdModal() {
        document.getElementById('createAdModal').style.display = 'flex';
    }
    
    function deleteAd(adId, adTitle) {
        if (!adId || adId.trim() === '') {
            alert('Error: ID de anuncio no válido');
            return;
        }
        
        document.getElementById('deleteAdId').value = adId;
        document.getElementById('deleteAdTitle').value = adTitle;
        document.getElementById('deleteAdModal').style.display = 'flex';
    }
    
    // CORRECCIÓN: Función previewAd mejorada
    function previewAd(adId) {
        if (!adId || adId.trim() === '') {
            alert('Error: ID de anuncio no válido');
            return;
        }
        
        // Buscar el anuncio en la tabla de manera más robusta
        const rows = document.querySelectorAll('tr');
        let adData = null;
        
        for (let row of rows) {
            const adIdElement = row.querySelector('.ad-advertiser');
            if (adIdElement && adIdElement.textContent.includes(adId)) {
                const title = row.querySelector('.ad-title')?.textContent || 'Sin título';
                const advertiser = row.querySelector('td:nth-child(2) strong')?.textContent || 'Sin anunciante';
                const imageUrl = row.querySelector('.ad-image')?.src || 'https://via.placeholder.com/300x150?text=Imagen+no+disponible';
                const impressions = row.querySelector('.stat-item:nth-child(1) .stat-value-small')?.textContent || '0';
                const clicks = row.querySelector('.stat-item:nth-child(2) .stat-value-small')?.textContent || '0';
                
                adData = { title, advertiser, imageUrl, impressions, clicks };
                break;
            }
        }
        
        if (adData) {
            const previewContent = `
                <div style="text-align: center; padding: 20px;">
                    <img src="${adData.imageUrl}" alt="${adData.title}" 
                         style="max-width: 100%; max-height: 300px; border-radius: 8px; margin-bottom: 20px;">
                    <h3 style="margin-bottom: 10px;">${adData.title}</h3>
                    <p style="color: var(--text-muted); margin-bottom: 15px;">Patrocinado por: ${adData.advertiser}</p>
                    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-top: 20px;">
                        <div style="background: var(--bg-main); padding: 15px; border-radius: 6px;">
                            <div style="font-size: 24px; font-weight: bold; color: var(--primary);">${adData.impressions}</div>
                            <div style="font-size: 12px; color: var(--text-muted);">Impresiones</div>
                        </div>
                        <div style="background: var(--bg-main); padding: 15px; border-radius: 6px;">
                            <div style="font-size: 24px; font-weight: bold; color: var(--success);">${adData.clicks}</div>
                            <div style="font-size: 12px; color: var(--text-muted);">Clics</div>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('previewAdContent').innerHTML = previewContent;
            document.getElementById('previewAdModal').style.display = 'flex';
        } else {
            alert('No se pudo encontrar la información del anuncio');
        }
    }
    
    // CORRECCIÓN: Función editAd corregida
    function editAd(adId) {
        if (!adId || adId.trim() === '') {
            alert('Error: ID de anuncio no válido');
            return;
        }
        window.location.href = './?r=admin/edit-ad&id=' + adId;
    }
    
    // CORRECCIÓN: Función pauseAd mejorada
    function pauseAd(adId) {
        if (!adId || adId.trim() === '') {
            alert('Error: ID de anuncio no válido');
            return;
        }
        
        if (confirm('¿Estás seguro de que quieres pausar este anuncio?')) {
            const formData = new FormData();
            formData.append('ad_id', adId);
            formData.append('status', 'paused');
            formData.append('csrf_token', document.querySelector('input[name="csrf_token"]')?.value || '');
            
            fetch('./?r=admin/update-ad-status', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.ok) {
                    return response.text();
                }
                throw new Error('Error en la respuesta del servidor');
            })
            .then(data => {
                // Recargar la página para ver los cambios
                location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error al pausar el anuncio: ' + error.message);
            });
        }
    }
    
    // CORRECCIÓN: Función activateAd mejorada
    function activateAd(adId) {
        if (!adId || adId.trim() === '') {
            alert('Error: ID de anuncio no válido');
            return;
        }
        
        if (confirm('¿Estás seguro de que quieres activar este anuncio?')) {
            const formData = new FormData();
            formData.append('ad_id', adId);
            formData.append('status', 'active');
            formData.append('csrf_token', document.querySelector('input[name="csrf_token"]')?.value || '');
            
            fetch('./?r=admin/update-ad-status', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.ok) {
                    return response.text();
                }
                throw new Error('Error en la respuesta del servidor');
            })
            .then(data => {
                location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error al activar el anuncio: ' + error.message);
            });
        }
    }
    
    function applyFilters() {
        const search = document.getElementById('searchInput').value;
        const status = document.getElementById('statusFilter').value;
        const sort = document.getElementById('sortFilter').value;
        
        const url = new URL(window.location.href);
        
        if (search) url.searchParams.set('q', search);
        else url.searchParams.delete('q');
        
        if (status) url.searchParams.set('status', status);
        else url.searchParams.delete('status');
        
        if (sort) url.searchParams.set('sort', sort);
        else url.searchParams.delete('sort');
        
        url.searchParams.set('page', '1'); // Volver a la primera página
        
        window.location.href = url.toString();
    }
    
    function clearFilters() {
        window.location.href = './?r=admin/ads';
    }
    
    function closeModal(modalId) {
        document.getElementById(modalId).style.display = 'none';
    }
    
    // Cerrar modal al hacer clic fuera del contenido
    window.onclick = function(event) {
        const modals = document.getElementsByClassName('modal');
        for (let modal of modals) {
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        }
    };
    
    // Sistema de upload de imagen mejorado
    document.addEventListener('DOMContentLoaded', function() {
        const imageUploadContainer = document.getElementById('imageUploadContainer');
        const imageInput = document.getElementById('adImageInput');
        const imagePreview = document.getElementById('imagePreview');
        const uploadIcon = imageUploadContainer.querySelector('.upload-icon');
        const uploadText = imageUploadContainer.querySelector('.upload-text');
        
        // Click en el contenedor
        imageUploadContainer.addEventListener('click', function() {
            imageInput.click();
        });
        
        // Drag and drop
        imageUploadContainer.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.classList.add('dragover');
        });
        
        imageUploadContainer.addEventListener('dragleave', function() {
            this.classList.remove('dragover');
        });
        
        imageUploadContainer.addEventListener('drop', function(e) {
            e.preventDefault();
            this.classList.remove('dragover');
            
            if (e.dataTransfer.files.length > 0) {
                const file = e.dataTransfer.files[0];
                if (file.type.startsWith('image/')) {
                    handleImageFile(file);
                } else {
                    alert('Por favor, selecciona un archivo de imagen válido.');
                }
            }
        });
        
        // Cambio en el input de archivo
        imageInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                handleImageFile(this.files[0]);
            }
        });
        
        function handleImageFile(file) {
            // Validar tamaño (2MB máximo)
            if (file.size > 2 * 1024 * 1024) {
                alert('La imagen es demasiado grande. El tamaño máximo permitido es 2MB.');
                return;
            }
            
            // Validar tipo
            if (!file.type.startsWith('image/')) {
                alert('Por favor, selecciona un archivo de imagen válido (JPG, PNG, GIF, WebP).');
                return;
            }
            
            // Mostrar vista previa
            const reader = new FileReader();
            reader.onload = function(e) {
                imagePreview.src = e.target.result;
                imagePreview.style.display = 'block';
                uploadIcon.style.display = 'none';
                uploadText.style.display = 'none';
            };
            reader.readAsDataURL(file);
            
            // Actualizar vista previa del anuncio
            updateAdPreview();
        }
        
        // Actualizar vista previa del anuncio
        const form = document.getElementById('createAdForm');
        const preview = document.getElementById('previewContent');
        
        function updateAdPreview() {
            const title = form.title.value || 'Título del anuncio';
            const description = form.description.value || 'Descripción del anuncio';
            const advertiser = form.advertiser.value || 'Anunciante';
            
            let imageSrc = 'https://via.placeholder.com/300x150?text=Imagen+del+anuncio';
            if (imagePreview.style.display === 'block') {
                imageSrc = imagePreview.src;
            }
            
            preview.innerHTML = `
                <img src="${imageSrc}" alt="Vista previa" style="max-width: 100%; height: 120px; object-fit: cover; border-radius: 6px; margin-bottom: 10px;">
                <h4 style="margin: 10px 0 5px 0;">${title}</h4>
                <p style="color: var(--text-muted); margin-bottom: 5px;">${description}</p>
                <small style="color: var(--text-muted);">Patrocinado por: ${advertiser}</small>
            `;
        }
        
        // Actualizar vista previa cuando cambien los campos
        ['title', 'description', 'advertiser'].forEach(field => {
            if (form[field]) {
                form[field].addEventListener('input', updateAdPreview);
            }
        });
        
        updateAdPreview();
        
        // Cargar valores de filtros actuales
        const urlParams = new URLSearchParams(window.location.search);
        document.getElementById('statusFilter').value = urlParams.get('status') || '';
        document.getElementById('sortFilter').value = urlParams.get('sort') || 'newest';
        document.getElementById('searchInput').value = urlParams.get('q') || '';
    });
    </script>
