<?php

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("../db.php"); 

if (!isset($_SESSION['rol']) || $_SESSION['rol'] !== 'admin') {
    header("Location: ../login.php?error=acceso_denegado"); 
    exit();
}

date_default_timezone_set('America/Argentina/Buenos_Aires');

$mensaje_alerta = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['menu_del_dia'])) {
    $menu_del_dia = mysqli_real_escape_string($conexion, $_POST['menu_del_dia']);
    $precio_promo = floatval($_POST['precio_promo']);
    $stock_promo = intval($_POST['stock_promo']);
    
    if (!empty($menu_del_dia)) {
        mysqli_begin_transaction($conexion);
        try {
            $ruta_imagen_db = ""; 
            if (isset($_FILES['imagen_promo']) && $_FILES['imagen_promo']['error'] === UPLOAD_ERR_OK) {
                $file_tmp = $_FILES['imagen_promo']['tmp_name'];
                $file_name = $_FILES['imagen_promo']['name'];
                $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                
                $extensiones_validas = array("jpg", "jpeg", "png", "webp");
                if (in_array($ext, $extensiones_validas)) {
                    $nombre_unico = "promo_" . time() . "." . $ext;
                    $directorio_destino = "../imagenes/";
                    
                    if (move_uploaded_file($file_tmp, $directorio_destino . $nombre_unico)) {
                        $ruta_imagen_db = "imagenes/" . $nombre_unico;
                    }
                }
            }

            $query_notif = "INSERT INTO promociones (mensaje, fecha_publicacion) VALUES ('$menu_del_dia', NOW())";
            mysqli_query($conexion, $query_notif);

            if (!empty($ruta_imagen_db)) {
                $query_prod = "UPDATE productos SET precio = $precio_promo, stock = $stock_promo, imagen = '$ruta_imagen_db', activo = 1 WHERE id = 999";
            } else {
                $query_prod = "UPDATE productos SET precio = $precio_promo, stock = $stock_promo, activo = 1 WHERE id = 999";
            }
            mysqli_query($conexion, $query_prod);

            mysqli_commit($conexion);
            $mensaje_alerta = "<div class='alert success'><i class='fa-solid fa-circle-check'></i> ¡Promoción lanzada con éxito! Cambios aplicados en vivo.</div>";
        } catch (Exception $e) {
            mysqli_rollback($conexion);
            $mensaje_alerta = "<div class='alert error'><i class='fa-solid fa-circle-xmark'></i> Error al procesar la promoción: " . $e->getMessage() . "</div>";
        }
    }
}

//Borrar una promoción vieja
if (isset($_GET['eliminar'])) {
    $id_eliminar = (int)$_GET['eliminar'];
    mysqli_query($conexion, "DELETE FROM promociones WHERE id = $id_eliminar");
    header("Location: promo.php");
    exit();
}

// Traemos las últimas 5 promos enviadas
$historial = mysqli_query($conexion, "SELECT * FROM promociones ORDER BY id DESC LIMIT 5");
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Panel La Pecosa - Promociones</title>
    <link rel="stylesheet" href="../css/all.min.css">
    <link rel="stylesheet" href="admin_style.css"> 
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', sans-serif; }
        body { background-color: #f4f6f9; min-height: 100vh; display: flex; }
        
        .main-wrapper { 
            flex: 1; 
            margin-left: 260px;
            padding: 40px;
            width: calc(100% - 260px);
        }

        .header-title { display: flex; align-items: center; gap: 15px; margin-bottom: 30px; }
        .header-title h2 { font-size: 1.8rem; color: #1a202c; font-weight: 700; }
        
        .card { background: white; padding: 30px; border-radius: 15px; box-shadow: 0 4px 20px rgba(0,0,0,0.02); margin-bottom: 30px; border: 1px solid #edf2f7; }
        .card h3 { color: #2d3748; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; font-size: 1.2rem; font-weight: 600; padding-bottom: 10px; border-bottom: 1px solid #edf2f7; }
        
        .form-grid { display: grid; grid-template-columns: 1.5fr 1fr; gap: 25px; }
        @media (max-width: 992px) { .form-grid { grid-template-columns: 1fr; } }
        
        .form-left { display: flex; flex-direction: column; gap: 15px; }
        
        .group-input { display: flex; flex-direction: column; gap: 6px; }
        .group-input label { font-size: 0.9rem; font-weight: 600; color: #4a5568; }
        
        textarea { width: 100%; padding: 12px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 0.95rem; resize: none; outline: none; transition: 0.2s; background: #f8fafc; }
        textarea:focus { border-color: #e02828; background: white; box-shadow: 0 0 0 3px rgba(224, 40, 40, 0.08); }
        
        .inputs-inline { display: flex; gap: 15px; }
        .inputs-inline .group-input { flex: 1; }
        
        .group-input input[type="number"] { padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 0.95rem; outline: none; transition: 0.2s; background: #f8fafc; }
        .group-input input[type="number"]:focus { border-color: #e02828; background: white; }
        
        .image-upload-wrapper { border: 2px dashed #cbd5e1; padding: 20px; border-radius: 10px; text-align: center; background: #f8fafc; transition: 0.2s; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; min-height: 180px; height: 100%; cursor: pointer; position: relative; }
        .image-upload-wrapper:hover { border-color: #e02828; background: #fff5f5; }
        .image-upload-wrapper i { font-size: 2.2rem; color: #a0aec0; }
        .image-upload-wrapper p { font-size: 0.85rem; color: #718096; }
        .image-upload-wrapper input[type="file"] { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
        
        #preview-container { display: none; width: 100%; height: 100%; position: absolute; top: 0; left: 0; background: white; border-radius: 10px; overflow: hidden; }
        #preview-container img { width: 100%; height: 100%; object-fit: cover; }
        #remove-preview-btn { position: absolute; top: 8px; right: 8px; background: rgba(0,0,0,0.7); color: white; border: none; padding: 5px 10px; border-radius: 5px; cursor: pointer; font-size: 0.75rem; z-index: 10; }
        #remove-preview-btn:hover { background: #e02828; }

        .footer-form { margin-top: 15px; display: flex; justify-content: flex-end; }
        .btn-lanzar { background: #e02828; color: white; border: none; padding: 12px 25px; border-radius: 50px; font-weight: 700; font-size: 0.95rem; cursor: pointer; transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; }
        .btn-lanzar:hover { background: #c02020; transform: translateY(-1px); }
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: 600; display: flex; align-items: center; gap: 10px; font-size: 0.95rem; }
        .alert.success { background-color: #f0fdf4; color: #16a34a; border-left: 4px solid #16a34a; }
        .alert.error { background-color: #fef2f2; color: #dc2626; border-left: 4px solid #dc2626; }

        .table-container { width: 100%; overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; text-align: left; font-size: 0.95rem; }
        th { background-color: #f8fafc; color: #718096; font-weight: 600; padding: 12px 15px; border-bottom: 2px solid #e2e8f0; font-size: 0.85rem; }
        td { padding: 12px 15px; border-bottom: 1px solid #edf2f7; color: #2d3748; }
        tr:hover td { background-color: #f8fafc; }
        .btn-delete { color: #a0aec0; text-decoration: none; font-size: 1.05rem; transition: 0.2s; }
        .btn-delete:hover { color: #e53e3e; }
    </style>
</head>
<body>

    <?php include("sidebar.php"); ?>

    <div class="main-wrapper">
        <div class="header-title">
            <i class="fa-solid fa-bullhorn" style="color: #e02828; font-size: 1.6rem;"></i>
            <h2>Gestión de promociones y menú del día</h2>
        </div>

        <?php echo $mensaje_alerta; ?>

        <div class="card">
            <h3><i class="fa-regular fa-paper-plane" style="color: #e02828;"></i> Lanzar nueva promoción en tiempo real</h3>
            
            <form action="" method="POST" enctype="multipart/form-data">
                <div class="form-grid">
                    
                    <div class="form-left">
                        <div class="group-input">
                            <label for="menu_del_dia">Mensaje promocional o descripción del plato</label>
                            <textarea id="menu_del_dia" name="menu_del_dia" rows="4" required placeholder="Ej: ¡Promo imperdible! 2 Lomitos completos + papas fritas medianas 🍔🍟"></textarea>
                        </div>
                        
                        <div class="inputs-inline">
                            <div class="group-input">
                                <label for="precio_promo">Precio final ($)</label>
                                <input type="number" id="precio_promo" name="precio_promo" min="0" step="50" required placeholder="Ej: 8500">
                            </div>
                            <div class="group-input">
                                <label for="stock_promo">Stock inicial</label>
                                <input type="number" id="stock_promo" name="stock_promo" min="1" required placeholder="Ej: 20">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-right">
                        <div class="group-input" style="height: 100%;">
                            <label>Imagen publicitaria de la promo</label>
                            <div class="image-upload-wrapper">
                                <i class="fa-solid fa-cloud-arrow-up"></i>
                                <p><strong>Hacé clic acá</strong> para cargar foto</p>
                                <span style="font-size: 0.75rem; color: #a0aec0;">PNG, JPG o WEBP</span>
                                <input type="file" id="imagen_promo" name="imagen_promo" accept="image/*">
                                
                                <div id="preview-container">
                                    <button type="button" id="remove-preview-btn">Cambiar Foto</button>
                                    <img id="image-preview" src="#" alt="Vista previa">
                                </div>
                            </div>
                        </div>
                    </div>

                </div>

                <div class="footer-form">
                    <button type="submit" class="btn-lanzar">
                        <i class="fa-solid fa-rocket"></i> Publicar promoción
                    </button>
                </div>
            </form>
        </div>

        <div class="card">
            <h3><i class="fa-solid fa-clock-rotate-left" style="color: #718096;"></i> Historial de notificaciones recientes</h3>
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th style="width: 20%;">Fecha y Hora</th>
                            <th>Mensaje enviado a los clientes</th>
                            <th style="width: 10%; text-align: center;">Acción</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($historial && mysqli_num_rows($historial) > 0): ?>
                            <?php while($row = mysqli_fetch_assoc($historial)): ?>
                                <tr>
                                    <td style="color: #718096; font-weight: 500;">
                                        <?php 
                                            $fecha = isset($row['fecha_publicacion']) ? $row['fecha_publicacion'] : 'now';
                                            echo date("d/m - H:i", strtotime($fecha)); 
                                        ?> hs
                                    </td>
                                    <td style="font-weight: 500; color: #2d3748;"><?php echo htmlspecialchars($row['mensaje']); ?></td>
                                    <td style="text-align: center;">
                                        <a href="promo.php?eliminar=<?php echo $row['id']; ?>" class="btn-delete" title="Eliminar del historial" onclick="return confirm('¿Seguro que querés quitar esta promo del historial?')">
                                            <i class="fa-solid fa-trash-can"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="3" style="text-align: center; color: #a0aec0; padding: 30px 0;">No se enviaron promociones todavía.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        const fileInput = document.getElementById('imagen_promo');
        const previewContainer = document.getElementById('preview-container');
        const imagePreview = document.getElementById('image-preview');
        const removePreviewBtn = document.getElementById('remove-preview-btn');

        fileInput.addEventListener('change', function() {
            const file = this.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    imagePreview.setAttribute('src', e.target.result);
                    previewContainer.style.display = 'block';
                }
                reader.readAsDataURL(file);
            }
        });

        removePreviewBtn.addEventListener('click', function(e) {
            e.preventDefault();
            fileInput.value = "";
            previewContainer.style.display = 'none';
            imagePreview.setAttribute('src', '#');
        });
    </script>
</body>
</html>