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

@ini_set('display_errors', 1);
@error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_OFF);

$ID = isset($_GET['ID']) ? (int)$_GET['ID'] : 0;

$titulo = $cat = $img = $bajada = $fecha = $texto = '';
$tag1 = $tag2 = $tag3 = $tag4 = $tag5 = '';

$ok_insert = false;
$error_msg = '';

/* ================================================================
   SOLO STR_REPLACE: mojibake "Ã¡" -> entidades "&aacute;"
   ================================================================ */
function mojibake_a_acute($s) {
    return str_replace(
        array(
            'Ã¡','Ã©','Ã­','Ã³','Ãº',
            'Ã','Ã','Ã','Ã','Ã',
            'Ã±','Ã',
            'Ã¼','Ã'
        ),
        array(
            '&aacute;','&eacute;','&iacute;','&oacute;','&uacute;',
            '&Aacute;','&Eacute;','&Iacute;','&Oacute;','&Uacute;',
            '&ntilde;','&Ntilde;',
            '&uuml;','&Uuml;'
        ),
        $s
    );
}

/* Título máx 255 (en ENTIDADES). Evita cortar "&oacute;" a la mitad */
function cortar_255_entidades($s) {
    if ($s === '' || strlen($s) <= 255) return $s;

    $cut = substr($s, 0, 255);

    $posAmp = strrpos($cut, '&');
    if ($posAmp !== false) {
        $posSemi = strrpos($cut, ';');
        if ($posSemi === false || $posSemi < $posAmp) {
            $cut = substr($cut, 0, $posAmp);
        }
    }
    return rtrim($cut);
}

try {
    if ($ID <= 0) throw new Exception('ID inválido.');

    /* ── 1) CONEXIÓN ORIGEN ── */
    $db_local = @new mysqli('localhost', 'almanoti_usuarios_rn', 'T96QG821J7ao', 'almanoti_base');
    if ($db_local->connect_errno) {
        throw new Exception('No se pudo conectar a almanoti_base: ' . $db_local->connect_error);
    }
    $db_local->set_charset('utf8mb4');

    $host2      = $host2      ?? '';
    $usuario2   = $usuario2   ?? '';
    $contra2    = $contra2    ?? '';
    $basedatos2 = $basedatos2 ?? '';

    if ($host2 !== '' && $usuario2 !== '' && $basedatos2 !== '') {
        $db_src = @new mysqli($host2, $usuario2, $contra2, $basedatos2);
        if ($db_src->connect_errno) {
            throw new Exception('No se pudo conectar a basedatos2: ' . $db_src->connect_error);
        }
        $db_src->set_charset('utf8mb4');
    } else {
        $db_src = $db_local;
    }

    /* ── 2) LEO LA NOTICIA ── */
    $sql = "SELECT ID, titulo, cat, img, bajada, fecha, texto
            FROM `noticias`
            WHERE ID = ?
            LIMIT 1";
    $st = $db_src->prepare($sql);
    if (!$st) throw new Exception('Prepare SELECT falló: ' . $db_src->error);

    $st->bind_param('i', $ID);
    $st->execute();
    $rs = $st->get_result();

    if ($row = $rs->fetch_assoc()) {
        $ID     = (int)$row['ID'];
        $titulo = (string)$row['titulo'];
        $cat    = (string)$row['cat'];
        $img    = (string)$row['img'];
        $bajada = (string)$row['bajada'];
        $fecha  = (string)$row['fecha'];
        $texto  = (string)$row['texto'];
    } else {
        throw new Exception('No se encontró la noticia con ID=' . $ID);
    }
    $st->close();

    /* ── 3) SOLO REPLACE a ENTIDADES ── */
    $titulo_ins = mojibake_a_acute($titulo);
    $bajada_ins = mojibake_a_acute($bajada);
    $texto_ins  = mojibake_a_acute($texto);

    /* ── 4) TÍTULO MÁX 255 ── */
    $titulo_ins = cortar_255_entidades($titulo_ins);

    /* ── 5) CONEXIÓN DESTINO ── */
    $host      = $host      ?? '';
    $usuario   = $usuario   ?? '';
    $contra    = $contra    ?? '';
    $basedatos = $basedatos ?? '';

    $db_dest = @new mysqli($host, $usuario, $contra, $basedatos);
    if ($db_dest->connect_errno) {
        throw new Exception('No se pudo conectar a base destino: ' . $db_dest->connect_error);
    }
    $db_dest->set_charset('utf8mb4');

    $d = date('d');
    $m = date('m');
    $a = date('Y');

    /* ── 6) INSERT ── */
    $sqlIns = "INSERT INTO `notas`
    (`ID`,`titulo`,`bajada`,`texto`,`d`,`m`,`a`,`ver`,`foto`,`cat`,`cat2`,`cat3`,`cat4`,`cat5`,`destacado`,
     `tag1`,`tag2`,`tag3`,`tag4`,`tag5`,`fechapub`,`horapub`,`youtube`,`audio`, `visitas`, `home`, `carpetafoto`,
     `impresiones`, `html`, `ejemplo_marca_de_agua`, `time`, `date`, `mktime`, `ext_img`, `editor`, `des_cat`,
     `pie_foto`, `user`, `altfoto`, `titulofoto`, `detaca_modulo`)
    VALUES
    (NULL, ?, ?, ?, ?, ?, ?, 'si', ?, '0', '0', '0', '0', '0','no',
     ?, ?, ?, ?, ?, '0','0','','','0','si','','0','','','0','0','0','.jpg','0','0','','','','','0')";

    $st2 = $db_dest->prepare($sqlIns);
    if (!$st2) throw new Exception('Prepare INSERT falló: ' . $db_dest->error);

    $st2->bind_param(
        'ssssssssssss',
        $titulo_ins, $bajada_ins, $texto_ins,
        $d, $m, $a,
        $img,
        $tag1, $tag2, $tag3, $tag4, $tag5
    );

    $ok_insert = $st2->execute();
    if (!$ok_insert) {
        throw new Exception('INSERT falló: ' . $st2->error);
    }

    $st2->close();
    $db_dest->close();
    if ($db_src !== $db_local) $db_src->close();
    $db_local->close();

} catch (Throwable $e) {
    $error_msg = $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="description" content="Panel de Administracion">
    <meta name="author" content="<?php echo isset($nombresitio) ? htmlspecialchars($nombresitio, ENT_QUOTES, 'UTF-8') : ''; ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title><?php echo isset($nombresitio) ? htmlspecialchars($nombresitio, ENT_QUOTES, 'UTF-8') : ''; ?> - Panel de Administracion</title>

    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,600,800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">

    <style>
        *{ border-radius: 0!important; }
        body {
            background-color: #EBEBEB !important;
        }
        .btn, a, h1, h2, h3, h4, h5, h6, b {
            font-family: 'Montserrat', sans-serif;
        }
        .btn-primary { color: #fff !important; background-color: #0066FF; border-color: #0066FF; }
    </style>
</head>

<body>
<div class="container" style="background-color:#F1F2ED; padding:20px; margin-top:20px;">
    <div align="center">
        <p class="h5">LA NOTA</p>
        <br>

        <?php if ($ok_insert): ?>
            <div class="alert alert-success" style="max-width:900px;">
                <div><b>Título (lo que insertaste):</b></div>
                <div style="margin-top:8px;">
                    <?php
                        // Muestro "lindo" decodificando entidades para la vista
                        echo htmlspecialchars(html_entity_decode($titulo_ins, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
                    ?>
                </div>
                <div style="margin-top:12px;">FUE CARGADA CORRECTAMENTE</div>
            </div>

            <?php if ($img !== ''): ?>
                <img src="<?php echo htmlspecialchars($img, ENT_QUOTES, 'UTF-8'); ?>" style="max-width:600px"/><br><br>
            <?php endif; ?>

            <a class="btn btn-primary" href="notas.php">VOLVER</a>

        <?php else: ?>
            <div class="alert alert-danger" style="max-width:900px; text-align:left;">
                <b>NO SE PUDO CARGAR LA NOTA</b><br><br>
                <?php echo htmlspecialchars($error_msg, ENT_QUOTES, 'UTF-8'); ?>
            </div>
            <a class="btn btn-secondary" href="notas.php">VOLVER</a>
        <?php endif; ?>
    </div>
</div>
</body>
</html>