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

/*
  Requiere PHP 8.2 (mysql_* eliminado) -> se usa mysqli + prepared statements.
  Toma $host, $usuario, $contra, $basedatos desde concha.php.
*/

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

// Si no hay ID válido, salimos prolijo (sin romper HTML)
$ok = false;
$mensaje = '';
$error_db = '';

if ($ID > 0) {
    // Si concha.php ya creó $conn como mysqli, lo reutilizamos. Si no, lo creamos.
    try {
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

        if (!isset($conn) || !($conn instanceof mysqli)) {
            $conn = new mysqli($host, $usuario, $contra, $basedatos);
        }
        $conn->set_charset('utf8mb4');

        // 1) Borrar nota
        $stmt = $conn->prepare("DELETE FROM `notas` WHERE `ID` = ? LIMIT 1");
        $stmt->bind_param("i", $ID);
        $stmt->execute();
        $borradas = $stmt->affected_rows;
        $stmt->close();

        // 2) Registrar historial (siempre loguea el intento)
        $d = date('d');
        $m = date('m');
        $Y = date('Y');
        $H = date('H');
        $i = date('i');

        $user_safe = isset($user) ? (string)$user : '';
        $operacion = "borraron una nota";
        $texto = "EL USUARIO $user_safe BORRO LA NOTA ID NUMERO $ID";

        $stmt2 = $conn->prepare("
            INSERT INTO `historial`
                (`ID`, `user`, `operacion`, `ID_op`, `texto`, `d`, `m`, `a`, `hora`, `min`, `fechaserver`)
            VALUES
                (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
        ");
        $stmt2->bind_param("ssissssss",
            $user_safe,
            $operacion,
            $ID,
            $texto,
            $d,
            $m,
            $Y,
            $H,
            $i
        );
        $stmt2->execute();
        $stmt2->close();

        if ($borradas > 0) {
            $ok = true;
            $mensaje = "OK";
        } else {
            $ok = false;
            $mensaje = "NO ENCONTRADA O YA BORRADA";
        }
    } catch (mysqli_sql_exception $e) {
        $ok = false;
        $mensaje = "ERROR";
        $error_db = $e->getMessage();
    }
} else {
    $ok = false;
    $mensaje = "ID INVALIDO";
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="description" content="Panel de Administracion">
    <meta name="author" content="<?php echo htmlspecialchars($nombresitio ?? '', ENT_QUOTES, 'UTF-8'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title><?php echo htmlspecialchars($nombresitio ?? '', ENT_QUOTES, 'UTF-8'); ?> - Panel de Administracion</title>

    <link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet" type="text/css">
    <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" 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; }
        .bloqueAzul { text-align:center; }
        .bloqueAzul .div { border:1px solid #e4e4e4; background-color:#fff; }
        ul { list-style:none; padding:0; }
        .far, .faso { color:#0066FF; }
        .colorAzul h3 { color:#0066FF; }
    </style>

    <script>
        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><?php echo htmlspecialchars($idioma_100764 ?? '', ENT_QUOTES, 'UTF-8'); ?></h2>
    </div>

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

        <?php if ($ok): ?>
            <h4><?php echo htmlspecialchars($idioma_100765 ?? '', ENT_QUOTES, 'UTF-8'); ?></h4>
        <?php else: ?>
            <h4><?php echo htmlspecialchars($idioma_100765 ?? '', ENT_QUOTES, 'UTF-8'); ?></h4>
            <?php if ($mensaje !== ''): ?>
                <div class="alert alert-warning mt-3" role="alert">
                    <?php echo htmlspecialchars($mensaje, ENT_QUOTES, 'UTF-8'); ?>
                    <?php if ($error_db !== ''): ?>
                        <div style="margin-top:8px; font-size:12px; opacity:.85;">
                            <?php echo htmlspecialchars($error_db, ENT_QUOTES, 'UTF-8'); ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>

        <div><a class="btn btn-primary mb-3" href="index.php"><?php echo htmlspecialchars($idioma_volver ?? 'Volver', ENT_QUOTES, 'UTF-8'); ?></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>
    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>