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

<?php
// Asegurar que MySQLi trabaje en UTF-8 (ideal utf8mb4)
if (isset($conn) && $conn) {
    @mysqli_set_charset($conn, "utf8mb4");
}

/**
 * Convierte letras (áéíóúñ, etc.) a entidades HTML,
 * PERO NO ESCAPA NI ROMPE el HTML (<h2>, <p>, etc.).
 *
 * - Primero decodifica entidades existentes para evitar &amp;aacute;
 * - Luego reemplaza caracteres por entidades (solo letras y signos)
 * - NO toca < > " ' ni & para que el HTML siga siendo HTML
 *
 * Nota: si te preocupa XSS, tenés que sanitizar HTML con whitelist (strip_tags) aparte.
 */
 
 function letras_a_entidades_sin_tocar_html($s) {
    // Unifica: si venía con &aacute; lo vuelve a "á"
    $s = html_entity_decode($s, ENT_QUOTES, 'UTF-8');

    // Reemplazos de letras y signos (sin tocar tags)
    $buscar = array(
        'á','é','í','ó','ú','Á','É','Í','Ó','Ú',
        'ñ','Ñ','ü','Ü',
        '¿','¡',
        '“','”','‘','’',

        // símbolos agregados
        'º','ª','°',
        '…','–','—',
        '«','»',
        '©','®','™',
        '¼','½','¾',
        '•',
        '€','£','¥',
        '×','÷','¬',

        // mojibake común de comillas
        'â€œ','â€','â€˜','â€™',

        // mojibake agregado
        'â€“','â€”','â€¦',
        'Â°','Âº','Âª',
        'Â«','Â»',
        'Â©','Â®','Â™',
        'Â¼','Â½','Â¾',
        'â€¢',
        'â‚¬','Â£','Â¥'
    );

    $reempl = array(
        '&aacute;','&eacute;','&iacute;','&oacute;','&uacute;',
        '&Aacute;','&Eacute;','&Iacute;','&Oacute;','&Uacute;',
        '&ntilde;','&Ntilde;','&uuml;','&Uuml;',
        '&iquest;','&iexcl;',
        '&ldquo;','&rdquo;','&lsquo;','&rsquo;',

        // símbolos agregados
        '&ordm;','&ordf;','&deg;',
        '&hellip;','&ndash;','&mdash;',
        '&laquo;','&raquo;',
        '&copy;','&reg;','&trade;',
        '&frac14;','&frac12;','&frac34;',
        '&bull;',
        '&euro;','&pound;','&yen;',
        '&times;','&divide;','&not;',

        '&ldquo;','&rdquo;','&lsquo;','&rsquo;',

        // mojibake agregado
        '&ndash;','&mdash;','&hellip;',
        '&deg;','&ordm;','&ordf;',
        '&laquo;','&raquo;',
        '&copy;','&reg;','&trade;',
        '&frac14;','&frac12;','&frac34;',
        '&bull;',
        '&euro;','&pound;','&yen;'
    );

    return str_replace($buscar, $reempl, $s);
}

// Captura
$titulo = isset($_POST['titulo']) ? $_POST['titulo'] : '';
$bajada = isset($_POST['bajada']) ? $_POST['bajada'] : '';
$texto  = isset($_POST['texto'])  ? $_POST['texto']  : '';

// Convertir letras a entidades SIN tocar HTML
$titulo = letras_a_entidades_sin_tocar_html($titulo);
$bajada = letras_a_entidades_sin_tocar_html($bajada);
$texto  = letras_a_entidades_sin_tocar_html($texto);



           $texto = str_replace('Ã¯Â¿Â½','',$texto); 
           $texto = str_replace('ï¿½','',$texto); 


// 1) Arreglar mojibake típico (UTF-8 mal interpretado)
$buscar  = array(
  "Ã¡","Ã©","Ã­","Ã³","Ãº",
  "Ã","Ã‰","Ã","Ã“","Ãš",
  "Ã±","Ã‘",
  "Ã¼","Ãœ",
  "Â¿","Â¡","Â«","Â»","Â“","Â”","â€œ","â€","â€˜","â€™","â€“","â€”","â€¦"
);

$reempl = array(
  "á","é","í","ó","ú",
  "Á","É","Í","Ó","Ú",
  "ñ","Ñ",
  "ü","Ü",
  "¿","¡","«","»","“","”","“","”","‘","’","–","—","…"
);

$texto = str_replace($buscar, $reempl, $texto);

// 2) Convertir a entidades HTML (acute)
$buscarEnt  = array(
  "á","é","í","ó","ú",
  "Á","É","Í","Ó","Ú",
  "ñ","Ñ",
  "ü","Ü",
  "¿","¡",
  "“","”","‘","’",
  "–","—","…",
  "«","»"
);

$reemplEnt = array(
  "&aacute;","&eacute;","&iacute;","&oacute;","&uacute;",
  "&Aacute;","&Eacute;","&Iacute;","&Oacute;","&Uacute;",
  "&ntilde;","&Ntilde;",
  "&uuml;","&Uuml;",
  "&iquest;","&iexcl;",
  "&ldquo;","&rdquo;","&lsquo;","&rsquo;",
  "&ndash;","&mdash;","&hellip;",
  "&laquo;","&raquo;"
);

$texto = str_replace($buscarEnt, $reemplEnt, $texto);



// Formato bajada
$bajada = nl2br($bajada);

// Escapes para SQL (lo correcto sería prepared statements, pero mantengo tu estilo)
$titulo = addslashes($titulo);
$bajada = addslashes($bajada);
$texto  = addslashes($texto);

// Fechas
$d = date('d');
$m = date('m');
$a = date('Y');
$hora = date('H');
$minuto = date('i');

// Campos varios
$cat  = isset($_POST['cat'])  ? $_POST['cat']  : '';
$cat2 = isset($_POST['cat2']) ? $_POST['cat2'] : '';
$cat3 = isset($_POST['cat3']) ? $_POST['cat3'] : '';
$cat4 = isset($_POST['cat4']) ? $_POST['cat4'] : '';
$cat5 = isset($_POST['cat5']) ? $_POST['cat5'] : '';

$tag1 = isset($_POST['tag1']) ? $_POST['tag1'] : '';
$tag2 = isset($_POST['tag2']) ? $_POST['tag2'] : '';
$tag3 = isset($_POST['tag3']) ? $_POST['tag3'] : '';
$tag4 = isset($_POST['tag4']) ? $_POST['tag4'] : '';
$tag5 = isset($_POST['tag5']) ? $_POST['tag5'] : '';

$publicar = isset($_POST['publicar']) ? $_POST['publicar'] : '';
$button   = isset($_POST['button'])   ? $_POST['button']   : '';

$fechapub = 0;
$ver_1 = "si";

// Programada
if ($publicar == 'programada') {
    $ver_1 = "no";

    $D = isset($_POST['D']) ? $_POST['D'] : $d;
    $M = isset($_POST['M']) ? $_POST['M'] : $m;
    $A = isset($_POST['A']) ? $_POST['A'] : $a;

    $hora   = isset($_POST['hora'])   ? $_POST['hora']   : $hora;
    $minuto = isset($_POST['minuto']) ? $_POST['minuto'] : $minuto;

    $d = $D; $m = $M; $a = $A;

    $D = str_pad((int)$D, 2, "0", STR_PAD_LEFT);
    $M = str_pad((int)$M, 2, "0", STR_PAD_LEFT);
    $hora = str_pad((int)$hora, 2, "0", STR_PAD_LEFT);
    $minuto = str_pad((int)$minuto, 2, "0", STR_PAD_LEFT);

    $fechapub = strtotime("$D-$M-$A $hora:$minuto");
}

// Ahora
if ($publicar == 'ahora') {
    $fechapub = 0;
    $ver_1 = "si";
}

// Tu código pisa $ver_1 con button; lo dejo pero ojo: si button no es "si/no" te rompe.
// Si lo que querés es usar button como ver, ok:
if ($button != '') {
    $ver_1 = $button;
}

// Tiempo php
$D = isset($D) ? $D : str_pad((int)$d, 2, "0", STR_PAD_LEFT);
$M = isset($M) ? $M : str_pad((int)$m, 2, "0", STR_PAD_LEFT);
$hora   = str_pad((int)$hora, 2, "0", STR_PAD_LEFT);
$minuto = str_pad((int)$minuto, 2, "0", STR_PAD_LEFT);
$tiempo_php = "$a$m$d$hora$minuto";

// Validaciones
?>
<!DOCTYPE html>
<html lang="es">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="description" content="Panel de Administracion">
  <meta name="author" content="<?php echo $nombresitio ?>">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title><?php echo $nombresitio ?> - Panel de Administracion</title>
  <link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
  <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">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

  <style type="text/css">
    *{ border-radius: 0!important; }
    body { background-image: url(../fondeux.jpg); }
    .navbar { position: relative; min-height: 50px; padding-bottom: 20px; }
    .btn-primary { color:#fff!important; background-color:#0066FF; border-color:#0066FF; }
    .page-header{ margin:0; padding:1em; background-color:#0066FF; border:0; text-align:center; }
    .page-header h2{ color:#ffffff; font-weight:bold; }
    ul{ list-style:none; padding:0; }
    .far, .faso{ color:#0066FF; }
    .colorAzul h3{ color:#0066FF; }
  </style>

  <script language=javascript>
    function ventanaSecundaria (URL){
      window.open(URL,"ventana1","width=550,height=450,scrollbars=NO")
    }
  </script>
</head>

<body>

<div class="container" style="background-color:#F1F2ED;max-width:960px;">
  <?php include 'menu.php'; ?>
</div>

<div role="main" style="background-color:#fff;max-width:960px;" class="container pt-3">
  <div class="page-header" style="text-align:center;">
    <h2><? echo $idioma_100759 ?></h2>
  </div>

  <div class="col-12 my-3 text-center">
    <div class="col-12">

<?php
if ($titulo == NULL) { ?>
  <p><? echo $idioma_100760 ?></p>
  <a class="btn btn-primary" href='javascript:history.back()'><? echo $idioma_volver?></a>
<?php exit; }

if ($bajada == NULL) { ?>
  <p><? echo $idioma_100761 ?></p>
  <a class="btn btn-primary" href='javascript:history.back()'><? echo $idioma_volver?></a>
<?php exit; }
$texto = str_replace('Ã¯Â¿Â½', '', $texto);

// INSERT
$sSQL = "INSERT INTO `$basedatos`.`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,'$titulo','$bajada','$texto','$d','$m','$a','$ver_1','','$cat','$cat2','$cat3','$cat4','$cat5','no','$tag1','$tag2','$tag3','$tag4','$tag5','$fechapub','$tiempo_php','','','0','si','','0','','','0','0','0','.jpg','0','0','','','','','0');";

$conn->query($sSQL);

// Obtener ID último
$ID_notaiiiii = 0;
$sql = "SELECT ID FROM notas ORDER BY ID DESC LIMIT 1";
$consulta = $conn->query($sql);
while ($row = $consulta->fetch_assoc()){
    $ID_notaiiiii = $row["ID"];
}
$consulta->free_result();

// Update user + mktime (tenías un bug: pisabas $sSQL y solo corrías 1 query)
$mktime = time();
$sSQL1 = "UPDATE `notas` SET `user` = '".addslashes($user)."' WHERE `notas`.`ID` = '$ID_notaiiiii' LIMIT 1;";
$sSQL2 = "UPDATE `notas` SET `mktime` = '$mktime' WHERE `notas`.`ID` = '$ID_notaiiiii' LIMIT 1;";
$conn->query($sSQL1);
$conn->query($sSQL2);
?>

      <h4 class=""><? echo $idioma_100762?></h4>
      <p class=""><? echo $idioma_100763?></p>

      <a class="btn btn-primary mb-3" href="index.php"><? echo $asd?>Inicio</a>
      <a class="btn btn-primary mb-3" href="<?php echo $dom?>/subir_foto_principal.php?ID=<?php echo $ID_notaiiiii?>"><? echo $asd?>Cargar foto principal</a>

    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>

<script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.js"></script>
<script type="text/javascript">
window.setInterval(function(){
  $('.grid').isotope({ itemSelector: '.grid-item' });
}, 500);
</script>

<script defer src="https://use.fontawesome.com/releases/v5.8.1/js/all.js" integrity="sha384-g5uSoOSBd7KkhAMlnQILrecXvzst9TdC09/VM+pjDTCM+1il8RHz5fKANTFFb+gQ" crossorigin="anonymous"></script>
</body>
</html>