<?php
include 'sesion.php';
include 'concha.php';
include 'concha_extras.php';

/* =========================
   Sesión / CSRF
========================= */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function csrf_random_hex($length = 32) {
    if (function_exists('random_bytes')) {
        return bin2hex(random_bytes($length));
    }
    if (function_exists('openssl_random_pseudo_bytes')) {
        return bin2hex(openssl_random_pseudo_bytes($length));
    }
    $bytes = '';
    for ($i = 0; $i < $length; $i++) {
        $bytes .= chr(mt_rand(0, 255));
    }
    return bin2hex($bytes);
}

if (empty($_SESSION['csrf_galeria'])) {
    $_SESSION['csrf_galeria'] = csrf_random_hex(32);
}
$csrf = $_SESSION['csrf_galeria'];

/* =========================
   Config
========================= */
$perPage = 12;
$c = isset($_GET['c']) ? (int)$_GET['c'] : 0;
if ($c < 0) $c = 0;

$maxImageBytes = 5 * 1024 * 1024;   // 5MB
$maxVideoBytes = 50 * 1024 * 1024;  // 50MB

/* =========================
   Helpers
========================= */
function h($s) {
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function get_public_base_dir() {
    // panel/galeria_de_medios.php  => raíz pública del sitio
    return dirname(__DIR__);
}

function build_site_base_url($dom) {
    $dom = trim((string)$dom);
    if ($dom !== '') {
        return rtrim($dom, '/');
    }

    $https = (
        (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
        (isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443)
    );

    $scheme = $https ? 'https://' : 'http://';
    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
    return rtrim($scheme . $host, '/');
}

function ensure_upload_dir($baseDir, $folder) {
    $baseDir = rtrim((string)$baseDir, '/');
    $dir = $baseDir . '/' . $folder;

    if (!is_dir($dir)) {
        if (!@mkdir($dir, 0777, true)) {
            return array(false, $dir);
        }
    }

    return array(true, $dir);
}

function detect_mime($tmpPath) {
    $mime = '';

    if (class_exists('finfo')) {
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($tmpPath);
    } elseif (function_exists('mime_content_type')) {
        $mime = mime_content_type($tmpPath);
    }

    return (string)$mime;
}

function insert_galeria_row($conn, $pathRel, $tipo) {
    $descripcion = '';
    $idNota = 0;

    $sql1 = "INSERT INTO galeria_de_medios (`url`,`descripcion`,`tipo`,`ID_nota`) VALUES (?,?,?,?)";
    $stmt = @$conn->prepare($sql1);
    if ($stmt) {
        $stmt->bind_param("sssi", $pathRel, $descripcion, $tipo, $idNota);
        $ok = $stmt->execute();
        $err = $stmt->error;
        $stmt->close();

        if ($ok) {
            return array(true, '');
        }
    }

    $sql2 = "INSERT INTO galeria_de_medios (`URL`,`descripcion`,`tipo`,`ID_nota`) VALUES (?,?,?,?)";
    $stmt2 = @$conn->prepare($sql2);
    if (!$stmt2) {
        return array(false, "Error preparando INSERT: " . $conn->error);
    }

    $stmt2->bind_param("sssi", $pathRel, $descripcion, $tipo, $idNota);
    $ok2 = $stmt2->execute();
    $err2 = $stmt2->error;
    $stmt2->close();

    if (!$ok2) {
        return array(false, "Error ejecutando INSERT: " . $err2);
    }

    return array(true, '');
}

function is_real_upload($tmp) {
    if (!$tmp) return false;

    if (function_exists('is_uploaded_file')) {
        return is_uploaded_file($tmp);
    }

    return file_exists($tmp);
}

/* =========================
   Defaults
========================= */
$nombresitio = isset($nombresitio) ? $nombresitio : '';
$dom = isset($dom) ? $dom : '';
$siteBaseUrl = build_site_base_url($dom);
$uploadBaseDir = get_public_base_dir();

/* =========================
   Upload desde MODAL
========================= */
$status = '';
$uploaded_ok = (isset($_GET['uploaded']) && $_GET['uploaded'] == '1');

if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload_media') {

    $csrfPost = isset($_POST['csrf']) ? (string)$_POST['csrf'] : '';
    if (!$csrfPost || !hash_equals($_SESSION['csrf_galeria'], $csrfPost)) {
        $status = "Token inválido. Reintentá.";
    } else {

        $a = date('Y');
        $m = date('m');
        $carpeta = $m . "-" . $a;

        list($okDir, $dir) = ensure_upload_dir($uploadBaseDir, $carpeta);

        if (!$okDir) {
            $status = "No se pudo crear la carpeta destino: " . h($dir);
        } else {

            if (!isset($_FILES['archivo'])) {
                $status = "No se recibió ningún archivo.";
            } else {

                $file = $_FILES['archivo'];

                if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
                    $status = "Error de subida (código " . (int)(isset($file['error']) ? $file['error'] : 999) . ").";
                } else {

                    $tmp = isset($file['tmp_name']) ? $file['tmp_name'] : '';
                    if (!$tmp || !is_real_upload($tmp)) {
                        $status = "Archivo temporal inválido.";
                    } else {

                        $size = isset($file['size']) ? (int)$file['size'] : 0;
                        if ($size <= 0) {
                            $status = "El archivo está vacío.";
                        } else {

                            $mime = detect_mime($tmp);

                            $allowedImages = array(
                                'image/jpeg' => 'jpg',
                                'image/png'  => 'png',
                                'image/gif'  => 'gif'
                            );

                            $allowedVideos = array(
                                'video/mp4' => 'mp4'
                            );

                            $isImage = isset($allowedImages[$mime]);
                            $isVideo = isset($allowedVideos[$mime]);

                            if (!$isImage && !$isVideo) {
                                $status = "Formato no válido. Solo JPG, PNG, GIF o MP4. MIME detectado: " . h($mime);
                            } else {

                                if ($isImage && $size > $maxImageBytes) {
                                    $status = "Imagen demasiado grande. Máximo " . (int)($maxImageBytes / 1024 / 1024) . "MB.";
                                } elseif ($isVideo && $size > $maxVideoBytes) {
                                    $status = "Video demasiado grande. Máximo " . (int)($maxVideoBytes / 1024 / 1024) . "MB.";
                                } else {

                                    if ($isImage) {
                                        $imgInfo = @getimagesize($tmp);
                                        if (!$imgInfo) {
                                            $status = "La imagen no es válida.";
                                        }
                                    }

                                    if ($status === '') {
                                        $ext = $isImage ? $allowedImages[$mime] : $allowedVideos[$mime];
                                        $tipo = $isImage ? 'img' : 'video';

                                        $prefijo = md5(uniqid((string)mt_rand(), true));
                                        $fileName = $prefijo . '.' . $ext;
                                        $dest = rtrim($dir, '/') . '/' . $fileName;

                                        if (!@move_uploaded_file($tmp, $dest)) {
                                            $status = "No se pudo guardar el archivo en el servidor.";
                                        } else {
                                            @chmod($dest, 0644);

                                            $pathRel = $carpeta . '/' . $fileName;

                                            list($okIns, $errIns) = insert_galeria_row($conn, $pathRel, $tipo);

                                            if (!$okIns) {
                                                @unlink($dest);
                                                $status = $errIns;
                                            } else {
                                                header("Location: galeria_de_medios.php?uploaded=1&c=" . (int)$c);
                                                exit;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

/* =========================
   HTML embed
========================= */
$html_embed = '';
$sql = "SELECT * FROM `html_inicio` LIMIT 1";
$consulta = $conn->query($sql);
if ($consulta) {
    if ($row = $consulta->fetch_assoc()) {
        $html_embed = isset($row["texto"]) ? $row["texto"] : '';
    }
    $consulta->free_result();
}

/* =========================
   Total + paginación
========================= */
$total = 0;
$qTotal = $conn->query("SELECT COUNT(*) AS total FROM `galeria_de_medios`");
if ($qTotal) {
    if ($rT = $qTotal->fetch_assoc()) {
        $total = (int)$rT['total'];
    }
    $qTotal->free_result();
}

$prev = max(0, $c - $perPage);
$next = $c + $perPage;

$hasPrev = ($c > 0);
$hasNext = ($next < $total);

/* =========================
   Datos
========================= */
$datas = array();
$sql65 = "SELECT * FROM `galeria_de_medios` ORDER BY ID DESC LIMIT " . (int)$c . "," . (int)$perPage;
$consulta65 = $conn->query($sql65);
if ($consulta65) {
    while ($row65 = $consulta65->fetch_assoc()) {
        $datas[] = $row65;
    }
    $consulta65->free_result();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="description" content="Panel de Administración">
    <meta name="author" content="<?php echo h($nombresitio); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title><?php echo h($nombresitio); ?> - Galería de Medios</title>

    <link href="https://fonts.googleapis.com/css?family=Montserrat:100,200,300,400,500,600,700,800,900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
    <link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">

    <style>
        :root{
            --azul: #0066FF;
            --fondo: #F4F6FB;
            --card: #FFFFFF;
            --texto: #1E2430;
            --muted: #6B7280;
            --borde: #E6EAF2;
        }

        body{
            background: radial-gradient(1000px 400px at 20% 0%, rgba(0,102,255,.10), transparent 60%),
                        radial-gradient(900px 400px at 80% 20%, rgba(0,102,255,.08), transparent 55%),
                        var(--fondo);
            color: var(--texto);
            font-family: 'Montserrat', sans-serif;
        }

        .container{ max-width: 1200px; }

        .topbar{
            background: #0B1220;
            border-bottom: 1px solid rgba(255,255,255,.08);
            color: #fff;
            padding: 18px 0;
            margin-bottom: 18px;
        }

        .topbar h1{
            font-size: 20px;
            font-weight: 700;
            margin: 0;
            letter-spacing: .2px;
        }

        .topbar small{
            color: rgba(255,255,255,.70);
            font-weight: 500;
        }

        .panel{
            background: var(--card);
            border: 1px solid var(--borde);
            border-radius: 14px;
            box-shadow: 0 8px 26px rgba(16,24,40,.06);
        }

        .section-title{
            font-size: 15px;
            font-weight: 800;
            margin: 0;
        }

        .section-sub{
            font-size: 12px;
            color: var(--muted);
            margin: 6px 0 0 0;
            font-weight: 500;
        }

        .btn-primary{
            background-color: var(--azul);
            border-color: var(--azul);
            font-weight: 700;
        }

        .btn-outline-primary{
            border-color: rgba(0,102,255,.35);
            color: var(--azul);
            font-weight: 700;
        }

        .btn-outline-primary:hover{
            background: var(--azul);
            border-color: var(--azul);
            color: #fff;
        }

        .chip{
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 6px 10px;
            border-radius: 999px;
            border: 1px solid var(--borde);
            background: #fff;
            font-size: 12px;
            font-weight: 700;
            color: #111827;
        }

        .chip .dot{
            width: 9px;
            height: 9px;
            border-radius: 999px;
            background: var(--azul);
            opacity: .9;
        }

        .help-box{
            background: linear-gradient(180deg, rgba(0,102,255,.06), rgba(0,102,255,.02));
            border: 1px dashed rgba(0,102,255,.25);
            border-radius: 14px;
            padding: 14px;
        }

        .help-box ol{ margin: 10px 0 0 18px; }

        .help-box li{
            font-size: 13px;
            color: #2b3445;
            margin-bottom: 6px;
            font-weight: 500;
        }

        .carousel{ background: transparent; }
        .carousel-cell{ width: 340px; margin-right: 14px; }

        @media (max-width: 575px){
            .carousel-cell{ width: 88%; }
        }

        .flickity-button{
            background: #fff;
            border: 1px solid var(--borde);
        }

        .flickity-prev-next-button{
            width: 40px;
            height: 40px;
            border-radius: 999px;
            box-shadow: 0 8px 22px rgba(16,24,40,.10);
        }

        .flickity-button-icon{ fill: #111827; }
        .flickity-page-dots{ display:none; }

        .media-card{
            background: var(--card);
            border: 1px solid var(--borde);
            border-radius: 14px;
            overflow: hidden;
            box-shadow: 0 10px 26px rgba(16,24,40,.06);
            transition: transform .12s ease, box-shadow .12s ease;
        }

        .media-card:hover{
            transform: translateY(-2px);
            box-shadow: 0 16px 34px rgba(16,24,40,.10);
        }

        .media-card .head{
            padding: 12px 14px;
            border-bottom: 1px solid var(--borde);
            display:flex;
            align-items:center;
            justify-content:space-between;
        }

        .media-card .head .type{
            font-size: 12px;
            font-weight: 800;
            color:#111827;
            letter-spacing:.2px;
        }

        .badge-soft{
            background: rgba(0,102,255,.10);
            border: 1px solid rgba(0,102,255,.20);
            color: var(--azul);
            font-weight: 800;
            font-size: 11px;
            padding: 6px 10px;
            border-radius: 999px;
        }

        .media-card .body{ padding: 12px 14px 14px 14px; }

        .preview-img{
            width: 100%;
            height: 210px;
            object-fit: cover;
            background: #f1f3f6;
            border-radius: 12px;
            border: 1px solid var(--borde);
            display:block;
        }

        .preview-video{
            width: 100%;
            height: 210px;
            background: #000;
            border-radius: 12px;
            border: 1px solid var(--borde);
            object-fit: cover;
            display:block;
        }

        .ratio-16x9{
            position: relative;
            padding-bottom: 56.25%;
            height: 0;
            overflow: hidden;
            border-radius: 12px;
            border: 1px solid var(--borde);
            background: #000;
        }

        .ratio-16x9 iframe{
            position: absolute;
            top:0;
            left:0;
            width:100%;
            height:100%;
            border:0;
        }

        .form-note{
            font-size: 11px;
            color: var(--muted);
            font-weight: 600;
            margin: 8px 0 0 0;
        }

        .input-group .form-control{
            font-size: 12px;
            font-weight: 600;
            border-color: var(--borde);
        }

        .btn-copy{
            font-weight: 800;
            font-size: 12px;
            border-color: rgba(0,102,255,.25);
            color: var(--azul);
            background: #fff;
        }

        .btn-copy:hover{
            color:#fff;
            background: var(--azul);
            border-color: var(--azul);
        }

        .footer-nav{ gap: 10px; }
        .muted{ color: var(--muted); font-weight: 600; }

        .modal-content{
            border: 0;
            box-shadow: 0 20px 60px rgba(0,0,0,.18);
        }
    </style>

    <script>
        function copyToClipboard(text, btn){
            if (!text) return;

            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(function(){
                    if(btn){
                        var old = btn.innerText;
                        btn.innerText = 'Copiado';
                        btn.disabled = true;
                        setTimeout(function(){
                            btn.innerText = old;
                            btn.disabled = false;
                        }, 900);
                    }
                }).catch(function(){
                    fallbackCopy(text, btn);
                });
            } else {
                fallbackCopy(text, btn);
            }
        }

        function fallbackCopy(text, btn){
            var aux = document.createElement("textarea");
            aux.value = text;
            aux.setAttribute("readonly", "");
            aux.style.position = "absolute";
            aux.style.left = "-9999px";
            document.body.appendChild(aux);
            aux.select();
            document.execCommand("copy");
            document.body.removeChild(aux);

            if(btn){
                var old = btn.innerText;
                btn.innerText = 'Copiado';
                btn.disabled = true;
                setTimeout(function(){
                    btn.innerText = old;
                    btn.disabled = false;
                }, 900);
            }
        }

        document.addEventListener('click', function(e){
            var el = e.target;
            if (el && el.matches('[data-copy]')) {
                var targetId = el.getAttribute('data-copy');
                var input = document.getElementById(targetId);
                if (input) {
                    copyToClipboard(input.value, el);
                }
            }
        });
    </script>
</head>
<body>

<div class="topbar">
    <div class="container">
        <div class="d-flex align-items-center justify-content-between flex-wrap" style="gap:12px;">
            <div>
                <h1>Galería de Medios</h1>
                <small>Imágenes, videos (MP4), YouTube e Instagram</small>
            </div>
            <div class="d-flex align-items-center flex-wrap" style="gap:10px;">
                <span class="chip"><span class="dot"></span> Total: <?php echo (int)$total; ?></span>

                <button class="btn btn-primary" data-toggle="modal" data-target="#modalUpload">
                    Subir medios
                </button>

                <button class="btn btn-outline-primary" onclick="window.location.reload();">
                    Actualizar
                </button>
            </div>
        </div>
    </div>
</div>

<div class="container pb-4">

    <?php if ($uploaded_ok) { ?>
        <div class="alert alert-success">Cargado correctamente.</div>
    <?php } ?>

    <?php if (!empty($status)) { ?>
        <div class="alert alert-danger"><?php echo $status; ?></div>
    <?php } ?>

    <div class="panel p-3 p-md-4 mb-3">
        <div class="d-flex align-items-center justify-content-between flex-wrap" style="gap:12px;">
            <div>
                <p class="section-title">Cargar</p>
                <p class="section-sub">También podés usar los módulos externos si ya los tenías</p>
            </div>
            <div class="d-flex flex-wrap" style="gap:10px;">
                <a class="btn btn-outline-primary" href="galeria_de_medios_youtube.php">Video de YouTube</a>
                <a class="btn btn-outline-primary" href="galeria_de_medios_instagram.php">Post de Instagram</a>
            </div>
        </div>
    </div>

    <div class="help-box mb-3">
        <div class="d-flex align-items-center justify-content-between flex-wrap" style="gap:12px;">
            <div>
                <p class="section-title">Cómo usar la galería</p>
                <p class="section-sub">Copiás el código y lo pegás donde quieras en el cuerpo de la nota</p>
            </div>
            <div class="muted">Usá los botones “Copiar” de cada tarjeta</div>
        </div>
        <ol class="mb-0">
            <li>Hacé click en “Copiar”.</li>
            <li>Pegá (Ctrl + V) en el cuerpo de la nota, en el lugar que quieras.</li>
        </ol>
    </div>

    <div class="panel p-3 p-md-4">
        <div class="d-flex align-items-center justify-content-between flex-wrap" style="gap:12px;">
            <div>
                <p class="section-title mb-1">Cargados en la galería</p>
                <p class="section-sub mb-0">
                    Mostrando <?php echo (int)count($datas); ?> de <?php echo (int)$total; ?>
                    (desde <?php echo $total > 0 ? (int)($c + 1) : 0; ?>)
                </p>
            </div>
            <div class="muted">Deslizá o usá las flechas</div>
        </div>

        <hr style="border-color:var(--borde);">

        <?php if (count($datas) === 0) { ?>
            <div class="text-center py-5">
                <h5 style="font-weight:800;">No hay medios cargados</h5>
                <p class="muted mb-0">Subí una imagen o un video MP4 para que aparezca acá.</p>
            </div>
        <?php } else { ?>

            <div class="carousel"
                 data-flickity='{
                    "cellAlign": "left",
                    "wrapAround": false,
                    "imagesLoaded": true,
                    "draggable": true,
                    "pageDots": false,
                    "contain": true
                 }'>

                <?php
                $n = 0;
                foreach ($datas as $row65) {
                    $n++;
                    $ID_foto = isset($row65["ID"]) ? (int)$row65["ID"] : 0;
                    $url = isset($row65["url"]) ? (string)$row65["url"] : (isset($row65["URL"]) ? (string)$row65["URL"] : '');
                    $tipo = isset($row65["tipo"]) ? (string)$row65["tipo"] : '';

                    $url = ltrim($url, '/');
                    $full = $siteBaseUrl . '/' . $url;

                    $bb_img = "[img]" . $full . "[/img]";
                    $bb_video = "[video]" . $full . "[/video]";
                    $bb_youtube = "[youtube]" . $url . "[/youtube]";
                    $bb_ig = "[ig]" . $url . "[/ig]";
                ?>

                <?php if ($tipo === 'img') { ?>
                    <div class="carousel-cell">
                        <div class="media-card">
                            <div class="head">
                                <div class="type">Imagen</div>
                                <span class="badge-soft">IMG</span>
                            </div>
                            <div class="body">
                                <img class="preview-img" src="<?php echo h($full); ?>" alt="Imagen" loading="lazy">

                                <div class="mt-3">
                                    <div class="input-group input-group-sm mb-2">
                                        <input id="bbcode_<?php echo $n; ?>" type="text" class="form-control" value="<?php echo h($bb_img); ?>" readonly>
                                        <div class="input-group-append">
                                            <button class="btn btn-copy" type="button" data-copy="bbcode_<?php echo $n; ?>">Copiar para la web</button>
                                        </div>
                                    </div>

                                    <div class="input-group input-group-sm">
                                        <input id="url_<?php echo $n; ?>" type="text" class="form-control" value="<?php echo h($full); ?>" readonly>
                                        <div class="input-group-append">
                                            <button class="btn btn-copy" type="button" data-copy="url_<?php echo $n; ?>">Copiar para Newsletter</button>
                                        </div>
                                    </div>

                                    <p class="form-note">ID: <?php echo $ID_foto; ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php } ?>

                <?php if ($tipo === 'video' || $tipo === 'mp4') { ?>
                    <div class="carousel-cell">
                        <div class="media-card">
                            <div class="head">
                                <div class="type">Video</div>
                                <span class="badge-soft">MP4</span>
                            </div>
                            <div class="body">
                                <video class="preview-video" controls preload="metadata">
                                    <source src="<?php echo h($full); ?>" type="video/mp4">
                                </video>

                                <div class="mt-3">
                                    <div class="input-group input-group-sm mb-2">
                                        <input id="bbcode_<?php echo $n; ?>" type="text" class="form-control" value="<?php echo h($bb_video); ?>" readonly>
                                        <div class="input-group-append">
                                            <button class="btn btn-copy" type="button" data-copy="bbcode_<?php echo $n; ?>">Copiar</button>
                                        </div>
                                    </div>

                                    <div class="input-group input-group-sm">
                                        <input id="url_<?php echo $n; ?>" type="text" class="form-control" value="<?php echo h($full); ?>" readonly>
                                        <div class="input-group-append">
                                            <button class="btn btn-copy" type="button" data-copy="url_<?php echo $n; ?>">Copiar link</button>
                                        </div>
                                    </div>

                                    <p class="form-note">ID: <?php echo $ID_foto; ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php } ?>

                <?php if ($tipo === 'youtube') { ?>
                    <div class="carousel-cell">
                        <div class="media-card">
                            <div class="head">
                                <div class="type">YouTube</div>
                                <span class="badge-soft">YT</span>
                            </div>
                            <div class="body">
                                <div class="ratio-16x9">
                                    <iframe
                                        src="https://www.youtube.com/embed/<?php echo h($url); ?>"
                                        allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
                                        allowfullscreen
                                        loading="lazy"
                                        referrerpolicy="strict-origin-when-cross-origin"
                                        title="YouTube"></iframe>
                                </div>

                                <div class="mt-3">
                                    <div class="input-group input-group-sm">
                                        <input id="bbcode_<?php echo $n; ?>" type="text" class="form-control" value="<?php echo h($bb_youtube); ?>" readonly>
                                        <div class="input-group-append">
                                            <button class="btn btn-copy" type="button" data-copy="bbcode_<?php echo $n; ?>">Copiar</button>
                                        </div>
                                    </div>

                                    <p class="form-note">ID: <?php echo $ID_foto; ?> · Video ID: <?php echo h($url); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php } ?>

                <?php if ($tipo === 'ig') { ?>
                    <div class="carousel-cell">
                        <div class="media-card">
                            <div class="head">
                                <div class="type">Instagram</div>
                                <span class="badge-soft">IG</span>
                            </div>
                            <div class="body">
                                <div style="border-radius:12px; overflow:hidden; border:1px solid var(--borde); background:#fff;">
                                    <iframe
                                        style="width:100%;height:520px;"
                                        src="https://www.instagram.com/p/<?php echo h($url); ?>/embed/"
                                        frameborder="0"
                                        allowfullscreen
                                        loading="lazy"
                                        referrerpolicy="strict-origin-when-cross-origin"
                                        title="Instagram"></iframe>
                                </div>

                                <div class="mt-3">
                                    <div class="input-group input-group-sm">
                                        <input id="bbcode_<?php echo $n; ?>" type="text" class="form-control" value="<?php echo h($bb_ig); ?>" readonly>
                                        <div class="input-group-append">
                                            <button class="btn btn-copy" type="button" data-copy="bbcode_<?php echo $n; ?>">Copiar</button>
                                        </div>
                                    </div>

                                    <p class="form-note">ID: <?php echo $ID_foto; ?> · Post: <?php echo h($url); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php } ?>

                <?php } ?>
            </div>

            <div class="d-flex align-items-center justify-content-center mt-4 footer-nav flex-wrap">
                <a class="btn btn-outline-primary <?php echo $hasPrev ? '' : 'disabled'; ?>"
                   href="galeria_de_medios.php?c=<?php echo (int)$prev; ?>">Anterior</a>

                <span class="muted">
                    Página: <?php echo (int)floor($c / $perPage) + 1; ?> / <?php echo (int)max(1, ceil($total / $perPage)); ?>
                </span>

                <a class="btn btn-outline-primary <?php echo $hasNext ? '' : 'disabled'; ?>"
                   href="galeria_de_medios.php?c=<?php echo (int)$next; ?>">Siguiente</a>
            </div>

        <?php } ?>
    </div>

</div>

<div class="modal fade" id="modalUpload" tabindex="-1" role="dialog" aria-labelledby="modalUploadLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content" style="border-radius:14px; overflow:hidden;">
            <div class="modal-header" style="background:#0B1220; color:#fff;">
                <h5 class="modal-title" id="modalUploadLabel" style="font-weight:800;">Subir medios</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar" style="color:#fff; opacity:1;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <form action="galeria_de_medios.php?c=<?php echo (int)$c; ?>" method="post" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" name="action" value="upload_media">
                    <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>">

                    <div class="form-group">
                        <label style="font-weight:800;">Archivo</label>
                        <input
                            type="file"
                            name="archivo"
                            class="form-control"
                            required
                            accept="image/jpeg,image/png,image/gif,video/mp4">
                        <small class="form-text text-muted" style="font-weight:600;">
                            Permitidos: JPG, PNG, GIF, MP4. Imágenes hasta <?php echo (int)($maxImageBytes/1024/1024); ?>MB. Videos hasta <?php echo (int)($maxVideoBytes/1024/1024); ?>MB.
                        </small>
                    </div>

                    <div class="alert alert-secondary" style="font-size:12px; font-weight:600;">
                        Se sube directo a la raíz pública del sitio y la vista previa usa la imagen real, sin timthumb.
                    </div>
                </div>

                <div class="modal-footer" style="border-top:1px solid #e9ecef;">
                    <button type="button" class="btn btn-outline-primary" data-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Subir</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/08c7c8fb48.js" crossorigin="anonymous"></script>

</body>
</html>