<?php
/**
 * admin/preview.php — Vista previa del aviso (cualquier estado).
 * Usa los mismos includes del sitio público para una preview fiel.
 */
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/../config/conn.php';
av_require_login();

$id = (int)($_GET['id'] ?? 0);
if (!$id) { header('Location: index.php'); exit; }

// Cargar aviso (sin filtro de estado — admin puede ver cualquiera)
$s = $conn->prepare("SELECT * FROM av_avisos WHERE id=? LIMIT 1");
$s->bind_param('i', $id);
$s->execute();
$aviso = $s->get_result()->fetch_assoc();
$s->close();

if (!$aviso) { header('Location: index.php'); exit; }

// Cargar bloques
$sb = $conn->prepare("SELECT * FROM av_aviso_bloques WHERE aviso_id=? ORDER BY orden ASC");
$sb->bind_param('i', $id);
$sb->execute();
$bloques = $sb->get_result()->fetch_all(MYSQLI_ASSOC);
$sb->close();

// Preparar variables para banner.php
$page_title  = $aviso['titulo'];
$meta_desc   = $aviso['resumen'] ?? $aviso['titulo'];
$current_page = '';

require_once __DIR__ . '/../includes/banner.php';   // define $base
require_once __DIR__ . '/../includes/navbar.php';

// ── Helpers de renderizado ───────────────────────────────────

function render_bloque(array $b, string $base): string
{
    $out = '';
    switch ($b['tipo']) {
        case 'texto':
            $out = '<div class="doc-prose">' . $b['contenido'] . '</div>';
            break;
        case 'imagen':
            $out = '<figure class="av-pub-figure">'
                 . '<img src="' . h($base . $b['contenido']) . '" alt="' . h($b['nombre_archivo'] ?? '') . '" loading="lazy">'
                 . '</figure>';
            break;
        case 'video':
            $out = render_video($b['contenido'] ?? '', $base);
            break;
        case 'pdf':
        case 'excel':
        case 'archivo':
        default:
            $out = render_archivo($b, $base);
            break;
    }
    return $out;
}

function render_archivo(array $b, string $base): string
{
    $relativePath = (string)($b['contenido'] ?? '');
    $fileUrl = $base . $relativePath;
    $safeUrl = htmlspecialchars($fileUrl, ENT_QUOTES);
    $nombre = (string)($b['nombre_archivo'] ?? 'Archivo adjunto');
    $safeNombre = htmlspecialchars($nombre, ENT_QUOTES);

    $dbMime = strtolower((string)($b['mime_type'] ?? ''));
    $ext = strtolower(pathinfo($nombre, PATHINFO_EXTENSION));
    if ($ext === '') {
        $ext = strtolower(pathinfo($relativePath, PATHINFO_EXTENSION));
    }

    $localPath = local_file_from_relative($relativePath);
    $diskMime = '';
    if ($localPath && is_file($localPath)) {
        $diskExt = strtolower((string)pathinfo($localPath, PATHINFO_EXTENSION));
        if ($diskExt !== '') { $ext = $diskExt; }
        if (class_exists('finfo')) {
            $finfo = new finfo(FILEINFO_MIME_TYPE);
            $diskMime = strtolower((string)$finfo->file($localPath));
        }
    }
    $mime = $diskMime !== '' ? $diskMime : $dbMime;

    $isPdf   = $ext === 'pdf' || strpos($mime, 'application/pdf') === 0;
    $isImage = in_array($ext, ['jpg','jpeg','png','gif','webp','bmp','svg','avif'], true)
               || strpos($mime, 'image/') === 0;
    $isWord  = in_array($ext, ['doc','docx','odt','rtf','docm'], true)
               || in_array($mime, [
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'application/vnd.ms-word.document.macroenabled.12',
                    'application/vnd.oasis.opendocument.text',
                    'application/rtf',
                  ], true);
    $isPpt   = in_array($ext, ['ppt','pptx','odp','pps','ppsx','pptm'], true)
               || in_array($mime, [
                    'application/vnd.ms-powerpoint',
                    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                    'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
                    'application/vnd.ms-powerpoint.presentation.macroenabled.12',
                    'application/vnd.oasis.opendocument.presentation',
                  ], true);

    $badgeClass = 'av-pub-file';
    $icon = '📁';
    if ($isImage)     { $badgeClass .= ' av-pub-file--img';  $icon = '🖼️'; }
    elseif ($isPdf)   { $badgeClass .= ' av-pub-file--pdf';  $icon = '📄'; }
    elseif ($isWord)  { $badgeClass .= ' av-pub-file--word'; $icon = '📝'; }
    elseif ($isPpt)   { $badgeClass .= ' av-pub-file--ppt';  $icon = '📽️'; }

    $html = '<div class="' . $badgeClass . '">'
          . '<span class="av-pub-file-icon">' . $icon . '</span>'
          . '<div><p class="av-pub-file-name">' . $safeNombre . '</p>';

    if ($isImage) {
        $html .= '<div class="av-pub-file-preview">'
              . '<img class="av-pub-file-preview-img" src="' . $safeUrl . '" alt="' . $safeNombre . '" loading="lazy">'
              . '</div>';
    } elseif ($isPdf) {
        $html .= '<div class="av-pub-file-preview">'
              . '<iframe src="' . $safeUrl . '#view=FitH" loading="lazy" title="Vista previa PDF"></iframe>'
              . '</div>';
    } elseif ($isWord || $isPpt) {
        $officeViewer = 'https://view.officeapps.live.com/op/embed.aspx?src=' . rawurlencode(absolute_url($fileUrl));
        $safeOfficeViewer = htmlspecialchars($officeViewer, ENT_QUOTES);
        $html .= '<div class="av-pub-file-preview">'
              . '<iframe src="' . $safeOfficeViewer . '" loading="lazy" title="Vista previa documento"></iframe>'
              . '</div>';
    } else {
        $html .= '<div class="av-pub-file-preview">'
              . '<iframe src="' . $safeUrl . '" loading="lazy" title="Vista previa archivo"></iframe>'
              . '</div>';
    }

    $html .= '<a class="av-pub-file-link" href="' . $safeUrl . '" target="_blank" rel="noopener">Abrir / Descargar</a>';
    $html .= '</div></div>';
    return $html;
}

function absolute_url(string $path): string
{
    if (preg_match('#^https?://#i', $path)) { return $path; }
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    if (strpos($path, '/') === 0) { return $scheme . '://' . $host . $path; }
    return $scheme . '://' . $host . '/' . ltrim($path, '/');
}

function local_file_from_relative(string $relativePath): string
{
    $relativePath = ltrim(str_replace('\\', '/', $relativePath), '/');
    if ($relativePath === '') return '';
    $root = realpath(__DIR__ . '/..');
    if ($root === false) return '';
    return $root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relativePath);
}

function render_video(string $contenido, string $base): string
{
    if (preg_match('/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/))([a-zA-Z0-9_\-]{11})/', $contenido, $m)) {
        $vid = htmlspecialchars($m[1], ENT_QUOTES);
        return '<div class="av-pub-embed"><iframe src="https://www.youtube.com/embed/' . $vid . '" allowfullscreen loading="lazy" title="Video"></iframe></div>';
    }
    if (preg_match('/vimeo\.com\/(\d+)/', $contenido, $m)) {
        $vid = (int)$m[1];
        return '<div class="av-pub-embed"><iframe src="https://player.vimeo.com/video/' . $vid . '" allowfullscreen loading="lazy" title="Video"></iframe></div>';
    }
    // Archivo de video local
    return '<video controls class="av-pub-video"><source src="' . h($base . $contenido) . '"><p>Tu navegador no soporta la reproducción de video.</p></video>';
}
?>

<!-- ── AVISO PREVIEW BANNER ───────────────────────────── -->
<div
    style="background:#fff3cd;border-bottom:3px solid #ffc107;padding:.5rem 1.5rem;font-size:.82rem;display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap">
    <span>⚠️ <strong>Vista previa — </strong>Estado actual:
        <strong><?= h($aviso['estado']) ?></strong>
        <?= $aviso['estado'] !== 'publicado' ? ' (no visible para visitantes)' : '' ?>
    </span>
    <span style="display:flex;gap:.5rem">
        <a href="editar.php?id=<?= $aviso['id'] ?>" style="color:#856404;font-weight:600">✏️ Editar</a>
        <a href="index.php" style="color:#856404;font-weight:600">← Panel</a>
    </span>
</div>

<!-- ── CONTENIDO DEL AVISO ───────────────────────────── -->
<div class="doc-shell">
    <article class="doc-paper">

        <!-- Cabecera -->
        <header class="doc-header">
            <div class="doc-kicker">Aviso institucional</div>
            <h1 style="font-family:var(--font-head);font-size:clamp(1.4rem,3vw,2rem);font-weight:700;
                 color:var(--c-primary);text-transform:uppercase;margin:.4rem 0 .6rem">
                <?= h($aviso['titulo']) ?>
            </h1>
            <div class="doc-meta">
                <div class="doc-meta-card">
                    <span class="doc-meta-label">Fecha</span>
                    <span class="doc-meta-value"><?= fecha_es($aviso['fecha_publicacion']) ?></span>
                </div>
            </div>
        </header>

        <!-- Banner -->
        <?php if ($aviso['banner_path']): ?>
        <div class="av-pub-banner">
            <img src="<?= h($base . $aviso['banner_path']) ?>" alt="<?= h($aviso['banner_alt'] ?? $aviso['titulo']) ?>"
                loading="lazy">
        </div>
        <?php endif; ?>

        <!-- Bloques de contenido -->
        <div class="doc-body">
            <?php if (empty($bloques)): ?>
            <p style="color:var(--c-muted);text-align:center;padding:2rem 0">
                (Este aviso aún no tiene contenido. Agrega bloques desde el editor.)
            </p>
            <?php else: ?>
            <?php foreach ($bloques as $bloque): ?>
            <div class="av-pub-bloque">
                <?= render_bloque($bloque, $base) ?>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>

    </article>
</div>

<style>
/* Estilos específicos de la vista del aviso público */
.av-pub-banner {
    margin: 0 0 1.5rem;
    border-radius: 6px;
    overflow: hidden;
}

.av-pub-banner img {
    width: 100%;
    max-height: 380px;
    object-fit: cover;
    display: block;
}

.av-pub-bloque {
    margin-bottom: 1.5rem;
}

.doc-prose {
    line-height: 1.7;
    color: var(--c-text);
}

.doc-prose p {
    margin-bottom: .8rem;
}

.doc-prose h2,
.doc-prose h3 {
    font-family: var(--font-head);
    color: var(--c-primary);
    margin: 1.2rem 0 .5rem;
    text-transform: uppercase;
}

.doc-prose ul,
.doc-prose ol {
    margin: .6rem 0 .8rem 1.4rem;
}

.doc-prose li {
    margin-bottom: .3rem;
}

.doc-prose a {
    color: var(--c-accent-dk);
}

.av-pub-figure {
    margin: 0;
    text-align: center;
}

.av-pub-figure img {
    max-width: 100%;
    border-radius: 6px;
    border: 1px solid var(--c-border);
    display: inline-block;
}

.av-pub-embed {
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
    border-radius: 8px;
}

.av-pub-embed iframe {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    border: 0;
}

.av-pub-video {
    width: 100%;
    border-radius: 8px;
}

.av-pub-file {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: .9rem 1.2rem;
    border: 1px solid var(--c-border);
    border-radius: 8px;
    background: #fafbff;
}

.av-pub-file--pdf {
    border-left: 4px solid #dc3545;
}

.av-pub-file--excel {
    border-left: 4px solid #198754;
}

.av-pub-file--img {
    border-left: 4px solid #6f42c1;
}

.av-pub-file--word {
    border-left: 4px solid #0d6efd;
}

.av-pub-file--ppt {
    border-left: 4px solid #fd7e14;
}

.av-pub-file-icon {
    font-size: 1.8rem;
    flex-shrink: 0;
}

.av-pub-file-name {
    font-weight: 600;
    color: var(--c-text);
    margin-bottom: .2rem;
}

.av-pub-file-link {
    font-size: .82rem;
    font-weight: 700;
    color: var(--c-primary);
}

.av-pub-file-link:hover {
    color: var(--c-accent-dk);
}

.av-pub-file-preview {
    margin: .55rem 0 .5rem;
    border: 1px solid var(--c-border);
    border-radius: 8px;
    overflow: hidden;
    background: #fff;
}

.av-pub-file-preview iframe {
    width: 100%;
    min-height: 560px;
    border: 0;
    display: block;
}

.av-pub-file-preview-img {
    display: block;
    width: 100%;
    height: auto;
    max-height: 560px;
    object-fit: contain;
    background: #fff;
}

@media (max-width: 768px) {
    .av-pub-file-preview iframe {
        min-height: 420px;
    }

    .av-pub-file-preview-img {
        max-height: 420px;
    }
}
</style>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>