<?php
/*
   MÓDULO REPORTES - SOLO VISTA VISUAL
   Este archivo se carga desde dashboard_superadmin.php con:
   include("modulos/reportes.php");
   No lleva <html>, <head>, <body>, scripts externos ni estilos.
*/


/* =========================================
   REPORTES INDEPENDIENTES VINCULADOS MEDIANTE REPORTES_NOTAS
========================================= */

$lista_clientes = array();
$consulta_clientes = $conn->query("
    SELECT id, razon_social
    FROM clientes
    WHERE estado='activo'
    ORDER BY razon_social ASC
");

if ($consulta_clientes) {
    while ($fila_cliente = $consulta_clientes->fetch_assoc()) {
        if (!empty($fila_cliente['razon_social'])) {
            $lista_clientes[] = array(
                'id' => intval($fila_cliente['id']),
                'nombre' => $fila_cliente['razon_social']
            );
        }
    }
}

/*
   Los reportes ya no se crean ni se sincronizan automáticamente por cliente.
   Cada reporte se crea desde Noticias y sus noticias se vinculan mediante
   la tabla reportes_notas.
*/

$filtro_estado = isset($_GET['estado']) ? trim($_GET['estado']) : '';
$filtro_cliente = isset($_GET['cliente_id']) ? intval($_GET['cliente_id']) : 0;
$filtro_fecha_inicio = isset($_GET['fecha_inicio']) ? trim($_GET['fecha_inicio']) : '';
$filtro_fecha_fin = isset($_GET['fecha_fin']) ? trim($_GET['fecha_fin']) : '';
$vista_reportes = isset($_GET['ver']) ? trim($_GET['ver']) : '';
$ver_archivados = $vista_reportes === 'archivados';
$ver_eliminados = $vista_reportes === 'eliminados';

$condiciones_reportes = array();

if ($ver_eliminados) {
    $condiciones_reportes[] = "r.estado='eliminado'";
} elseif ($ver_archivados) {
    $condiciones_reportes[] = "r.estado='archivado'";
} else {
    $condiciones_reportes[] = "r.estado='activo'";
}

if ($filtro_estado === 'bloqueado' || $filtro_estado === 'desbloqueado') {
    $condiciones_reportes[] = "r.estado_acceso='" . $conn->real_escape_string($filtro_estado) . "'";
}

if ($filtro_cliente > 0) {
    $condiciones_reportes[] = "r.cliente_id=" . intval($filtro_cliente);
}

if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $filtro_fecha_inicio)) {
    $condiciones_reportes[] = "DATE(r.fecha_reporte)>='" . $conn->real_escape_string($filtro_fecha_inicio) . "'";
}

if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $filtro_fecha_fin)) {
    $condiciones_reportes[] = "DATE(r.fecha_reporte)<='" . $conn->real_escape_string($filtro_fecha_fin) . "'";
}

$sql_reportes = "
    SELECT
        r.id,
        r.titulo,
        (
            SELECT COUNT(*)
            FROM reportes_notas rn_contador
            INNER JOIN notas n_contador ON n_contador.id = rn_contador.nota_id
            WHERE rn_contador.reporte_id = r.id
              AND (n_contador.estado IS NULL OR n_contador.estado NOT IN ('archivado','eliminado'))
              AND (n_contador.tipo_medio IS NULL OR n_contador.tipo_medio <> 'Archivo')
        ) AS total_notas,
        r.total_alertas,
        r.fecha_reporte,
        r.fecha_creacion,
        r.estado_acceso,
        r.estado,
        r.cliente_id,
        COALESCE(c.razon_social, 'Sin cliente asignado') AS cliente
    FROM reportes r
    LEFT JOIN clientes c ON c.id=r.cliente_id
    WHERE " . implode(' AND ', $condiciones_reportes) . "
    ORDER BY COALESCE(r.fecha_reporte, DATE(r.fecha_creacion)) DESC, r.id DESC
";

/*==========================================
DETALLE DEL REPORTE
==========================================*/

$reporte_detalle = isset($_GET["reporte_id"])
    ? intval($_GET["reporte_id"])
    : 0;

$noticias_cliente = array();

/*
   Resolver siempre la tarifa individual de cada noticia.
   La columna notas.tarifa es la fuente principal. Para noticias antiguas o
   registros que aún no tengan esa columna actualizada, se usa el valor
   individual guardado dentro de __DATOS_NOTICIA__. Nunca se suman tarifas
   entre noticias en esta función.
*/
if (!function_exists('tarifaIndividualReporte')) {
    function tarifaIndividualReporte($noticia) {
        /* Fuente oficial de producción: notas.tarifa. */
        $tarifa = $noticia['tarifa'] ?? null;
        if ($tarifa !== null && $tarifa !== '' && is_numeric($tarifa)) {
            return round((float)$tarifa, 2);
        }

        /* Compatibilidad temporal con noticias anteriores a la migración. */
        $descripcion = (string)($noticia['descripcion'] ?? '');
        if (preg_match('/__DATOS_NOTICIA__\:([A-Za-z0-9+\/=]+)/', $descripcion, $m)) {
            $json = base64_decode($m[1], true);
            if ($json !== false) {
                $datos = json_decode($json, true);
                if (is_array($datos) && isset($datos['valor_noticia']) && is_numeric($datos['valor_noticia'])) {
                    return round((float)$datos['valor_noticia'], 2);
                }
            }
        }

        return 0.0;
    }
}

$nombre_cliente_detalle = "";
$titulo_reporte_detalle = "";
$estado_acceso_detalle = "desbloqueado";
$reporte_id_detalle = 0;

if ($reporte_detalle > 0) {

    $qReporteDetalle = $conn->query("
        SELECT
            r.id,
            r.titulo,
            r.estado_acceso,
            r.cliente_id,
            COALESCE(c.razon_social, 'Sin cliente asignado') AS cliente
        FROM reportes r
        LEFT JOIN clientes c ON c.id=r.cliente_id
        WHERE r.id=".$reporte_detalle."
        LIMIT 1
    ");

    if ($qReporteDetalle && $qReporteDetalle->num_rows > 0) {
        $filaReporteDetalle = $qReporteDetalle->fetch_assoc();

        $reporte_id_detalle = intval($filaReporteDetalle["id"]);
        $titulo_reporte_detalle = trim((string)$filaReporteDetalle["titulo"]);
        $estado_acceso_detalle = trim((string)$filaReporteDetalle["estado_acceso"]);
        $nombre_cliente_detalle = trim((string)$filaReporteDetalle["cliente"]);

        if ($titulo_reporte_detalle === "") {
            $titulo_reporte_detalle = "Reporte sin título";
        }

        $sql_detalle = "
            SELECT n.*
            FROM reportes_notas rn
            INNER JOIN notas n ON n.id=rn.nota_id
            WHERE rn.reporte_id=".$reporte_id_detalle."
              AND n.estado NOT IN ('archivado','eliminado')
              AND (n.tipo_medio IS NULL OR n.tipo_medio<>'Archivo')
            ORDER BY rn.orden ASC, rn.fecha_agregada ASC, n.id ASC
        ";

        $qDetalle = $conn->query($sql_detalle);

        if ($qDetalle) {
            while ($fila = $qDetalle->fetch_assoc()) {
                $noticias_cliente[] = $fila;
            }
        }
    } else {
        $reporte_detalle = 0;
    }
}


$reportes = array();
$consulta_reportes = $conn->query($sql_reportes);

if ($consulta_reportes) {
    while ($fila_reporte = $consulta_reportes->fetch_assoc()) {
        $reportes[] = $fila_reporte;
    }
}

?>

<style>
.reportes-cliente-buscador{position:relative;width:100%;}
.reportes-cliente-buscador input[type="text"]{width:100%;border:1px solid #d9dce8;border-radius:8px;padding:13px;color:#1e2942;font-size:14px;background:#fff;outline:none;}
.reportes-cliente-buscador input[type="text"]:focus{border-color:#ef5124;}
.reportes-cliente-resultados{display:none;position:absolute;top:calc(100% + 4px);left:0;right:0;max-height:260px;overflow-y:auto;background:#fff;border:1px solid #d9dce8;border-radius:8px;box-shadow:0 10px 24px rgba(0,0,0,.14);z-index:99999;}
.reportes-cliente-item{padding:11px 12px;border-bottom:1px solid #eef0f5;cursor:pointer;color:#1e2942;font-size:13px;line-height:1.35;background:#fff;}
.reportes-cliente-item:last-child{border-bottom:0;}
.reportes-cliente-item:hover{background:#fff0ea;color:#ef5124;}
.reportes-cliente-vacio{padding:12px;color:#8a90a3;font-size:12px;text-align:center;}
/* =========================
   CALENDARIO DE REPORTES
========================= */
.reportes-date-box{position:relative;width:100%;}
.reportes-date-display{border:1px solid #d9dce8;border-radius:8px;padding:14px 12px;background:#fff;cursor:pointer;display:flex;align-items:center;gap:9px;color:#6f7480;font-size:14px;margin-bottom:14px;min-height:50px;}
.reportes-date-display.active{border:2px solid #b6b8c4;box-shadow:0 0 0 2px #d4d5dd;}
.reportes-date-display .calendar-icon{font-size:17px;}
.reportes-date-display em{font-style:italic;}
.reportes-calendar-popup{display:none;position:absolute;top:62px;left:0;width:300px;background:#fff;border-radius:8px;box-shadow:0 10px 28px rgba(0,0,0,.16);border:1px solid #e5e7eb;padding:12px;z-index:99998;box-sizing:border-box;}
.reportes-calendar-popup.show{display:block;}
.reportes-calendar-popup *{box-sizing:border-box;}
.reportes-calendar-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px;}
.reportes-calendar-head button{border:none;background:#fff;font-size:21px;color:#777;cursor:pointer;width:28px;height:28px;border-radius:5px;}
.reportes-calendar-head button:hover{background:#f4f5f7;}
.reportes-calendar-selects{display:flex;align-items:center;justify-content:center;gap:6px;flex:1;}
.reportes-calendar-selects select{border:1px solid #d9dce8;background:#fff;font-size:13px;color:#333;cursor:pointer;padding:5px 7px;border-radius:6px;width:auto;margin:0;}
.reportes-range-info{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px;}
.reportes-range-box{border:1px solid #e4e6ec;border-radius:6px;padding:7px 8px;background:#fafbfc;}
.reportes-range-box small{display:block;color:#8a90a3;font-size:10px;margin-bottom:2px;}
.reportes-range-box strong{display:block;color:#1e2942;font-size:12px;min-height:15px;}
.reportes-week-days{display:grid!important;grid-template-columns:repeat(7,minmax(0,1fr))!important;gap:2px!important;width:100%!important;margin:0 0 6px!important;padding:0!important;text-align:center;font-size:10px;color:#999;}
.reportes-week-days>div{height:18px!important;display:flex!important;align-items:center!important;justify-content:center!important;margin:0!important;padding:0!important;}
.reportes-days-grid{display:grid!important;grid-template-columns:repeat(7,minmax(0,1fr))!important;grid-auto-rows:31px!important;gap:2px!important;width:100%!important;margin:0!important;padding:0!important;}
.reportes-day{width:auto!important;min-width:0!important;height:31px!important;margin:0!important;padding:0!important;display:flex!important;align-items:center!important;justify-content:center!important;font-size:11px;color:#555;cursor:pointer;user-select:none;border-radius:50%;position:relative!important;float:none!important;transform:none!important;}
.reportes-day.empty{cursor:default;}
.reportes-day:not(.empty):hover{background:#eaf3ff;}
.reportes-day.start,.reportes-day.end,.reportes-day.same{background:#5aa2f2;color:#fff;border-radius:50%;z-index:2;}
.reportes-day.range{background:#d5d5d5;color:#555;border-radius:0;}
.reportes-calendar-actions{display:flex;align-items:center;justify-content:space-between;gap:6px;margin-top:10px;padding-top:10px;border-top:1px solid #eceef2;}
.reportes-calendar-actions button{flex:1;border:1px solid #d9dce8;background:#fff;color:#1e2942;border-radius:6px;padding:8px 6px;font-size:11px;font-weight:bold;cursor:pointer;}
.reportes-calendar-actions button:hover{background:#f4f6fa;}
.reportes-calendar-actions .reportes-calendar-apply{background:#ef5124;border-color:#ef5124;color:#fff;}
.reportes-btn-clear{width:100%;margin-top:10px;border:1px solid #ef5124;background:#fff;color:#ef5124;padding:13px;border-radius:8px;font-weight:bold;cursor:pointer;text-transform:uppercase;font-size:12px;}
.reportes-btn-clear:hover{background:#fff0ea;}
/*=========================
BOTONES SUPERIORES
=========================*/

.reportes-actions-row{
    display:flex;
    justify-content:flex-start;
    align-items:center;
    gap:10px;
    margin-bottom:20px;
}

.reportes-actions-box{
    position:relative;
    display:inline-block;
}

.reportes-btn-actions,
.reportes-btn-secondary,
.reportes-btn-select{

    height:42px;
    padding:0 18px;
    border-radius:8px;
    border:1px solid #ef5124;
    background:#fff;
    color:#ef5124;
    font-size:13px;
    font-weight:600;
    cursor:pointer;
    transition:.20s;
    margin-left:0;

}

.reportes-btn-actions:hover,
.reportes-btn-secondary:hover,
.reportes-btn-select:hover{

    background:#ef5124;
    color:#fff;

}


.reportes-btn-actions.disabled{
    opacity:.45;
    cursor:not-allowed;
    background:#f5f5f5;
    color:#777;
    border-color:#d9dce8;
}

.reportes-btn-actions:disabled{

    opacity:.45;
    cursor:not-allowed;
    background:#f5f5f5;
    color:#777;
    border-color:#d9dce8;

}

.reportes-actions-menu{

    display:none;
    position:absolute;
    top:100%;
    left:0;
    margin-top:6px;

    width:190px;

    background:#fff;
    border:1px solid #d9dce8;
    border-radius:8px;
    box-shadow:0 8px 20px rgba(0,0,0,.12);

    z-index:99999;

}

.reportes-actions-menu button{

    width:100%;
    padding:12px 15px;
    border:0;
    background:#fff;
    text-align:left;
    cursor:pointer;
    font-size:13px;

}

.reportes-actions-menu button:hover{

    background:#fff3ee;

}

.reportes-actions-menu .danger:hover{

    background:#ffe9e9;
    color:#d62f2f;

}

.reportes-actions-box.open .reportes-actions-menu{
    display:block;
}    
    

.reportes-empty-state{
    display:none;
    padding:35px 20px;
    text-align:center;
    color:#8a90a3;
    border:1px dashed #d9dce8;
    border-radius:10px;
    background:#fafbfc;
}

.reporte-item.reportes-oculto{
    display:none !important;
}



/* =========================================
   TARJETAS DE REPORTES - DISEÑO EXPECTATIVA
========================================= */
.reporte-item{
    position:relative !important;
    display:block !important;
    width:100% !important;
    padding:0 0 0 38px !important;
    margin:0 0 16px !important;
    border:0 !important;
    border-radius:0 !important;
    background:transparent !important;
    box-shadow:none !important;
    overflow:visible !important;
}
.reporte-item::before,
.reporte-item::after{
    display:none !important;
    content:none !important;
}
.reporte-item .reporte-check{
    position:absolute !important;
    left:1px !important;
    top:50% !important;
    transform:translateY(-50%) !important;
    width:22px !important;
    height:22px !important;
    margin:0 !important;
    z-index:3 !important;
}
.reporte-item .reporte-box{
    display:grid !important;
    grid-template-columns:minmax(0,1fr) 215px !important;
    width:100% !important;
    min-height:158px !important;
    margin:0 !important;
    padding:0 !important;
    overflow:hidden !important;
    border:2px solid #e2e4ef !important;
    border-radius:17px !important;
    background:#fff !important;
    box-shadow:none !important;
}
.reporte-item .reporte-main{
    min-width:0 !important;
    min-height:158px !important;
    padding:27px 28px 20px !important;
    display:flex !important;
    flex-direction:column !important;
    justify-content:flex-start !important;
}
.reporte-item .reporte-top{
    width:100% !important;
    margin:0 0 8px !important;
    padding:0 !important;
    display:flex !important;
    align-items:center !important;
    justify-content:flex-start !important;
    text-align:left !important;
}
.reporte-item .reporte-date{
    display:inline-flex !important;
    align-items:center !important;
    justify-content:flex-start !important;
    gap:8px !important;
    margin:0 !important;
    padding:0 !important;
    color:#9196a8 !important;
    font-size:16px !important;
    line-height:1 !important;
    text-align:left !important;
}
.reporte-item .reporte-date svg{
    width:18px !important;
    height:18px !important;
    stroke:currentColor !important;
    flex:0 0 18px !important;
}
.reporte-item .reporte-content-row{
    display:flex !important;
    align-items:center !important;
    justify-content:space-between !important;
    gap:24px !important;
    min-width:0 !important;
    flex:1 1 auto !important;
}
.reporte-item .reporte-info{
    min-width:0 !important;
    flex:1 1 auto !important;
    display:flex !important;
    flex-direction:column !important;
    align-items:flex-start !important;
    justify-content:center !important;
    text-align:left !important;
}
.reporte-item .reporte-title{
    display:inline-block !important;
    margin:0 !important;
    color:#202a49 !important;
    font-size:21px !important;
    line-height:1.2 !important;
    font-weight:800 !important;
    text-decoration:underline !important;
    text-underline-offset:2px !important;
    text-transform:uppercase !important;
}
.reporte-item .reporte-title:hover{
    color:#202a49 !important;
}
.reporte-item .reporte-client{
    display:flex !important;
    align-items:center !important;
    gap:7px !important;
    margin-top:13px !important;
    color:#ff5d42 !important;
    font-size:15px !important;
    line-height:1.3 !important;
    font-weight:500 !important;
}
.reporte-item .reporte-client svg{
    width:20px !important;
    height:20px !important;
    flex:0 0 20px !important;
    stroke:currentColor !important;
}
.reporte-item .reporte-links{
    display:flex !important;
    align-items:center !important;
    gap:14px !important;
    flex:0 0 auto !important;
    padding-bottom:0 !important;
}
.reporte-item .reporte-link{
    display:inline-flex !important;
    align-items:center !important;
    justify-content:center !important;
    width:45px !important;
    height:45px !important;
    border:0 !important;
    border-radius:11px !important;
    background:#fff0ec !important;
    color:#ff6248 !important;
    text-decoration:none !important;
    box-shadow:none !important;
    transition:transform .18s ease, background .18s ease !important;
}
.reporte-item .reporte-link:hover{
    transform:translateY(-2px) !important;
    background:#ffe5de !important;
}
.reporte-item .reporte-link svg{
    width:22px !important;
    height:22px !important;
    display:block !important;
    stroke:currentColor !important;
}
.reporte-item .reporte-count{
    min-width:0 !important;
    border-left:1px solid #e5e6ef !important;
    display:flex !important;
    flex-direction:column !important;
    align-items:center !important;
    justify-content:center !important;
    text-align:center !important;
    background:#fff !important;
    padding:0 !important;
    margin:0 !important;
    width:100% !important;
    box-sizing:border-box !important;
}
.reporte-item .reporte-count h1{
    margin:0 !important;
    padding:0 !important;
    color:#252c49 !important;
    font-size:64px !important;
    line-height:1 !important;
    font-weight:400 !important;
    text-align:center !important;
}
.reporte-item .reporte-count small{
    display:block !important;
    margin:8px 0 0 !important;
    padding:0 !important;
    color:#9296a8 !important;
    font-size:14px !important;
    font-weight:500 !important;
    line-height:1 !important;
    text-transform:uppercase !important;
    text-align:center !important;
}
@media(max-width:900px){
    .reporte-item .reporte-box{grid-template-columns:1fr !important;}
    .reporte-item .reporte-count{border-left:0 !important;border-top:1px solid #e5e6ef !important;min-height:110px !important;}
    .reporte-item .reporte-content-row{align-items:flex-start !important;flex-direction:column !important;}
}

/* =========================================
   VISTA DETALLE DEL REPORTE
========================================= */
.reportes-wrapper.reportes-modo-detalle{
    display:block !important;
    width:100% !important;
}
.reportes-modo-detalle .reportes-right{
    width:100% !important;
    max-width:none !important;
    flex:1 1 100% !important;
}
.reportes-modo-detalle .reportes-content{
    padding:0 !important;
}
.reportes-detalle{
    width:100%;
    background:#fff;
    color:#172442;
}
.reportes-detalle-cabecera{
    background:#f5f5fb;
    border-bottom:1px solid #ececf4;
    padding:44px 8.5% 48px;
}
.reportes-detalle-volver{
    display:inline-flex;
    align-items:center;
    gap:9px;
    margin-bottom:24px;
    padding:10px 16px;
    border:1px solid #ef5124;
    border-radius:9px;
    background:#fff;
    color:#ef5124;
    text-decoration:none;
    font-size:14px;
    font-weight:700;
    transition:.2s ease;
}
.reportes-detalle-volver:hover{
    background:#ef5124;
    color:#fff;
    transform:translateY(-1px);
}
.reportes-detalle-titulo{
    margin:0 0 12px;
    color:#202e53;
    font-size:31px;
    line-height:1.18;
    font-weight:800;
    text-transform:uppercase;
}
.reportes-detalle-cliente{
    margin:0;
    color:#202e53;
    font-size:17px;
}
.reportes-detalle-cliente strong{
    font-weight:500;
}
.reportes-detalle-botones{
    display:flex;
    flex-wrap:wrap;
    gap:14px;
    margin-top:27px;
}
.reportes-detalle-boton{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:7px;
    min-height:38px;
    padding:0 15px;
    border-radius:7px;
    background:#fff;
    text-decoration:none;
    font-size:14px;
    font-weight:500;
}
.reportes-detalle-boton.editar{border:1px solid #ff694b;color:#ff694b;}
.reportes-detalle-boton.bloquear{border:1px solid #00bce8;color:#00bce8;}
.reportes-detalle-boton.secundario{border:1px solid #a9acb8;color:#9295a2;}
.reportes-detalle-boton{cursor:pointer;}
.reportes-modal-editar{
    display:none;
    position:fixed;
    inset:0;
    z-index:100000;
    background:rgba(20,28,48,.52);
    align-items:center;
    justify-content:center;
    padding:20px;
}
.reportes-modal-editar.abierto{display:flex;}
.reportes-modal-panel{
    width:min(520px,100%);
    background:#fff;
    border-radius:14px;
    box-shadow:0 22px 60px rgba(0,0,0,.25);
    overflow:hidden;
}
.reportes-modal-cabecera{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:15px;
    padding:20px 24px;
    border-bottom:1px solid #eceef4;
}
.reportes-modal-cabecera h3{margin:0;color:#202e53;font-size:20px;}
.reportes-modal-cerrar{border:0;background:transparent;color:#8a90a3;font-size:28px;line-height:1;cursor:pointer;}
.reportes-modal-cuerpo{padding:24px;}
.reportes-modal-campo{margin-bottom:18px;}
.reportes-modal-campo label{display:block;margin-bottom:7px;color:#202e53;font-size:13px;font-weight:700;}
.reportes-modal-campo input,.reportes-modal-campo select{width:100%;height:46px;border:1px solid #d9dce8;border-radius:8px;padding:0 12px;color:#1e2942;background:#fff;font-size:14px;outline:none;box-sizing:border-box;}
.reportes-modal-campo input:focus,.reportes-modal-campo select:focus{border-color:#ef5124;box-shadow:0 0 0 2px rgba(239,81,36,.12);}
.reportes-modal-acciones{display:flex;justify-content:flex-end;gap:10px;padding:0 24px 24px;}
.reportes-modal-acciones button{height:42px;padding:0 18px;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;}
.reportes-modal-cancelar{border:1px solid #cfd3df;background:#fff;color:#60677a;}
.reportes-modal-guardar{border:1px solid #ef5124;background:#ef5124;color:#fff;}
.reportes-modal-guardar:disabled{opacity:.6;cursor:wait;}
.reportes-detalle-cuerpo{
    padding:52px 8.5% 70px;
}
.reportes-detalle-resumen{
    margin:0 0 18px;
    color:#989baa;
    font-size:16px;
    font-style:italic;
}
.reportes-noticia-card{
    display:grid;
    grid-template-columns:minmax(0,1fr) 205px 44px;
    min-height:151px;
    margin-bottom:17px;
    overflow:hidden;
    border:1px solid #d9dcea;
    border-radius:14px;
    background:#fff;
}
.reportes-noticia-contenido{
    padding:27px 27px 23px;
}
.reportes-noticia-meta{
    display:flex;
    flex-wrap:wrap;
    align-items:center;
    gap:28px;
    margin-bottom:15px;
    color:#9297a8;
    font-size:14px;
}
.reportes-noticia-meta span{
    display:inline-flex;
    align-items:center;
    gap:7px;
}
.reportes-noticia-titulo{
    display:inline-block;
    margin-bottom:17px;
    color:#172442;
    font-size:17px;
    line-height:1.35;
    font-weight:700;
    text-decoration:underline;
    text-underline-offset:2px;
}
.reportes-noticia-titulo:hover{
    color:#ef5124;
}
.reportes-noticia-medio{
    display:flex;
    flex-wrap:wrap;
    align-items:center;
    gap:12px;
    color:#172442;
    font-size:14px;
}
.reportes-noticia-tipo{
    color:#ff6047;
    font-size:12px;
    font-weight:700;
    text-transform:uppercase;
}
.reportes-noticia-separador{
    width:20px;
    height:1px;
    background:#27334f;
}
.reportes-noticia-tarifa{
    display:flex;
    flex-direction:column;
    justify-content:center;
    padding:20px 28px;
    border-left:1px solid #e0e2ed;
    background:#fff;
}
.reportes-noticia-tarifa small{
    margin-bottom:7px;
    color:#9a9dad;
    font-size:13px;
}
.reportes-noticia-tarifa strong{
    color:#172442;
    font-size:24px;
    line-height:1;
}
.reportes-noticia-estado{
    display:flex;
    align-items:center;
    justify-content:center;
    background:#f7f7fc;
    border:0;
    padding:0;
    cursor:pointer;
}
.reportes-noticia-estado:hover{
    background:#ffe9e9;
}
.reportes-noticia-estado:disabled{
    opacity:.55;
    cursor:wait;
}
.reportes-noticia-estado span{
    display:flex;
    align-items:center;
    justify-content:center;
    width:20px;
    height:20px;
    border-radius:50%;
    background:#ff4f43;
    color:#fff;
    font-size:16px;
    font-weight:800;
    line-height:1;
}
.reportes-detalle-vacio{
    padding:35px;
    border:1px dashed #d9dce8;
    border-radius:12px;
    color:#8a90a3;
    text-align:center;
}
@media(max-width:900px){
    .reportes-detalle-cabecera,
    .reportes-detalle-cuerpo{padding-left:25px;padding-right:25px;}
    .reportes-noticia-card{grid-template-columns:1fr;}
    .reportes-noticia-tarifa{border-left:0;border-top:1px solid #e0e2ed;}
    .reportes-noticia-estado{min-height:42px;}
}

</style>

<style>
/* BOLETÍN PERSONALIZADO - FASE 1 */
.reporte-link.boletin-personalizado{border:1px solid #ffd0c5;background:#fff7f4;color:#ef5124}
.reporte-link.boletin-personalizado:hover{background:#ef5124;color:#fff}
.boletin-modal{display:none;position:fixed;inset:0;background:rgba(17,24,39,.58);z-index:100000;padding:24px;overflow:hidden}
.boletin-modal.abierto{display:flex;align-items:flex-start;justify-content:center}
.boletin-panel{width:min(1080px,100%);height:calc(100vh - 48px);max-height:calc(100vh - 48px);margin:0 auto;background:#fff;border-radius:18px;box-shadow:0 24px 70px rgba(0,0,0,.25);overflow:hidden;display:flex;flex-direction:column}
.boletin-modal-cabecera{display:flex;align-items:center;justify-content:space-between;padding:20px 24px;border-bottom:1px solid #eceef4}
.boletin-modal-cabecera h2{margin:0;color:#17213d;font-size:22px}
.boletin-cerrar{border:0;background:#f5f6fa;width:38px;height:38px;border-radius:10px;font-size:24px;cursor:pointer;color:#596078}
.boletin-contenido{display:grid;grid-template-columns:330px minmax(0,1fr);min-height:0;flex:1;overflow:hidden}
.boletin-controles{padding:22px;border-right:1px solid #eceef4;background:#fafbfe;align-self:stretch;overflow-y:auto;position:relative;z-index:2}
.boletin-campo{margin-bottom:17px}.boletin-campo label{display:block;font-weight:700;color:#25304c;margin-bottom:7px;font-size:13px}
.boletin-campo select,.boletin-campo input[type=date],.boletin-campo input[type=file]{width:100%;box-sizing:border-box;border:1px solid #d9ddeb;border-radius:9px;padding:11px;background:#fff}.boletin-cliente-fijo{width:100%;box-sizing:border-box;border:1px solid #d9ddeb;border-radius:9px;padding:12px;background:#fff;color:#17213d;font-weight:800;line-height:1.35}
.boletin-color-fila{display:flex;gap:10px;align-items:center}.boletin-color-fila input[type=color]{width:58px;height:43px;border:1px solid #d9ddeb;border-radius:9px;background:#fff;padding:3px}.boletin-color-fila input[type=text]{flex:1;border:1px solid #d9ddeb;border-radius:9px;padding:11px}
.boletin-generar{width:100%;border:0;border-radius:9px;background:#ef5124;color:#fff;font-weight:800;padding:13px;cursor:pointer;font-size:14px}.boletin-generar:disabled{opacity:.6;cursor:wait}
.boletin-estado{min-height:22px;margin-top:12px;font-size:13px;color:#667085}.boletin-estado.error{color:#c62828}.boletin-estado.ok{color:#198754}
.boletin-vista-wrap{padding:24px;background:#f2f4f8;overflow-y:auto;overflow-x:auto;min-width:0;min-height:0}
.boletin-vista{width:620px;max-width:100%;margin:0 auto;background:#f5f5f5;border:1px solid #cfd3da;box-shadow:0 8px 24px rgba(0,0,0,.12)}
.boletin-portada{height:150px;position:relative;background:#d92f2f center/cover no-repeat;box-sizing:border-box}
.boletin-portada.sin-imagen{height:34px}.boletin-portada::before{display:none}
.boletin-meta{display:flex;justify-content:space-between;padding:13px 20px;font-size:13px;background:#fff}.boletin-meta span:first-child{font-weight:700}
.boletin-seccion{margin:18px 20px 24px;background:#fff;border-radius:10px;overflow:hidden}.boletin-seccion-titulo{padding:11px 14px;color:#fff;font-weight:800;font-size:14px;text-transform:uppercase}.boletin-noticia{padding:14px;border-bottom:1px solid #ececec}.boletin-noticia:last-child{border-bottom:0}.boletin-noticia h4{margin:0 0 7px;color:#202942;font-size:15px;line-height:1.35}.boletin-noticia-meta{font-size:12px;color:#667085;margin-bottom:7px}.boletin-noticia p{margin:0 0 9px;color:#40475a;font-size:13px;line-height:1.45;white-space:pre-line}.boletin-noticia-extra{display:flex;flex-wrap:wrap;gap:8px;align-items:center;font-size:12px}.boletin-tarifa{display:inline-block;background:#f2f4f8;color:#17213d;border-radius:5px;padding:5px 8px;font-weight:800}.boletin-enlace{color:#ef5124;text-decoration:none;font-weight:700}.boletin-enlace:hover{text-decoration:underline}.boletin-vacio{padding:28px;text-align:center;color:#7d8497}
.boletin-pie{padding:12px;text-align:center;color:#fff;font-size:12px}.boletin-acciones{display:none;flex-direction:column;gap:10px;margin-top:12px}.boletin-acciones.visible{display:flex}.boletin-accion{width:100%;min-width:0;border:0;border-radius:10px;padding:13px 14px;font-size:14px;font-weight:800;cursor:pointer;text-align:center}.boletin-accion.pdf{background:#ef5124;color:#fff}.boletin-accion.enlace{background:#17213d;color:#fff}.boletin-accion:disabled{opacity:.6;cursor:wait}.boletin-aviso-copiado{text-align:left;min-height:22px;margin-top:9px;color:#198754;font-size:13px;font-weight:700}
@media(max-width:850px){.boletin-modal{padding:8px;overflow:auto}.boletin-panel{height:auto;max-height:none;margin:0 auto}.boletin-contenido{grid-template-columns:1fr;overflow:visible}.boletin-controles{border-right:0;border-bottom:1px solid #eceef4;overflow:visible}.boletin-vista-wrap{padding:12px;overflow:visible}}
</style>


<div class="reportes-wrapper<?php echo $reporte_detalle>0 ? ' reportes-modo-detalle' : ''; ?>">
   
    <?php if($reporte_detalle==0){ ?>
    <aside class="reportes-left">

        <small>Reportes</small>
        <h2>Reportes</h2>

        <form method="GET">
            <input type="hidden" name="modulo" value="reportes">
            <?php if($ver_archivados){ ?><input type="hidden" name="ver" value="archivados"><?php } ?>
            <?php if($ver_eliminados){ ?><input type="hidden" name="ver" value="eliminados"><?php } ?>

            <div class="reportes-filter">
                <label>Estado</label>
                <select name="estado">
                    <option value="">Seleccione el estado</option>
                    <option value="bloqueado" <?php echo $filtro_estado==='bloqueado' ? 'selected' : ''; ?>>Bloqueado</option>
                    <option value="desbloqueado" <?php echo $filtro_estado==='desbloqueado' ? 'selected' : ''; ?>>Desbloqueado</option>
                </select>
            </div>

            <div class="reportes-filter">
                <label>Cliente</label>

                <div class="reportes-cliente-buscador">
                    <input
                        type="text"
                        id="reportes_cliente_buscar"
                        placeholder="Buscar cliente..."
                        autocomplete="off"
                        value="<?php
                        $nombre_cliente_filtro = '';
                        if ($filtro_cliente > 0) {
                            foreach ($lista_clientes as $cliente_item) {
                                if (intval($cliente_item['id']) === $filtro_cliente) {
                                    $nombre_cliente_filtro = $cliente_item['nombre'];
                                    break;
                                }
                            }
                        }
                        echo htmlspecialchars($nombre_cliente_filtro, ENT_QUOTES, 'UTF-8');
                        ?>">

                    <input
                        type="hidden"
                        name="cliente_id"
                        id="reportes_cliente"
                        value="<?php echo intval($filtro_cliente); ?>">

                    <div
                        id="reportes_cliente_resultados"
                        class="reportes-cliente-resultados">
                    </div>
                </div>
            </div>
            <div class="reportes-filter">
                <label>Creados el</label>
                <div class="reportes-date-box">
                    <div id="reportes_date_display" class="reportes-date-display">
                        <span class="calendar-icon">📅</span>
                        <span id="reportes_date_text"><em>Seleccionar fecha</em></span>
                    </div>
                    <input type="hidden" name="fecha_inicio" id="reportes_fecha_inicio" value="">
                    <input type="hidden" name="fecha_fin" id="reportes_fecha_fin" value="">
                    <div id="reportes_calendar_popup" class="reportes-calendar-popup">
                        <div class="reportes-calendar-head">
                            <button type="button" id="reportes_mes_anterior">‹</button>
                            <div class="reportes-calendar-selects">
                                <select id="reportes_selector_mes" aria-label="Mes"></select>
                                <select id="reportes_selector_anio" aria-label="Año"></select>
                            </div>
                            <button type="button" id="reportes_mes_siguiente">›</button>
                        </div>
                        <div class="reportes-range-info">
                            <div class="reportes-range-box"><small>Desde</small><strong id="reportes_rango_desde">—</strong></div>
                            <div class="reportes-range-box"><small>Hasta</small><strong id="reportes_rango_hasta">—</strong></div>
                        </div>
                        <div class="reportes-week-days">
                            <div>Lun</div><div>Mar</div><div>Mié</div><div>Jue</div><div>Vie</div><div>Sáb</div><div>Dom</div>
                        </div>
                        <div id="reportes_calendar_days" class="reportes-days-grid"></div>
                        <div class="reportes-calendar-actions">
                            <button type="button" id="reportes_cal_hoy">HOY</button>
                            <button type="button" id="reportes_cal_limpiar">LIMPIAR</button>
                            <button type="button" id="reportes_cal_aplicar" class="reportes-calendar-apply">APLICAR</button>
                        </div>
                    </div>
                </div>
            </div>
            <button type="submit" class="reportes-btn-filter">Aplicar filtros</button>
            <button type="button" id="reportes_limpiar_filtros" class="reportes-btn-clear">Limpiar filtros</button>
        </form>

    </aside>
    <?php } ?>

    <section class="reportes-right">

        <div class="reportes-toolbar">
            <div class="reportes-title-top">Reportes</div>
        </div>

        <div class="reportes-content">
           
            <?php if($reporte_detalle==0){ ?>

            <div class="reportes-actions-row">

    <div class="reportes-actions-box">

        <button
            type="button"
            id="btnAccionesReportes"
            class="reportes-btn-actions">
            ACCIONES⌄
        </button>

        <div
            id="menuAccionesReportes"
            class="reportes-actions-menu">

            <?php if($ver_eliminados){ ?>
                <button
                    type="button"
                    id="btnRestaurarReportes">
                    ↩ Restaurar
                </button>

                <button
                    type="button"
                    id="btnEliminarDefinitivamenteReportes"
                    class="danger">
                    🗑 Eliminar definitivamente
                </button>
            <?php } else { ?>
                <button
                    type="button"
                    id="btnArchivarReportes">
                    <span id="textoAccionArchivarReportes"><?php echo $ver_archivados ? '↩ Desarchivar' : '📦 Archivar'; ?></span>
                </button>

                <button
                    type="button"
                    id="btnEliminarReportes"
                    class="danger">
                    🗑 Eliminar
                </button>
            <?php } ?>

        </div>

    </div>

    <?php if(!$ver_archivados && !$ver_eliminados){ ?>
        <button
            type="button"
            id="btnArchivadosReportes"
            class="reportes-btn-secondary"
            data-url="dashboard_superadmin.php?modulo=reportes&ver=archivados">
            ARCHIVADOS
        </button>

        <button
            type="button"
            id="btnEliminadosReportes"
            class="reportes-btn-secondary"
            data-url="dashboard_superadmin.php?modulo=reportes&ver=eliminados">
            ELIMINADOS
        </button>
    <?php } else { ?>
        <button
            type="button"
            id="btnVolverReportes"
            class="reportes-btn-secondary"
            data-url="dashboard_superadmin.php?modulo=reportes">
            VOLVER
        </button>
    <?php } ?>

    <button
        type="button"
        id="btnSeleccionarReportes"
        class="reportes-btn-select">
        SELECCIONAR TODOS
    </button>

</div>
            <?php } ?>

            <?php if($reporte_detalle==0){ ?>
            <div class="reportes-list">

                <div id="reportesEmptyState" class="reportes-empty-state" style="<?php echo count($reportes)===0 ? 'display:block' : 'display:none'; ?>">
                    <?php
                    if ($ver_eliminados) {
                        echo 'No hay reportes eliminados.';
                    } elseif ($ver_archivados) {
                        echo 'No hay reportes archivados.';
                    } else {
                        echo 'No hay reportes para mostrar.';
                    }
                    ?>
                </div>

                <?php foreach($reportes as $r){ ?>
                    <article class="reporte-item" data-reporte-id="<?php echo intval($r['id']); ?>">

                        <input type="checkbox" class="reporte-check" value="<?php echo intval($r['id']); ?>">

                        <div class="reporte-box">

                            <div class="reporte-main">
                                <div class="reporte-top">
                                    <span class="reporte-date">
                                        <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"></circle><path d="M12 7v5l3 2"></path></svg>
                                        <?php $fecha_mostrar = !empty($r['fecha_reporte']) ? $r['fecha_reporte'] : $r['fecha_creacion']; echo date('d/m/Y', strtotime($fecha_mostrar)); ?>
                                    </span>
                                </div>

                                <div class="reporte-content-row">
                                    <div class="reporte-info">
                                        <a href="dashboard_superadmin.php?modulo=reportes&reporte_id=<?php echo intval($r['id']); ?>" class="reporte-title">
                                            <?php
echo html_entity_decode(
    html_entity_decode($r['titulo'], ENT_QUOTES | ENT_HTML5, 'UTF-8'),
    ENT_QUOTES | ENT_HTML5,
    'UTF-8'
);
?>
                                        </a>

                                        <span class="reporte-client">
                                            <svg viewBox="0 0 24 24" fill="none" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="2"></rect><circle cx="8" cy="10" r="2"></circle><path d="M5.5 16c.7-1.7 1.8-2.6 3.2-2.6 1.4 0 2.5.9 3.2 2.6"></path><path d="M14 9h4"></path><path d="M14 13h4"></path></svg>
                                            <?php echo htmlspecialchars($r['cliente'], ENT_QUOTES, 'UTF-8'); ?>
                                        </span>
                                    </div>

                                    <div class="reporte-links">

                                        <a href="#" class="reporte-link boletin-personalizado" data-reporte="<?php echo intval($r['id']); ?>" data-cliente="<?php echo intval($r['cliente_id']); ?>" data-cliente-nombre="<?php echo htmlspecialchars($r['cliente'], ENT_QUOTES, 'UTF-8'); ?>" onclick="return abrirBoletinPersonalizado(<?php echo intval($r['id']); ?>, <?php echo htmlspecialchars(json_encode($r['cliente'], JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8'); ?>);" title="Generar boletín personalizado" aria-label="Generar boletín personalizado">
                                            <svg viewBox="0 0 24 24" fill="none" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 3h11l3 3v15H5z"></path><path d="M16 3v4h4"></path><path d="M8 11h8"></path><path d="M8 15h8"></path><path d="M8 19h5"></path></svg>
                                        </a>
                                        <a href="#" class="reporte-link abrir-reporte-publico" data-reporte="<?php echo intval($r['id']); ?>" title="Abrir en una pestaña nueva" aria-label="Abrir en una pestaña nueva">
                                            <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 3h7v7"></path><path d="M10 14 21 3"></path><path d="M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5"></path></svg>
                                        </a>

                                        <a href="#" class="reporte-link copiar-enlace-reporte" data-reporte="<?php echo intval($r['id']); ?>" title="Copiar enlace" aria-label="Copiar enlace">
                                            <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg>
                                        </a>

                                        <a href="modulos/exportar_reporte_excel.php?reporte=<?php echo intval($r['id']); ?>" class="reporte-link" title="Descargar reporte Excel" aria-label="Descargar reporte Excel">
                                            <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v12"></path><path d="m7 10 5 5 5-5"></path><path d="M5 21h14"></path></svg>
                                        </a>
                                    </div>
                                </div>
                            </div>

                            <div class="reporte-count">
                                <h1><?php echo intval($r['total_notas']); ?></h1>
                                <small><?php echo intval($r['total_notas']) == 1 ? 'NOTICIA' : 'NOTICIAS'; ?></small>
                            </div>

                        </div>

                    </article>
                <?php } ?>
                
                
                <?php } else { ?>

<div class="reportes-detalle">

    <div class="reportes-detalle-cabecera">

        <a href="dashboard_superadmin.php?modulo=reportes" class="reportes-detalle-volver">
            <span>←</span>
            <span>Volver a reportes</span>
        </a>

        <h1 class="reportes-detalle-titulo">
            <?php
echo html_entity_decode(
    html_entity_decode($titulo_reporte_detalle, ENT_QUOTES | ENT_HTML5, 'UTF-8'),
    ENT_QUOTES | ENT_HTML5,
    'UTF-8'
);
?>
        </h1>

        <p class="reportes-detalle-cliente">
            Cliente:
            <strong><?php echo htmlspecialchars($nombre_cliente_detalle, ENT_QUOTES, 'UTF-8'); ?></strong>
        </p>

        <div class="reportes-detalle-botones">
            <button type="button" id="btnEditarInformacionReporte" class="reportes-detalle-boton editar">✎ Editar información</button>
            <button
    type="button"
    id="btnBloquearDetalle"
    data-reporte="<?php echo intval($reporte_id_detalle); ?>"
    data-accion="<?php echo $estado_acceso_detalle === 'bloqueado' ? 'desbloquear' : 'bloquear'; ?>"
    class="reportes-detalle-boton bloquear">

    🔒
    <?php echo $estado_acceso_detalle === 'bloqueado' ? 'Desbloquear' : 'Bloquear'; ?>

</button>
            <button
                type="button"
                id="btnVistaPublicaReporte"
                data-reporte="<?php echo intval($reporte_id_detalle); ?>"
                class="reportes-detalle-boton secundario">
                ◉ Vista Pública
            </button>
            <a href="modulos/exportar_reporte_excel.php?reporte=<?php echo intval($reporte_id_detalle); ?>" class="reportes-detalle-boton secundario">▧ Exportar Excel</a>
        </div>

    </div>

    <div id="modalEditarReporte" class="reportes-modal-editar" aria-hidden="true">
        <div class="reportes-modal-panel" role="dialog" aria-modal="true" aria-labelledby="tituloModalEditarReporte">
            <div class="reportes-modal-cabecera">
                <h3 id="tituloModalEditarReporte">Editar información del reporte</h3>
                <button type="button" id="cerrarModalEditarReporte" class="reportes-modal-cerrar" aria-label="Cerrar">×</button>
            </div>
            <div class="reportes-modal-cuerpo">
                <div class="reportes-modal-campo">
                    <label for="editarReporteTitulo">Título</label>
                    <input type="text" id="editarReporteTitulo" maxlength="255" value="<?php echo htmlspecialchars($titulo_reporte_detalle, ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="reportes-modal-campo">
                    <label for="editarReporteCliente">Cliente</label>
                    <select id="editarReporteCliente">
                        <option value="">Seleccione un cliente</option>
                        <?php foreach ($lista_clientes as $cliente_modal) { ?>
                            <option value="<?php echo intval($cliente_modal['id']); ?>" <?php echo intval($cliente_modal['id']) === intval($filaReporteDetalle['cliente_id'] ?? 0) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cliente_modal['nombre'], ENT_QUOTES, 'UTF-8'); ?>
                            </option>
                        <?php } ?>
                    </select>
                </div>
            </div>
            <div class="reportes-modal-acciones">
                <button type="button" id="cancelarEditarReporte" class="reportes-modal-cancelar">Cancelar</button>
                <button type="button" id="guardarEditarReporte" class="reportes-modal-guardar">Guardar cambios</button>
            </div>
        </div>
    </div>

    <div class="reportes-detalle-cuerpo">

        <p class="reportes-detalle-resumen">
            Este reporte contiene <?php echo count($noticias_cliente); ?>
            <?php echo count($noticias_cliente) === 1 ? 'noticia' : 'noticias'; ?> en total.
        </p>

        <?php if (count($noticias_cliente) === 0) { ?>
            <div class="reportes-detalle-vacio">
                Este reporte todavía no tiene noticias vinculadas.
            </div>
        <?php } ?>

        <?php foreach ($noticias_cliente as $n) { ?>
            <?php
                $descripcion_bruta = (string)($n["descripcion"] ?? "");
                $datos_extra_noticia = array();

                if (preg_match('/__DATOS_NOTICIA__\:([A-Za-z0-9+\/=]+)/', $descripcion_bruta, $coincidencia_extra)) {
                    $json_extra = base64_decode($coincidencia_extra[1], true);

                    if ($json_extra !== false) {
                        $extra_decodificado = json_decode($json_extra, true);

                        if (is_array($extra_decodificado)) {
                            $datos_extra_noticia = $extra_decodificado;
                        }
                    }
                }

                $descripcion_visible = preg_replace('/\n\n__DATOS_NOTICIA__\:[A-Za-z0-9+\/=]+/', '', $descripcion_bruta);
                $descripcion_visible = preg_replace('/\n\nEtiquetas\:.*$/s', '', $descripcion_visible);

                /* Usar primero la región real guardada en la noticia. */
                $departamento_noticia = trim((string)($n["region"] ?? ""));

                if ($departamento_noticia === "") {
                    $departamento_noticia = trim((string)($datos_extra_noticia["departamento"] ?? ""));
                }

                $localidad_noticia = trim((string)($datos_extra_noticia["localidad"] ?? ""));

                $partes_medio = array_map('trim', explode(" / ", (string)($n["subtipo_medio"] ?? "")));
                $nombre_medio_noticia = trim((string)($n["subtipo_medio"] ?? ""));
                $ubicacion_noticia = "";

                if (count($partes_medio) >= 4) {
                    if ($departamento_noticia === "") {
                        $departamento_noticia = $partes_medio[0];
                    }

                    if ($localidad_noticia === "") {
                        $localidad_noticia = $partes_medio[1];
                    }

                    $nombre_medio_noticia = $partes_medio[3];
                }

                $partes_ubicacion = array_filter(array($departamento_noticia, $localidad_noticia));
                $ubicacion_noticia = implode(", ", array_unique($partes_ubicacion));

                if ($ubicacion_noticia === "") {
                    $ubicacion_noticia = "Ubicación no registrada";
                }

                if ($nombre_medio_noticia === "") {
                    $nombre_medio_noticia = "Medio no registrado";
                }

                $tipo_medio_noticia = strtoupper(trim((string)($n["tipo_medio"] ?? "NOTICIA")));

                /* La tarifa sale de la columna real notas.tarifa.
                   No se vuelve a calcular por cantidad de caracteres. */
                $tarifa_noticia = tarifaIndividualReporte($n);

                $fecha_noticia = !empty($n["fecha_nota"])
                    ? date("d/m/Y", strtotime($n["fecha_nota"]))
                    : "";
            ?>

            <article class="reportes-noticia-card">

                <div class="reportes-noticia-contenido">

                    <div class="reportes-noticia-meta">
                        <span>◷ <?php echo htmlspecialchars($fecha_noticia, ENT_QUOTES, 'UTF-8'); ?></span>
                        <span>⌖ <?php echo htmlspecialchars($ubicacion_noticia, ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>

                    <a
                        href="#"
                        class="reportes-noticia-titulo abrirNoticiaPublica"
                        data-id="<?php echo intval($n["id"]); ?>">

                        <?php
echo html_entity_decode(
    html_entity_decode($n["titulo"], ENT_QUOTES | ENT_HTML5, 'UTF-8'),
    ENT_QUOTES | ENT_HTML5,
    'UTF-8'
);
?>

                    </a>

                    <div class="reportes-noticia-medio">
                        <span class="reportes-noticia-tipo">▦ <?php echo htmlspecialchars($tipo_medio_noticia, ENT_QUOTES, 'UTF-8'); ?></span>
                        <span class="reportes-noticia-separador"></span>
                        <span><?php echo htmlspecialchars($nombre_medio_noticia, ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>

                </div>

                <div class="reportes-noticia-tarifa">
                    <small>Tarifa</small>
                    <strong>S/<?php echo number_format($tarifa_noticia, 2); ?></strong>
                </div>

                <button
                    type="button"
                    class="reportes-noticia-estado btn-quitar-noticia-reporte"
                    data-reporte="<?php echo intval($reporte_id_detalle); ?>"
                    data-noticia="<?php echo intval($n["id"]); ?>"
                    title="Quitar noticia del reporte"
                    aria-label="Quitar noticia del reporte">
                    <span>−</span>
                </button>

            </article>

        <?php } ?>

    </div>

</div>

<?php } ?>
                

            </div>

        </div>

    </section>

</div>



<div id="modalBoletinPersonalizado" class="boletin-modal" aria-hidden="true">
  <div class="boletin-panel" role="dialog" aria-modal="true" aria-labelledby="tituloModalBoletin">
    <div class="boletin-modal-cabecera">
      <h2 id="tituloModalBoletin">Generar boletín personalizado</h2>
      <button type="button" id="cerrarModalBoletin" class="boletin-cerrar" aria-label="Cerrar">×</button>
    </div>
    <div class="boletin-contenido">
      <div class="boletin-controles">
        <div class="boletin-campo">
          <label>Cliente</label>
          <div id="boletinClienteNombre" class="boletin-cliente-fijo">—</div>
        </div>
        <div class="boletin-campo">
          <label for="boletinFecha">Fecha del boletín</label>
          <input type="date" id="boletinFecha" value="<?php echo date('Y-m-d'); ?>">
        </div>
        <div class="boletin-campo">
          <label>Color principal</label>
          <div class="boletin-color-fila"><input type="color" id="boletinColor" value="#d92f2f"><input type="text" id="boletinColorTexto" value="#d92f2f" maxlength="7"></div>
        </div>
        <button type="button" id="generarBoletin" class="boletin-generar">GENERAR BOLETÍN</button>
        <div id="boletinEstado" class="boletin-estado"></div>
        <div id="boletinAcciones" class="boletin-acciones">
          <button type="button" id="boletinDescargarPdf" class="boletin-accion pdf">📄 DESCARGAR PDF</button>
          <button type="button" id="boletinCopiarEnlace" class="boletin-accion enlace">🔗 COPIAR ENLACE</button>
        </div>
        <div id="boletinAvisoCopiado" class="boletin-aviso-copiado"></div>
      </div>
      <div class="boletin-vista-wrap">
        <div id="boletinVista" class="boletin-vista">
          <div class="boletin-vacio">Pulsa <strong>GENERAR BOLETÍN</strong> para cargar todas las noticias de esta tarjeta.</div>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="assets/js/boletin_personalizado.js?v=7"></script>

<script>
(function(){
var clientesReportes=<?php echo json_encode($lista_clientes); ?>;
var txt=document.getElementById("reportes_cliente_buscar"),hidden=document.getElementById("reportes_cliente"),lista=document.getElementById("reportes_cliente_resultados");
function cerrarClientes(){if(lista){lista.style.display="none";}}
function buscarClientes(){if(!txt||!hidden||!lista){return;}var t=txt.value.toLowerCase().replace(/^\s+|\s+$/g,""),e=0;lista.innerHTML="";hidden.value="";if(t===""){cerrarClientes();return;}for(var i=0;i<clientesReportes.length;i++){var cliente=clientesReportes[i],c=String(cliente.nombre || "");if(c.toLowerCase().indexOf(t)!==-1){e++;var item=document.createElement("div");item.className="reportes-cliente-item";item.appendChild(document.createTextNode(c));item.onclick=(function(n,id){return function(){txt.value=n;hidden.value=id;cerrarClientes();};})(c,cliente.id);lista.appendChild(item);}}if(e===0){var v=document.createElement("div");v.className="reportes-cliente-vacio";v.appendChild(document.createTextNode("No se encontraron clientes."));lista.appendChild(v);}lista.style.display="block";}
if(txt){txt.onkeyup=buscarClientes;}

var d=document.getElementById("reportes_date_display"),p=document.getElementById("reportes_calendar_popup"),days=document.getElementById("reportes_calendar_days"),prev=document.getElementById("reportes_mes_anterior"),next=document.getElementById("reportes_mes_siguiente"),tfecha=document.getElementById("reportes_date_text"),ini=document.getElementById("reportes_fecha_inicio"),fin=document.getElementById("reportes_fecha_fin"),smes=document.getElementById("reportes_selector_mes"),sanio=document.getElementById("reportes_selector_anio"),rdesde=document.getElementById("reportes_rango_desde"),rhasta=document.getElementById("reportes_rango_hasta"),bhoy=document.getElementById("reportes_cal_hoy"),blim=document.getElementById("reportes_cal_limpiar"),bapl=document.getElementById("reportes_cal_aplicar"),blf=document.getElementById("reportes_limpiar_filtros");
var meses=["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],vista=new Date(),fini=null,ffin=null;vista=new Date(vista.getFullYear(),vista.getMonth(),1);
function dos(n){return n<10?"0"+n:String(n);}function iso(f){return f.getFullYear()+"-"+dos(f.getMonth()+1)+"-"+dos(f.getDate());}function vis(f){return dos(f.getDate())+"/"+dos(f.getMonth()+1)+"/"+f.getFullYear();}function sh(f){return new Date(f.getFullYear(),f.getMonth(),f.getDate());}function misma(a,b){return !!a&&!!b&&a.getFullYear()===b.getFullYear()&&a.getMonth()===b.getMonth()&&a.getDate()===b.getDate();}
function cerrarCal(){if(p){p.className="reportes-calendar-popup";}if(d){d.className="reportes-date-display";}}
function llenar(){if(smes&&smes.options.length===0){for(var m=0;m<12;m++){var o=document.createElement("option");o.value=m;o.text=meses[m];smes.appendChild(o);}}if(sanio&&sanio.options.length===0){var a0=new Date().getFullYear();for(var a=1970;a<=a0+10;a++){var y=document.createElement("option");y.value=a;y.text=a;sanio.appendChild(y);}}}
function sync(){if(smes){smes.value=vista.getMonth();}if(sanio){sanio.value=vista.getFullYear();}}
function resumen(){if(rdesde){rdesde.textContent=fini?vis(fini):"—";}if(rhasta){rhasta.textContent=ffin?vis(ffin):"—";}}
function aplicarTexto(){if(!fini){tfecha.innerHTML="<em>Seleccionar fecha</em>";ini.value="";fin.value="";resumen();return;}ini.value=iso(fini);if(!ffin||misma(fini,ffin)){tfecha.textContent=vis(fini);fin.value=iso(fini);}else{tfecha.textContent=vis(fini)+" - "+vis(ffin);fin.value=iso(ffin);}resumen();}
function elegir(f){f=sh(f);if(!fini||ffin){fini=f;ffin=null;}else{ffin=f;if(ffin<fini){var tmp=fini;fini=ffin;ffin=tmp;}}resumen();render();}
function render(){if(!days){return;}llenar();sync();days.innerHTML="";var primero=new Date(vista.getFullYear(),vista.getMonth(),1),ultimo=new Date(vista.getFullYear(),vista.getMonth()+1,0).getDate(),esp=(primero.getDay()+6)%7;for(var v=0;v<esp;v++){var ev=document.createElement("div");ev.className="reportes-day empty";days.appendChild(ev);}for(var dia=1;dia<=ultimo;dia++){var f=new Date(vista.getFullYear(),vista.getMonth(),dia),c=document.createElement("div");c.className="reportes-day";c.textContent=dia;if(misma(f,fini)&&misma(f,ffin)){c.className+=" same";}else if(misma(f,fini)){c.className+=" start";}else if(misma(f,ffin)){c.className+=" end";}else if(fini&&ffin&&sh(f)>fini&&sh(f)<ffin){c.className+=" range";}c.onclick=(function(ff){return function(e){e.stopPropagation();elegir(ff);};})(f);days.appendChild(c);}resumen();}
if(d){d.onclick=function(e){e.stopPropagation();var abrir=p.className.indexOf("show")===-1;p.className=abrir?"reportes-calendar-popup show":"reportes-calendar-popup";d.className=abrir?"reportes-date-display active":"reportes-date-display";if(abrir){render();}};}
if(p){p.onclick=function(e){e.stopPropagation();};}
if(prev){prev.onclick=function(e){e.stopPropagation();vista=new Date(vista.getFullYear(),vista.getMonth()-1,1);render();};}
if(next){next.onclick=function(e){e.stopPropagation();vista=new Date(vista.getFullYear(),vista.getMonth()+1,1);render();};}
if(smes){smes.onchange=function(e){e.stopPropagation();vista=new Date(vista.getFullYear(),parseInt(smes.value,10),1);render();};}
if(sanio){sanio.onchange=function(e){e.stopPropagation();vista=new Date(parseInt(sanio.value,10),vista.getMonth(),1);render();};}
if(bhoy){bhoy.onclick=function(e){e.stopPropagation();var h=new Date();fini=sh(h);ffin=sh(h);vista=new Date(h.getFullYear(),h.getMonth(),1);render();};}
if(blim){blim.onclick=function(e){e.stopPropagation();fini=null;ffin=null;ini.value="";fin.value="";tfecha.innerHTML="<em>Seleccionar fecha</em>";render();};}
if(bapl){bapl.onclick=function(e){e.stopPropagation();if(fini&&!ffin){ffin=sh(fini);}aplicarTexto();cerrarCal();};}
if(blf){blf.onclick=function(){window.location.href="dashboard_superadmin.php?modulo=reportes";};}
document.onclick=function(e){e=e||window.event;var n=e.target||e.srcElement,dentroC=false,dentroF=false;while(n){var cl=n.className?String(n.className):"";if(cl.indexOf("reportes-cliente-buscador")!==-1){dentroC=true;}if(cl.indexOf("reportes-date-box")!==-1||cl.indexOf("reportes-calendar-popup")!==-1){dentroF=true;}n=n.parentNode;}if(!dentroC){cerrarClientes();}if(!dentroF){cerrarCal();}};
llenar();render();
})();

/*=========================
ACCIONES DE REPORTES EN BASE DE DATOS
=========================*/

var btnAccionesReportes = document.getElementById("btnAccionesReportes");
var cajaAccionesReportes = document.querySelector(".reportes-actions-box");
var btnSeleccionarReportes = document.getElementById("btnSeleccionarReportes");
var btnArchivarReportes = document.getElementById("btnArchivarReportes");
var btnEliminarReportes = document.getElementById("btnEliminarReportes");
var btnRestaurarReportes = document.getElementById("btnRestaurarReportes");
var btnEliminarDefinitivamenteReportes = document.getElementById("btnEliminarDefinitivamenteReportes");
var btnArchivadosReportes = document.getElementById("btnArchivadosReportes");
var btnEliminadosReportes = document.getElementById("btnEliminadosReportes");
var btnVolverReportes = document.getElementById("btnVolverReportes");
var checksReportes = document.querySelectorAll(".reporte-check");
var viendoArchivadosReportes = <?php echo $ver_archivados ? 'true' : 'false'; ?>;
var viendoEliminadosReportes = <?php echo $ver_eliminados ? 'true' : 'false'; ?>;
var csrfReportes = <?php echo json_encode(isset($csrf_token) ? $csrf_token : ''); ?>;

function checksVisiblesReportes(){
    return Array.prototype.filter.call(checksReportes, function(check){
        var tarjeta = check.closest(".reporte-item");
        return tarjeta && !tarjeta.classList.contains("reportes-oculto");
    });
}

function idsSeleccionadosReportes(){
    return checksVisiblesReportes()
        .filter(function(check){ return check.checked; })
        .map(function(check){ return check.value; });
}

function actualizarBotonesReportes(){
    var visibles = checksVisiblesReportes();
    var seleccionados = idsSeleccionadosReportes().length;
    var todosMarcados = visibles.length > 0 && visibles.every(function(check){ return check.checked; });

    if(btnAccionesReportes){
        btnAccionesReportes.disabled = seleccionados === 0;
        btnAccionesReportes.classList.toggle("disabled", seleccionados === 0);
    }

    if(btnSeleccionarReportes){
        btnSeleccionarReportes.textContent = todosMarcados
            ? "DESELECCIONAR TODOS"
            : "SELECCIONAR TODOS";
    }

    if(seleccionados === 0 && cajaAccionesReportes){
        cajaAccionesReportes.classList.remove("open");
    }
}

function ejecutarAccionReportes(accion){
    var ids = idsSeleccionadosReportes();

    if(ids.length === 0){
        alert("Selecciona al menos un reporte.");
        return;
    }

    var mensaje = "¿Deseas completar esta acción?";

    if(accion === "eliminar"){
        mensaje = "¿Deseas enviar los reportes seleccionados a Eliminados?";
    }else if(accion === "desarchivar"){
        mensaje = "¿Deseas desarchivar los reportes seleccionados?";
    }else if(accion === "archivar"){
        mensaje = "¿Deseas archivar los reportes seleccionados?";
    }else if(accion === "restaurar"){
        mensaje = "¿Deseas restaurar los reportes seleccionados?";
    }else if(accion === "eliminar_definitivamente"){
        mensaje = "¿Deseas eliminar definitivamente los reportes seleccionados? Esta acción no se puede deshacer.";
    }

    if(!confirm(mensaje)){
        return;
    }

    var datos = new FormData();
    datos.append("accion", accion);
    datos.append("csrf_token", csrfReportes);

    ids.forEach(function(id){
        datos.append("ids[]", id);
    });

    fetch("modulos/reportes_acciones.php", {
        method: "POST",
        body: datos,
        credentials: "same-origin"
    })
    .then(function(respuesta){
        return respuesta.json().then(function(datosRespuesta){
            return { ok: respuesta.ok, datos: datosRespuesta };
        });
    })
    .then(function(resultado){
        if(!resultado.ok || !resultado.datos.ok){
            throw new Error(resultado.datos.mensaje || "No se pudo completar la operación.");
        }

        window.location.reload();
    })
    .catch(function(error){
        alert(error.message || "Ocurrió un error al actualizar los reportes.");
    });
}

checksReportes.forEach(function(check){
    check.addEventListener("change", actualizarBotonesReportes);
});

if(btnSeleccionarReportes){
    btnSeleccionarReportes.addEventListener("click", function(){
        var visibles = checksVisiblesReportes();
        var todosMarcados = visibles.length > 0 && visibles.every(function(check){ return check.checked; });

        visibles.forEach(function(check){
            check.checked = !todosMarcados;
        });

        actualizarBotonesReportes();
    });
}

if(btnAccionesReportes && cajaAccionesReportes){
    btnAccionesReportes.addEventListener("click", function(evento){
        evento.preventDefault();
        evento.stopPropagation();

        if(!btnAccionesReportes.disabled){
            cajaAccionesReportes.classList.toggle("open");
        }
    });

    cajaAccionesReportes.addEventListener("click", function(evento){
        evento.stopPropagation();
    });
}

if(btnArchivarReportes){
    btnArchivarReportes.addEventListener("click", function(evento){
        evento.preventDefault();
        evento.stopPropagation();
        ejecutarAccionReportes(viendoArchivadosReportes ? "desarchivar" : "archivar");
    });
}

if(btnEliminarReportes){
    btnEliminarReportes.addEventListener("click", function(evento){
        evento.preventDefault();
        evento.stopPropagation();
        ejecutarAccionReportes("eliminar");
    });
}

if(btnRestaurarReportes){
    btnRestaurarReportes.addEventListener("click", function(evento){
        evento.preventDefault();
        evento.stopPropagation();
        ejecutarAccionReportes("restaurar");
    });
}

if(btnEliminarDefinitivamenteReportes){
    btnEliminarDefinitivamenteReportes.addEventListener("click", function(evento){
        evento.preventDefault();
        evento.stopPropagation();
        ejecutarAccionReportes("eliminar_definitivamente");
    });
}

if(btnArchivadosReportes){
    btnArchivadosReportes.addEventListener("click", function(){
        window.location.href = btnArchivadosReportes.getAttribute("data-url");
    });
}

if(btnEliminadosReportes){
    btnEliminadosReportes.addEventListener("click", function(){
        window.location.href = btnEliminadosReportes.getAttribute("data-url");
    });
}

if(btnVolverReportes){
    btnVolverReportes.addEventListener("click", function(){
        window.location.href = btnVolverReportes.getAttribute("data-url");
    });
}

document.addEventListener("click", function(){
    if(cajaAccionesReportes){
        cajaAccionesReportes.classList.remove("open");
    }
});

actualizarBotonesReportes();

document.querySelectorAll(".abrirNoticiaPublica").forEach(function(item){

    item.addEventListener("click",function(e){

        e.preventDefault();

        var id=this.dataset.id;

        fetch("ajax_generar_link_noticia.php",{

            method:"POST",

            headers:{
                "Content-Type":"application/x-www-form-urlencoded"
            },

            body:"id="+encodeURIComponent(id)

        })

        .then(r=>r.json())

        .then(function(resp){

            if(resp.ok){

                window.open(resp.url,"_blank");

            }else{

                alert(resp.mensaje);

            }

        });

    });

});
    
/*==========================================
BOTONES ↗ Y 🔗 DEL LISTADO DE REPORTES
==========================================*/

function generarEnlacePublicoReporte(idReporte){

    var datos = new FormData();
    datos.append("id", idReporte);

    return fetch("ajax_generar_link_reporte.php",{

        method:"POST",
        body:datos,
        credentials:"same-origin"

    })
    .then(function(r){

        return r.json();

    });

}


/*-------------------------
ABRIR
-------------------------*/

document.querySelectorAll(".abrir-reporte-publico").forEach(function(boton){

    boton.addEventListener("click",function(e){

        e.preventDefault();

        var id=this.dataset.reporte;

        generarEnlacePublicoReporte(id)

        .then(function(resp){

            if(resp.ok){

                window.open(resp.url,"_blank");

            }else{

                alert(resp.mensaje);

            }

        });

    });

});


/*-------------------------
COPIAR ENLACE
-------------------------*/

document.querySelectorAll(".copiar-enlace-reporte").forEach(function(boton){

    boton.addEventListener("click",function(e){

        e.preventDefault();

        var id=this.dataset.reporte;

        generarEnlacePublicoReporte(id)

        .then(function(resp){

            if(!resp.ok){

                alert(resp.mensaje);
                return;

            }

            navigator.clipboard.writeText(resp.url)

            .then(function(){


            });

        });

    });

});
    
    
/*=========================
VISTA PÚBLICA DEL REPORTE
=========================*/

var btnVistaPublicaReporte = document.getElementById("btnVistaPublicaReporte");

if(btnVistaPublicaReporte){

    btnVistaPublicaReporte.addEventListener("click",function(){

        generarEnlacePublicoReporte(btnVistaPublicaReporte.dataset.reporte)

        .then(function(resp){

            if(resp.ok){

                window.open(resp.url,"_blank");

            }else{

                alert(resp.mensaje);

            }

        });

    });

}

/*=========================
QUITAR NOTICIA DEL REPORTE
=========================*/
document.querySelectorAll(".btn-quitar-noticia-reporte").forEach(function(boton){
    boton.addEventListener("click", function(){
        var reporteId = boton.getAttribute("data-reporte");
        var noticiaId = boton.getAttribute("data-noticia");

        if(!reporteId || !noticiaId){
            alert("No se pudo identificar la noticia o el reporte.");
            return;
        }

        if(!confirm("¿Deseas quitar esta noticia del reporte?")){
            return;
        }

        var datos = new FormData();
        datos.append("accion", "quitar_noticia");
        datos.append("csrf_token", csrfReportes);
        datos.append("ids[]", reporteId);
        datos.append("nota_id", noticiaId);

        boton.disabled = true;

        fetch("modulos/reportes_acciones.php", {
            method: "POST",
            body: datos,
            credentials: "same-origin"
        })
        .then(function(respuesta){
            return respuesta.json().then(function(datosRespuesta){
                return { ok: respuesta.ok, datos: datosRespuesta };
            });
        })
        .then(function(resultado){
            if(!resultado.ok || !resultado.datos.ok){
                throw new Error(resultado.datos.mensaje || "No se pudo quitar la noticia del reporte.");
            }
            window.location.reload();
        })
        .catch(function(error){
            boton.disabled = false;
            alert(error.message || "Ocurrió un error al quitar la noticia del reporte.");
        });
    });
});

/*=========================
EDITAR INFORMACIÓN DEL REPORTE
=========================*/
var btnEditarInformacionReporte = document.getElementById("btnEditarInformacionReporte");
var modalEditarReporte = document.getElementById("modalEditarReporte");
var cerrarModalEditarReporte = document.getElementById("cerrarModalEditarReporte");
var cancelarEditarReporte = document.getElementById("cancelarEditarReporte");
var guardarEditarReporte = document.getElementById("guardarEditarReporte");
var editarReporteTitulo = document.getElementById("editarReporteTitulo");
var editarReporteCliente = document.getElementById("editarReporteCliente");

function abrirModalEditarReporte(){
    if(!modalEditarReporte){ return; }
    modalEditarReporte.classList.add("abierto");
    modalEditarReporte.setAttribute("aria-hidden", "false");
    if(editarReporteTitulo){
        setTimeout(function(){ editarReporteTitulo.focus(); editarReporteTitulo.select(); }, 50);
    }
}

function ocultarModalEditarReporte(){
    if(!modalEditarReporte){ return; }
    modalEditarReporte.classList.remove("abierto");
    modalEditarReporte.setAttribute("aria-hidden", "true");
}

if(btnEditarInformacionReporte){ btnEditarInformacionReporte.addEventListener("click", abrirModalEditarReporte); }
if(cerrarModalEditarReporte){ cerrarModalEditarReporte.addEventListener("click", ocultarModalEditarReporte); }
if(cancelarEditarReporte){ cancelarEditarReporte.addEventListener("click", ocultarModalEditarReporte); }
if(modalEditarReporte){
    modalEditarReporte.addEventListener("click", function(e){
        if(e.target === modalEditarReporte){ ocultarModalEditarReporte(); }
    });
}
document.addEventListener("keydown", function(e){
    if(e.key === "Escape" && modalEditarReporte && modalEditarReporte.classList.contains("abierto")){
        ocultarModalEditarReporte();
    }
});

if(guardarEditarReporte){
    guardarEditarReporte.addEventListener("click", function(){
        var titulo = editarReporteTitulo ? editarReporteTitulo.value.trim() : "";
        var cliente = editarReporteCliente ? editarReporteCliente.value : "";

        if(titulo === ""){
            alert("Escribe el título del reporte.");
            if(editarReporteTitulo){ editarReporteTitulo.focus(); }
            return;
        }
        if(cliente === ""){
            alert("Selecciona el cliente del reporte.");
            if(editarReporteCliente){ editarReporteCliente.focus(); }
            return;
        }

        var datos = new FormData();
        datos.append("accion", "editar_informacion");
        datos.append("csrf_token", csrfReportes);
        datos.append("ids[]", <?php echo intval($reporte_id_detalle); ?>);
        datos.append("titulo", titulo);
        datos.append("cliente_id", cliente);

        guardarEditarReporte.disabled = true;
        guardarEditarReporte.textContent = "Guardando...";

        fetch("modulos/reportes_acciones.php", {
            method:"POST",
            body:datos,
            credentials:"same-origin"
        })
        .then(function(r){
            return r.json().then(function(j){ return {ok:r.ok, data:j}; });
        })
        .then(function(resp){
            if(!resp.ok || !resp.data.ok){
                throw new Error(resp.data.mensaje || "No se pudo actualizar el reporte.");
            }
            window.location.href = "dashboard_superadmin.php?modulo=reportes&reporte_id=<?php echo intval($reporte_id_detalle); ?>";
        })
        .catch(function(error){
            alert(error.message || "No se pudo actualizar el reporte.");
            guardarEditarReporte.disabled = false;
            guardarEditarReporte.textContent = "Guardar cambios";
        });
    });
}

/*=========================
BLOQUEAR / DESBLOQUEAR REPORTE
=========================*/

var btnBloquearDetalle = document.getElementById("btnBloquearDetalle");

if(btnBloquearDetalle){

    btnBloquearDetalle.addEventListener("click",function(){

        var datos = new FormData();

        datos.append(
            "accion",
            btnBloquearDetalle.dataset.accion
        );

        datos.append(
            "csrf_token",
            csrfReportes
        );

        datos.append(
            "ids[]",
            btnBloquearDetalle.dataset.reporte
        );

        fetch(
            "modulos/reportes_acciones.php",
            {
                method:"POST",
                body:datos,
                credentials:"same-origin"
            }
        )
        .then(r=>r.json())
        .then(function(resp){

            if(resp.ok){

                location.reload();

            }else{

                alert(resp.mensaje);

            }

        });

    });

}

/* La lógica del boletín se carga únicamente desde assets/js/boletin_personalizado.js. */

</script>