<?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: 1200px;
            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;
        }

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

        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 20px;
        }

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

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

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

        .form-textarea {
            min-height: 100px;
            resize: vertical;
        }

        .form-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid var(--border);
        }

        .btn {
            padding: 12px 24px;
            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-secondary {
            background: var(--secondary);
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

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

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

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

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

        .stats-info {
            background: var(--bg-main);
            padding: 20px;
            border-radius: var(--radius);
            margin-bottom: 20px;
        }

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

        .stat-item {
            text-align: center;
            padding: 10px;
            background: white;
            border-radius: var(--radius-sm);
            border: 1px solid var(--border);
        }

        .stat-value {
            font-weight: 700;
            font-size: 18px;
            color: var(--primary);
        }

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

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

        .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: block;
            margin: 0 auto 15px;
        }

        .current-image {
            text-align: center;
            margin-bottom: 15px;
        }

        .current-image img {
            max-width: 100%;
            max-height: 200px;
            border-radius: 6px;
            border: 2px solid var(--border);
        }

        .status-info {
            padding: 10px;
            border-radius: var(--radius-sm);
            margin-bottom: 15px;
            font-size: 14px;
        }

        .status-info.active {
            background: rgba(40, 167, 69, 0.1);
            border: 1px solid var(--success);
            color: var(--success);
        }

        .status-info.pending {
            background: rgba(255, 193, 7, 0.1);
            border: 1px solid var(--warning);
            color: var(--warning);
        }

        .status-info.paused {
            background: rgba(108, 117, 125, 0.1);
            border: 1px solid var(--secondary);
            color: var(--secondary);
        }

        .status-info.expired {
            background: rgba(220, 53, 69, 0.1);
            border: 1px solid var(--danger);
            color: var(--danger);
        }

        @media (max-width: 768px) {
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .form-actions {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
                justify-content: center;
            }
        }
    
</style>
<div class="admin-container">
        <div class="admin-header">
            <a href="./?r=admin/ads" class="back-button" title="Volver a anuncios">
                <i class="fas fa-arrow-left"></i>
            </a>
            <div>
                <h1><?= h($pageTitle) ?></h1>
                <p><?= h($pageSubtitle) ?></p>
            </div>
        </div>

        <!-- Información de estadísticas -->
        <div class="stats-info">
            <h3 style="margin-bottom: 15px;">Estadísticas del Anuncio</h3>
            <div class="stats-grid">
                <div class="stat-item">
                    <div class="stat-value"><?= h($ad['impressions']) ?></div>
                    <div class="stat-label">Impresiones</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value"><?= h($ad['clicks']) ?></div>
                    <div class="stat-label">Clics</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value"><?= h($ad['impressions'] > 0 ? round(($ad['clicks'] / $ad['impressions']) * 100, 1) : 0) ?>%</div>
                    <div class="stat-label">CTR</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">$<?= h(number_format($ad['budget'], 2)) ?></div>
                    <div class="stat-label">Presupuesto</div>
                </div>
            </div>
        </div>

        <!-- Información del estado actual -->
        <div class="status-info <?= h($ad['status']) ?>">
            <strong>Estado actual:</strong> 
            <?= h(ucfirst($ad['status'])) ?>
            
            <?php 
            $now = time();
            $start = strtotime($ad['start_date']);
            $end = strtotime($ad['end_date']);
            
            if ($ad['status'] === 'active'): ?>
                <?php if ($now < $start): ?>
                    - <strong>Programado</strong> (inicia <?= h(fdt($ad['start_date'], 'd/m/Y H:i')) ?>)
                <?php elseif ($now > $end): ?>
                    - <strong>Expirado</strong> (finalizó <?= h(fdt($ad['end_date'], 'd/m/Y H:i')) ?>)
                <?php else: ?>
                    - <strong>En curso</strong> (finaliza <?= h(fdt($ad['end_date'], 'd/m/Y H:i')) ?>)
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <form method="post" action="./?r=admin/update-ad" class="form-container" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <input type="hidden" name="ad_id" value="<?= h($ad['id']) ?>">
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Título del Anuncio *</label>
                    <input type="text" name="title" class="form-input" value="<?= h($ad['title']) ?>" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Anunciante *</label>
                    <input type="text" name="advertiser" class="form-input" value="<?= h($ad['advertiser']) ?>" required>
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label">Descripción</label>
                <textarea name="description" class="form-textarea"><?= h($ad['description']) ?></textarea>
            </div>
            
            <!-- Imagen actual -->
            <div class="form-group">
                <label class="form-label">Imagen Actual</label>
                <div class="current-image">
                    <img src="<?= h(media_url($ad['image_url'])) ?>" alt="Imagen actual" id="currentImage" 
                         onerror="this.src='https://via.placeholder.com/300x150?text=Imagen+no+disponible'">
                </div>
            </div>
            
            <!-- Upload de nueva imagen -->
            <div class="form-group">
                <label class="form-label">Cambiar Imagen (opcional)</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 nueva 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 de nueva imagen" style="display: none;">
                    <input type="file" name="ad_image" id="adImageInput" accept="image/*" style="display: none;">
                </div>
                <small style="color: var(--text-muted);">Si no seleccionas una nueva imagen, se mantendrá la actual.</small>
            </div>
            
            <div class="form-group">
                <label class="form-label">URL de Destino *</label>
                <input type="url" name="target_url" class="form-input" value="<?= h($ad['target_url']) ?>" required>
            </div>
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Presupuesto ($) *</label>
                    <input type="number" name="budget" step="0.01" min="0" class="form-input" value="<?= h($ad['budget']) ?>" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Máximo de Impresiones</label>
                    <input type="number" name="max_impressions" min="0" class="form-input" value="<?= h($ad['max_impressions']) ?>" placeholder="Ilimitado">
                </div>
            </div>
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Fecha de Inicio *</label>
                    <input type="datetime-local" name="start_date" class="form-input" value="<?= h(date('Y-m-d\TH:i', strtotime($ad['start_date']))) ?>" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Fecha de Fin *</label>
                    <input type="datetime-local" name="end_date" class="form-input" value="<?= h(date('Y-m-d\TH:i', strtotime($ad['end_date']))) ?>" required>
                </div>
            </div>
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Audiencia Objetivo</label>
                    <select name="target_audience" class="form-select">
                        <option value="all" <?= $ad['target_audience'] === 'all' ? 'selected' : '' ?>>Todos los usuarios</option>
                        <option value="verified" <?= $ad['target_audience'] === 'verified' ? 'selected' : '' ?>>Solo verificados</option>
                        <option value="new_users" <?= $ad['target_audience'] === 'new_users' ? 'selected' : '' ?>>Usuarios nuevos (últimos 30 días)</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Estado Manual</label>
                    <select name="status" class="form-select">
                        <option value="active" <?= $ad['status'] === 'active' ? 'selected' : '' ?>>Activo</option>
                        <option value="pending" <?= $ad['status'] === 'pending' ? 'selected' : '' ?>>Pendiente</option>
                        <option value="paused" <?= $ad['status'] === 'paused' ? 'selected' : '' ?>>Pausado</option>
                        <option value="expired" <?= $ad['status'] === 'expired' ? 'selected' : '' ?>>Expirado</option>
                    </select>
                    <small style="color: var(--text-muted);">Nota: El sistema actualizará automáticamente el estado según las fechas.</small>
                </div>
            </div>
            
            <!-- Vista previa -->
            <div class="ad-preview">
                <h4 style="margin-bottom: 15px;">Vista previa del anuncio</h4>
                <div id="previewContent">
                    <img src="<?= h(media_url($ad['image_url'])) ?>" alt="Vista previa" style="max-width: 100%; height: 150px; object-fit: cover; border-radius: 6px; margin-bottom: 10px;">
                    <h4 style="margin: 10px 0 5px 0;"><?= h($ad['title']) ?></h4>
                    <p style="color: var(--text-muted); margin-bottom: 5px;"><?= h($ad['description']) ?></p>
                    <small style="color: var(--text-muted);">Patrocinado por: <?= h($ad['advertiser']) ?></small>
                </div>
            </div>
            
            <div class="form-actions">
                <a href="./?r=admin/ads" class="btn btn-outline">Cancelar</a>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Actualizar Anuncio
                </button>
            </div>
        </form>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.querySelector('form');
        const preview = document.getElementById('previewContent');
        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 de upload
        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';
                
                // Actualizar vista previa del anuncio
                updatePreview();
            };
            reader.readAsDataURL(file);
        }
        
        function updatePreview() {
            const title = form.title.value || '<?= h($ad['title']) ?>';
            const description = form.description.value || '<?= h($ad['description']) ?>';
            const advertiser = form.advertiser.value || '<?= h($ad['advertiser']) ?>';
            
            // Usar nueva imagen si está disponible, sino la actual
            let imageSrc = '<?= h($ad['image_url']) ?>';
            if (imagePreview.style.display === 'block') {
                imageSrc = imagePreview.src;
            }
            
            preview.innerHTML = `
                <img src="${imageSrc}" alt="Vista previa" onerror="this.src='https://via.placeholder.com/300x150?text=Imagen+no+disponible'" style="max-width: 100%; height: 150px; 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', updatePreview);
            }
        });
        
        // Validar fechas
        const startDateInput = form.querySelector('input[name="start_date"]');
        const endDateInput = form.querySelector('input[name="end_date"]');
        
        function validateDates() {
            const startDate = new Date(startDateInput.value);
            const endDate = new Date(endDateInput.value);
            const now = new Date();
            
            if (startDate >= endDate) {
                alert('La fecha de fin debe ser posterior a la fecha de inicio.');
                endDateInput.value = '';
                return false;
            }
            
            if (endDate <= now) {
                if (!confirm('La fecha de fin es anterior a la fecha actual. ¿Estás seguro de que quieres crear un anuncio expirado?')) {
                    endDateInput.value = '';
                    return false;
                }
            }
            
            return true;
        }
        
        endDateInput.addEventListener('change', validateDates);
        
        // Validar formulario antes de enviar
        form.addEventListener('submit', function(e) {
            if (!validateDates()) {
                e.preventDefault();
                return false;
            }
            
            // Mostrar confirmación si el anuncio va a expirar pronto
            const endDate = new Date(endDateInput.value);
            const now = new Date();
            const timeDiff = endDate - now;
            const daysDiff = timeDiff / (1000 * 3600 * 24);
            
            if (daysDiff < 1 && daysDiff > 0) {
                if (!confirm('El anuncio expirará en menos de 24 horas. ¿Estás seguro de que quieres continuar?')) {
                    e.preventDefault();
                    return false;
                }
            }
        });
        
        updatePreview();
    });
    </script>
