<?php
// publis.php (PHP 8.2)
// Layout tipo tu dibujo (2 columnas de notas + sidebar derecho)
// - Solo ADMIN (panel/sesion.php)
// - Cada nota tiene su "slot" = 10000004 + posicion (pos 1 => 10000005; pos 4 => 10000008)
// - Botón "Poner publi acá" abre modal con iframe que lista publicidades_gif
// - En el iframe, al tocar "Colocar esta" asigna publicidades_gif.lugar = slot (y libera el slot antes)

require_once __DIR__ . '/panel/sesion.php';
require_once __DIR__ . '/url_amigable.php';
require_once __DIR__ . '/concha.php';

// Compat: algunos concha.php definen $con en vez de $conn
if (!isset($conn) || !($conn instanceof mysqli)) {
    if (isset($con) && ($con instanceof mysqli)) {
        $conn = $con;
    }
}
if (!isset($conn) || !($conn instanceof mysqli)) {
    http_response_code(500);
    exit('Error: concha.php debe definir $conn (mysqli) o $con (mysqli).');
}

$conn->set_charset('utf8mb4');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (empty($_SESSION['csrf_publis'])) {
    $_SESSION['csrf_publis'] = bin2hex(random_bytes(16));
}
$CSRF = $_SESSION['csrf_publis'];

function e(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
function txt(string $s): string {
    // Para que si viene en entidades tipo m&#225; se vea "má"
    $d = html_entity_decode($s, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    return htmlspecialchars($d, ENT_QUOTES, 'UTF-8');
}
function mb_cut(string $s, int $n): string {
    $d = html_entity_decode($s, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $d = trim(preg_replace('~\s+~u', ' ', strip_tags($d)));
    if ($d === '') return '';
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        if (mb_strlen($d, 'UTF-8') <= $n) return $d;
        return mb_substr($d, 0, $n, 'UTF-8') . '…';
    }
    if (strlen($d) <= $n) return $d;
    return substr($d, 0, $n) . '...';
}
function is_video_file(string $file): bool {
    $file = strtolower(trim($file));
    return (substr($file, -4) === '.mp4' || substr($file, -5) === '.webm' || substr($file, -4) === '.mov');
}
function current_base_dom(): string {
    $d = '';
    if (isset($GLOBALS['dom33']) && is_string($GLOBALS['dom33']) && $GLOBALS['dom33'] !== '') $d = $GLOBALS['dom33'];
    elseif (isset($GLOBALS['dom']) && is_string($GLOBALS['dom']) && $GLOBALS['dom'] !== '') $d = $GLOBALS['dom'];
    else {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $d = $scheme . '://' . $host;
    }
    $d = str_replace('http://', 'https://', $d);
    return rtrim($d, '/');
}
function build_media_url(string $dom, string $carpeta, string $file): string {
    $file = trim($file);
    $carpeta = trim($carpeta);

    if ($file === '') return '';
    if (preg_match('~^https?://~i', $file)) return $file;

    $dom = str_replace('http://', 'https://', $dom);
    $dom = rtrim($dom, '/');

    $carpeta = trim($carpeta, '/');
    if ($carpeta === '') return $dom . '/' . ltrim($file, '/');
    return $dom . '/' . $carpeta . '/' . ltrim($file, '/');
}

$DOM_BASE = current_base_dom();

/**
 * IFRAME: listado de publicidades_gif + asignación
 * URL: publis.php?iframe=1&slot=10000008
 */
if (isset($_GET['iframe']) && $_GET['iframe'] == '1') {

    $slot = (int)($_GET['slot'] ?? 0);
    if ($slot < 10000001) { // pos 1 => 10000005
        http_response_code(400);
        exit('Slot inválido.');
    }

    // Asignar
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_publi_id'])) {
        $csrf = (string)($_POST['csrf'] ?? '');
        if (!hash_equals($CSRF, $csrf)) {
            http_response_code(403);
            exit('CSRF inválido.');
        }

        $publiId = (int)$_POST['assign_publi_id'];
        if ($publiId <= 0) {
            http_response_code(400);
            exit('ID de publicidad inválido.');
        }

        $conn->begin_transaction();
        try {
            // libero el slot (si alguien ya estaba)
            $stmt = $conn->prepare("UPDATE publicidades_gif SET lugar = 0 WHERE lugar = ?");
            $stmt->bind_param("i", $slot);
            $stmt->execute();
            $stmt->close();

            // asigno
            $stmt = $conn->prepare("UPDATE publicidades_gif SET lugar = ? WHERE ID = ? LIMIT 1");
            $stmt->bind_param("ii", $slot, $publiId);
            $stmt->execute();
            $stmt->close();

            $conn->commit();
        } catch (Throwable $t) {
            $conn->rollback();
            http_response_code(500);
            exit('Error al asignar publicidad: ' . e($t->getMessage()));
        }

        ?>
        <!doctype html>
        <html lang="es">
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Asignada</title>
        </head>
        <body style="font-family: Arial, sans-serif;">
            <div style="padding:12px;">Listo. Asignada al lugar <?php echo (int)$slot; ?>.</div>
            <script>
                try {
                    if (window.parent) {
                        if (window.parent.$) window.parent.$('#publiModal').modal('hide');
                        window.parent.location.reload();
                    }
                } catch (e) {}
            </script>
        </body>
        </html>
        <?php
        exit;
    }

    // Listado
    $q = trim((string)($_GET['q'] ?? ''));
    $page = max(1, (int)($_GET['p'] ?? 1));
    $perPage = 18;
    $offset = ($page - 1) * $perPage;

    $where = "1=1";
    $params = [];
    $types = "";

    if ($q !== '') {
        $where = "(CAST(ID AS CHAR) = ? OR CAST(lugar AS CHAR) = ? OR img LIKE ? OR url LIKE ?)";
        $qLike = '%' . $q . '%';
        $params = [$q, $q, $qLike, $qLike];
        $types = "ssss";
    }

    // Count
    $total = 0;
    if ($q === '') {
        $res = $conn->query("SELECT COUNT(*) AS c FROM publicidades_gif");
        if ($res && ($row = $res->fetch_assoc())) $total = (int)$row['c'];
        if ($res) $res->free();
    } else {
        $stmt = $conn->prepare("SELECT COUNT(*) AS c FROM publicidades_gif WHERE $where");
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res && ($row = $res->fetch_assoc())) $total = (int)$row['c'];
        $stmt->close();
    }

    $pages = max(1, (int)ceil($total / $perPage));

    // Rows
    $rows = [];
    if ($q === '') {
        $stmt = $conn->prepare("SELECT ID, carpetafoto, img, url, lugar FROM publicidades_gif ORDER BY ID DESC LIMIT ?, ?");
        $stmt->bind_param("ii", $offset, $perPage);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($res && ($r = $res->fetch_assoc())) $rows[] = $r;
        $stmt->close();
    } else {
        $stmt = $conn->prepare("SELECT ID, carpetafoto, img, url, lugar FROM publicidades_gif WHERE $where ORDER BY ID DESC LIMIT ?, ?");
        $params2 = $params;
        $params2[] = $offset;
        $params2[] = $perPage;
        $types2 = $types . "ii";
        $stmt->bind_param($types2, ...$params2);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($res && ($r = $res->fetch_assoc())) $rows[] = $r;
        $stmt->close();
    }

    ?>
    <!doctype html>
    <html lang="es">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Elegir publicidad</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
              integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
              crossorigin="anonymous">
        <style>
            body { background:#f7f7f7; }
            .thumb { width: 180px; max-width: 100%; border-radius: 6px; }
            .table td, .table th { vertical-align: middle; }
            .badge-slot { font-size: 13px; }
        </style>
    </head>
    <body>
    <div class="container-fluid py-3">

        <div class="d-flex align-items-center justify-content-between mb-2">
            <div>
                <h5 class="m-0">Elegir publicidad</h5>
                <div class="text-muted" style="font-size:13px;">
                    Asignando al lugar: <span class="badge badge-primary badge-slot"><?php echo (int)$slot; ?></span>
                </div>
            </div>
            <div>
                <a class="btn btn-sm btn-outline-secondary" href="<?php echo e('publis.php'); ?>" target="_top">Volver</a>
            </div>
        </div>

        <form class="form-inline mb-3" method="get" action="publis.php">
            <input type="hidden" name="iframe" value="1">
            <input type="hidden" name="slot" value="<?php echo (int)$slot; ?>">
            <input class="form-control form-control-sm mr-2" type="text" name="q" value="<?php echo e($q); ?>"
                   placeholder="Buscar por ID, lugar, img o url" style="min-width:280px;">
            <button class="btn btn-sm btn-primary" type="submit">Buscar</button>
            <?php if ($q !== '') { ?>
                <a class="btn btn-sm btn-link" href="publis.php?iframe=1&slot=<?php echo (int)$slot; ?>">Limpiar</a>
            <?php } ?>
        </form>

        <div class="table-responsive bg-white rounded border">
            <table class="table table-sm mb-0">
                <thead class="thead-light">
                <tr>
                    <th style="width:90px;">ID</th>
                    <th style="width:220px;">Preview</th>
                    <th>Archivo</th>
                    <th style="width:120px;">Lugar actual</th>
                    <th style="width:160px;">Acción</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$rows) { ?>
                    <tr><td colspan="5" class="text-center p-4 text-muted">Sin resultados.</td></tr>
                <?php } ?>

                <?php foreach ($rows as $r):
                    $id = (int)$r['ID'];
                    $carp = (string)$r['carpetafoto'];
                    $img = (string)$r['img'];
                    $url = (string)$r['url'];
                    $lugarActual = (int)$r['lugar'];

                    $src = build_media_url($DOM_BASE, $carp, $img);
                    $isVideo = is_video_file($img);
                    ?>
                    <tr>
                        <td><b><?php echo $id; ?></b></td>
                        <td>
                            <?php if ($src !== '') { ?>
                                <?php if ($isVideo) { ?>
                                    <video class="thumb" muted autoplay loop playsinline>
                                        <source src="<?php echo e($src); ?>" type="video/mp4">
                                    </video>
                                <?php } else { ?>
                                    <img class="thumb" src="<?php echo e($src); ?>" alt="">
                                <?php } ?>
                            <?php } else { ?>
                                <span class="text-muted">Sin archivo</span>
                            <?php } ?>
                        </td>
                        <td>
                            <div style="font-size:13px;"><b><?php echo e($img); ?></b></div>
                            <?php if ($url !== '') { ?>
                                <div style="font-size:12px;" class="text-muted"><?php echo e($url); ?></div>
                            <?php } ?>
                            <div style="font-size:12px;" class="text-muted">Carpeta: <?php echo e($carp); ?></div>
                        </td>
                        <td>
                            <?php if ($lugarActual > 0) { ?>
                                <span class="badge badge-info"><?php echo $lugarActual; ?></span>
                            <?php } else { ?>
                                <span class="badge badge-secondary">0</span>
                            <?php } ?>
                        </td>
                        <td>
                            <form method="post" action="publis.php?iframe=1&slot=<?php echo (int)$slot; ?>&q=<?php echo urlencode($q); ?>&p=<?php echo (int)$page; ?>">
                                <input type="hidden" name="csrf" value="<?php echo e($CSRF); ?>">
                                <button class="btn btn-sm btn-success" type="submit" name="assign_publi_id" value="<?php echo $id; ?>">
                                    Colocar esta
                                </button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="d-flex align-items-center justify-content-between mt-3">
            <div class="text-muted" style="font-size:13px;">
                Total: <?php echo (int)$total; ?> — Página <?php echo (int)$page; ?> / <?php echo (int)$pages; ?>
            </div>

            <div>
                <?php
                $baseUrl = 'publis.php?iframe=1&slot=' . (int)$slot;
                if ($q !== '') $baseUrl .= '&q=' . urlencode($q);

                $prev = max(1, $page - 1);
                $next = min($pages, $page + 1);
                ?>
                <a class="btn btn-sm btn-outline-secondary <?php echo ($page <= 1 ? 'disabled' : ''); ?>"
                   href="<?php echo e($baseUrl . '&p=' . $prev); ?>">Anterior</a>
                <a class="btn btn-sm btn-outline-secondary <?php echo ($page >= $pages ? 'disabled' : ''); ?>"
                   href="<?php echo e($baseUrl . '&p=' . $next); ?>">Siguiente</a>
            </div>
        </div>

    </div>
    </body>
    </html>
    <?php
    exit;
}

// ---------------------------
// MAIN: notas en 2 columnas + sidebar derecho (placeholder)
// ---------------------------

$limitNotas = 24; // ajustá si querés
$notas = [];

$stmt = $conn->prepare("
    SELECT ID, titulo, bajada, d, m, a, carpetafoto, foto, ext_img
    FROM notas
    WHERE ver = 'si' AND home = 'si'
    ORDER BY ID DESC
    LIMIT ?
");
$stmt->bind_param("i", $limitNotas);
$stmt->execute();
$res = $stmt->get_result();
while ($res && ($r = $res->fetch_assoc())) $notas[] = $r;
$stmt->close();

// Slots: 10000004 + pos (pos desde 1)
$baseSlot = 10000000;
$slots = [];
foreach ($notas as $i => $r) {
    $pos = $i + 1;
    $slots[] = $baseSlot + $pos;
}

// Publicidades ya asignadas a esos slots
$publiPorSlot = [];
if ($slots) {
    $in = implode(',', array_fill(0, count($slots), '?'));
    $types = str_repeat('i', count($slots));
    $sql = "SELECT ID, lugar, carpetafoto, img, url FROM publicidades_gif WHERE lugar IN ($in)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$slots);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($res && ($p = $res->fetch_assoc())) {
        $publiPorSlot[(int)$p['lugar']] = $p;
    }
    $stmt->close();
}
?>
<!doctype html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Asignar publicidades</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
          crossorigin="anonymous">

    <style>
        body { background:#f3f5f7; }
        .topbar { background:#111; color:#fff; }
        .note-card { border:0; border-radius:10px; overflow:hidden; box-shadow: 0 6px 18px rgba(0,0,0,.06); height:100%; }
        .note-thumb { width:100%; height:170px; object-fit:cover; background:#ddd; }
        .note-body { padding:14px 14px 10px 14px; }
        .note-title { font-size:16px; font-weight:700; margin:0 0 6px 0; line-height:1.15; }
        .note-excerpt { font-size:13px; color:#555; margin:0; }
        .slot-line { font-size:12px; color:#777; margin-top:10px; }
        .btn-publi { background:#28a745; border-color:#28a745; font-weight:700; }
        .btn-publi:hover { background:#23903c; border-color:#23903c; }
        .assigned-mini { font-size:12px; color:#666; margin-top:8px; }
        .sidebar-box {
            background:#e9ecef;
            border:2px solid #111;
            border-radius:10px;
            min-height: calc(100vh - 160px);
        }
        .sidebar-title { font-weight:700; padding:14px; border-bottom:1px solid rgba(0,0,0,.12); }
        .sidebar-body { padding:14px; color:#555; font-size:13px; }
        .sticky { position: sticky; top: 16px; }
        .footer-actions { margin-top: 18px; }
    </style>
</head>
<body>

<div class="topbar py-3">
    <div class="container-fluid px-4 d-flex align-items-center justify-content-between">
        <div>
            <div style="font-size:18px; font-weight:700;">Asignar publicidades entre notas</div>
            <div style="font-size:12px; color:#cfcfcf;">Lugares: 10000004 + posición de nota (4ta nota => 10000008)</div>
        </div>
        <div class="d-flex gap-2" style="gap:8px;">
            <a class="btn btn-sm btn-outline-light" href="/panel">Volver al panel</a>
        </div>
    </div>
</div>

<div class="container-fluid px-4 py-4">
    <div class="row">
        <!-- IZQUIERDA: notas en 2 columnas -->
        <div class="col-12 col-lg-8">
            <?php if (!$notas) { ?>
                <div class="alert alert-warning">No hay notas para mostrar (ver='si' y home='si').</div>
            <?php } ?>

            <div class="row">
                <?php foreach ($notas as $i => $n):
                    $pos  = $i + 1;
                    $slot = $baseSlot + $pos;

                    $id     = (int)$n['ID'];
                    $titulo = (string)$n['titulo'];
                    $bajada = (string)$n['bajada'];

                    $carp = (string)$n['carpetafoto'];
                    $foto = (string)$n['foto'];
                    $ext  = (string)$n['ext_img'];

                    $thumb = '';
                    if ($foto !== '') {
                        if (stripos($foto, 'http') === 0) {
                            $thumb = str_replace('http://', 'https://', $foto);
                        } else {
                            // tu convención típica: $dom/$carpetafoto/thumbnail_$foto$ext_img
                            $thumb = build_media_url($DOM_BASE, $carp, 'thumbnail_' . $foto . $ext);
                        }
                    }

                    $pub = $publiPorSlot[$slot] ?? null;
                    ?>
                    <div class="col-12 col-md-6 mb-4">
                        <div class="note-card">
                            <?php if ($thumb !== '') { ?>
                                <img class="note-thumb" src="<?php echo e($thumb); ?>" alt="">
                            <?php } else { ?>
                                <div class="note-thumb d-flex align-items-center justify-content-center text-muted">
                                    Sin imagen
                                </div>
                            <?php } ?>

                            <div class="note-body">
                                <div class="slot-line">Nota ID: <?php echo $id; ?> — Posición: <?php echo $pos; ?> — Lugar: <b><?php echo (int)$slot; ?></b></div>
                                <h3 class="note-title"><?php echo txt($titulo); ?></h3>
                                <p class="note-excerpt"><?php echo e(mb_cut($bajada, 180)); ?></p>

                                <div class="mt-3">
                                    <button type="button"
                                            class="btn btn-success btn-block btn-publi btn-slot"
                                            data-slot="<?php echo (int)$slot; ?>"
                                            data-toggle="modal"
                                            data-target="#publiModal">
                                        Poner publi acá
                                    </button>

                                    <?php if ($pub): ?>
                                        <?php
                                        $pubId = (int)$pub['ID'];
                                        $pubImg = (string)$pub['img'];
                                        $pubCarp = (string)$pub['carpetafoto'];
                                        $pubSrc = build_media_url($DOM_BASE, $pubCarp, $pubImg);
                                        $pubIsVideo = is_video_file($pubImg);
                                        ?>
                                        <div class="assigned-mini">
                                            Asignada: <b>ID <?php echo $pubId; ?></b> — <?php echo e($pubImg); ?>
                                            <?php if ($pubSrc !== '') { ?>
                                                <div class="mt-2">
                                                    <?php if ($pubIsVideo) { ?>
                                                        <video muted autoplay loop playsinline style="width:100%; border-radius:8px; max-height:140px; object-fit:cover;">
                                                            <source src="<?php echo e($pubSrc); ?>" type="video/mp4">
                                                        </video>
                                                    <?php } else { ?>
                                                        <img src="<?php echo e($pubSrc); ?>" alt="" style="width:100%; border-radius:8px; max-height:140px; object-fit:cover;">
                                                    <?php } ?>
                                                </div>
                                            <?php } ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="assigned-mini">No hay publicidad asignada todavía a este lugar.</div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="footer-actions text-center">
                <a class="btn btn-outline-dark" href="/panel">Volver al panel</a>
            </div>
        </div>

        <!-- DERECHA: espacio publicidades clásico -->
        <div class="col-12 col-lg-4 mt-4 mt-lg-0">
            <div class="sidebar-box sticky">
                <div class="sidebar-title">Espacio para publicidades (clásico)</div>
                <div class="sidebar-body">
                    Acá después podés mostrar el bloque clásico (por ahora placeholder gris, como tu dibujo).
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="publiModal" tabindex="-1" role="dialog" aria-labelledby="publiModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document" style="max-width:1140px;">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title" id="publiModalLabel">Elegir publicidad</h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <div class="modal-body p-0">
                <iframe id="publiFrame" src="" style="width:100%; height:75vh; border:0;"></iframe>
            </div>

            <div class="modal-footer">
                <div style="font-size:13px;color:#666;" class="mr-auto" id="slotInfo"></div>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>

<script>
    $(function () {
        $('.btn-slot').on('click', function () {
            var slot = $(this).data('slot');
            $('#slotInfo').text('Asignando al lugar: ' + slot);
            $('#publiFrame').attr('src', 'publis.php?iframe=1&slot=' + encodeURIComponent(slot));
        });

        $('#publiModal').on('hidden.bs.modal', function () {
            $('#publiFrame').attr('src', '');
            $('#slotInfo').text('');
        });
    });
</script>

</body>
</html>