<?php
include 'tiny.php';
include '../url_amigable.php';
include 'sesion.php';
include 'concha.php';

/* =========================================================
   CONFIGURACIÓN UTF-8
   ========================================================= */
if (isset($conn) && is_object($conn)) {
    if (method_exists($conn, 'set_charset')) {
        @$conn->set_charset('utf8mb4');
    }
    @mysqli_set_charset($conn, 'utf8mb4');
    @$conn->query("SET NAMES utf8mb4");
    @$conn->query("SET CHARACTER SET utf8mb4");
    @$conn->query("SET SESSION collation_connection = 'utf8mb4_unicode_ci'");
}

/* =========================================================
   FUNCIONES DE CODIFICACIÓN
   ========================================================= */

function rn_post($key)
{
    return isset($_POST[$key]) ? (string)$_POST[$key] : '';
}

function rn_reparar_mojibake($s)
{
    $s = (string)$s;

    // Espacios raros / nbsp roto
    $s = str_replace(array("\xC2\xA0", "Â ", "Â&nbsp;", "Â"), ' ', $s);

    /*
      Repara textos rotos tipo:
      Ã¡ Ã© Ã¨ Ã± Å› â€œ â€ â€™
    */
    if (preg_match('/(?:Ã.|Å.|â..)/u', $s)) {
        $s = preg_replace_callback('/(?:Ã.|Å.|â..)+/u', function ($m) {
            $trozo = $m[0];

            if (function_exists('mb_convert_encoding')) {
                $fix = @mb_convert_encoding($trozo, 'Windows-1252', 'UTF-8');
                if ($fix !== false && $fix !== '') {
                    return $fix;
                }
            }

            $fix = @utf8_decode($trozo);
            return ($fix !== false && $fix !== '') ? $fix : $trozo;
        }, $s);
    }

    return $s;
}

function rn_texto_a_entidades($s)
{
    $s = rn_reparar_mojibake($s);

    // Decodifica entidades existentes para normalizar:
    // si entra &aacute;, vuelve a á y después queda otra vez &aacute;
    $s = html_entity_decode($s, ENT_QUOTES, 'UTF-8');

    // Convierte caracteres especiales a entidades HTML
    $r = @htmlentities($s, ENT_QUOTES, 'UTF-8', false);

    if ($r === false || $r === '') {
        if (function_exists('mb_convert_encoding')) {
            $s2 = @mb_convert_encoding($s, 'UTF-8', 'UTF-8');
            $r = @htmlentities($s2, ENT_QUOTES, 'UTF-8', false);
        }
    }

    if ($r === false) {
        $r = $s;
    }

    // Si todavía queda algún carácter no ASCII, lo fuerza a entidad HTML
    if (function_exists('mb_convert_encoding') && preg_match('/[^\x00-\x7F]/u', $r)) {
        $r2 = @mb_convert_encoding($r, 'HTML-ENTITIES', 'UTF-8');
        if ($r2 !== false && $r2 !== '') {
            $r = $r2;
        }
    }

    return trim($r);
}

function rn_html_a_entidades_preservando_tags($html)
{
    $html = rn_reparar_mojibake($html);

    /*
      Separa tags HTML del texto.
      Convierte solamente el contenido textual.
      Ejemplo:
      <p>áéí</p>
      queda:
      <p>&aacute;&eacute;&iacute;</p>
    */
    $partes = preg_split('/(<[^>]+>)/u', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
    $salida = '';

    if (is_array($partes)) {
        foreach ($partes as $parte) {
            if ($parte === '') {
                continue;
            }

            if (preg_match('/^<[^>]+>$/u', $parte)) {
                // Es etiqueta HTML, se conserva
                $salida .= $parte;
            } else {
                // Es texto, se convierte a entidades
                $salida .= rn_texto_a_entidades($parte);
            }
        }
    } else {
        $salida = rn_texto_a_entidades($html);
    }

    return trim($salida);
}

function rn_sql($conn, $s)
{
    if (isset($conn) && is_object($conn)) {
        return $conn->real_escape_string($s);
    }

    return addslashes($s);
}

/* =========================================================
   DATOS DEL FORMULARIO
   ========================================================= */

$titulo_original = rn_post('titulo');
$bajada_original = rn_post('bajada');
$texto_original  = rn_post('texto');

$titulo = rn_texto_a_entidades($titulo_original);
$bajada = rn_texto_a_entidades($bajada_original);
$texto  = rn_html_a_entidades_preservando_tags($texto_original);

$goear   = rn_texto_a_entidades(rn_post('goear'));
$listengo = rn_texto_a_entidades(rn_post('listengo'));

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

$cat = rn_post('cat');

$tag1 = rn_texto_a_entidades(rn_post('tag1'));
$tag2 = rn_texto_a_entidades(rn_post('tag2'));
$tag3 = rn_texto_a_entidades(rn_post('tag3'));
$tag4 = rn_texto_a_entidades(rn_post('tag4'));
$tag5 = rn_texto_a_entidades(rn_post('tag5'));

$radio = rn_post('radio');

$Dp = rn_post('Dp');
$Mp = rn_post('Mp');
$Ap = rn_post('Ap');

$youtube = rn_texto_a_entidades(rn_post('youtube'));

if ($radio == 'a') {
    $fechapub = 0;
    $horap = 0;
} else {
    $fechapub = $Ap . $Mp . $Dp;
    $horap = rn_post('horap');
}

/* =========================================================
   VALIDACIONES
   ========================================================= */

$error = '';

if (trim($titulo_original) == '') {
    $error = 'LA NOTICIA DEBE TENER UN TITULO';
}

if ($error == '' && trim($bajada_original) == '') {
    $error = 'EL TEXTO DE LA BAJADA ESTA VACIO';
}

/* =========================================================
   INSERT
   ========================================================= */

$ID = 0;

if ($error == '') {

    $titulo_sql   = rn_sql($conn, $titulo);
    $bajada_sql   = rn_sql($conn, $bajada);
    $texto_sql    = rn_sql($conn, $texto);
    $goear_sql    = rn_sql($conn, $goear);
    $listengo_sql = rn_sql($conn, $listengo);
    $cat_sql      = rn_sql($conn, $cat);
    $tag1_sql     = rn_sql($conn, $tag1);
    $tag2_sql     = rn_sql($conn, $tag2);
    $tag3_sql     = rn_sql($conn, $tag3);
    $tag4_sql     = rn_sql($conn, $tag4);
    $tag5_sql     = rn_sql($conn, $tag5);
    $fechapub_sql = rn_sql($conn, $fechapub);
    $horap_sql    = rn_sql($conn, $horap);
    $youtube_sql  = rn_sql($conn, $youtube);

    $sSQL = "
        INSERT INTO `$basedatos`.`notas`
        (
            `ID`,
            `titulo`,
            `bajada`,
            `texto`,
            `goear`,
            `listengo`,
            `d`,
            `m`,
            `a`,
            `ver`,
            `foto`,
            `cat`,
            `destacado`,
            `tag1`,
            `tag2`,
            `tag3`,
            `tag4`,
            `tag5`,
            `fechapub`,
            `horapub`,
            `youtube`
        )
        VALUES
        (
            NULL,
            '$titulo_sql',
            '$bajada_sql',
            '$texto_sql',
            '$goear_sql',
            '$listengo_sql',
            '$d',
            '$m',
            '$a',
            'si',
            '0',
            '$cat_sql',
            'no',
            '$tag1_sql',
            '$tag2_sql',
            '$tag3_sql',
            '$tag4_sql',
            '$tag5_sql',
            '$fechapub_sql',
            '$horap_sql',
            '$youtube_sql'
        )
    ";

    $ok_insert = $conn->query($sSQL);

    if ($ok_insert) {
        $ID = $conn->insert_id;
    } else {
        $error = 'ERROR AL GUARDAR LA NOTA: ' . $conn->error;
    }
}

$titulo_para_url = html_entity_decode($titulo, ENT_QUOTES, 'UTF-8');

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta 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="https://fonts.googleapis.com/css?family=Montserrat:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900&display=swap" rel="stylesheet">
    <link rel="shortcut icon" href="" type="image/x-icon">
    <link rel="apple-touch-icon" href="">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

    <style>
        .carousel-cell {
            width: 66%;
            margin-right: 5px;
        }

        .display-flex {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        * {
            border-radius: 0 !important;
        }

        body {
            background-image: url(../fondeux.jpg);
            background-position: top center;
            background-repeat: repeat-x;
            background-color: #EBEBEB;
            height: 100%;
        }

        .btn, a, h1, h2, h3, h4, h5, h6, b {
            font-family: 'Montserrat', sans-serif;
        }

        .btn, h1, h2, h3, h4, h5, h6 {
            font-weight: 600;
        }

        .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;
        }

        .bloqueAzul {
            text-align: center;
        }

        .bloqueAzul .div {
            border: 1px solid #e4e4e4;
            background-color: #fff;
        }

        ul {
            list-style: none;
            padding: 0;
        }

        .far {
            color: #0066FF;
        }

        .faso {
            color: #fff;
        }

        .colorAzul h3 {
            color: #0066FF;
        }

        .caja-panel {
            background: #DDDDDD;
            padding: 40px 20px;
            min-height: 300px;
        }

        .mensaje-ok {
            font-size: 18px;
            font-weight: 700;
            color: #111;
        }

        .mensaje-error {
            font-size: 18px;
            font-weight: 700;
            color: #b00020;
        }

        table.panel-table {
            width: 862px;
            margin: 0 auto;
            border: 0;
        }

        .menu-lateral {
            width: 200px;
            background: #C3C3C3;
            vertical-align: top;
            padding: 15px;
        }

        .contenido {
            width: 652px;
            background: #DDDDDD;
            vertical-align: top;
        }
    </style>

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

<body>

<table class="panel-table" border="0" align="center">
    <tr>
        <td class="menu-lateral">
            <a href="index.php">MENU</a> &gt;<br><br><br>
        </td>

        <td class="contenido">
            <div align="center" class="caja-panel">

                <?php if ($error != '') { ?>

                    <p class="mensaje-error"><?php echo htmlentities($error, ENT_QUOTES, 'UTF-8'); ?></p>
                    <p>
                        <a href="javascript:history.back()">Volver</a>
                    </p>

                <?php } else { ?>

                    <p class="mensaje-ok">LA NOTA FUE CARGADA CORRECTAMENTE</p>

                    <p>
                        <a href="upload_crop_v1.2.php?ID=<?php echo $ID; ?>" target="_blank">
                            PONER UNA FOTO EN LA NOTICIA
                        </a>
                        <br><br>

                        <a href="<?php echo $dom; ?>/nota/<?php echo $ID; ?>/<?php echo urls_amigables($titulo_para_url); ?>" target="_blank">
                            VER COMO QUEDO LA NOTA EN LA PAGINA
                        </a>
                        <br><br>
                    </p>

                <?php } ?>

            </div>
        </td>
    </tr>
</table>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>

<script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.js"></script>
<script>
window.setInterval(function () {
    if (typeof $ !== 'undefined' && $('.grid').length) {
        $('.grid').isotope({
            itemSelector: '.grid-item'
        });
    }
}, 500);
</script>

<script defer src="https://use.fontawesome.com/releases/v5.8.1/js/all.js"></script>

</body>
</html>