<?php
require_once 'auth.php';
require_once '../db_conexion.php';

// CRUD — Eliminar
if (isset($_GET['eliminar'])) {
    $stmt = $pdo->prepare("DELETE FROM productos WHERE id = ?");
    $stmt->execute([$_GET['eliminar']]);
    header("Location: dashboard.php?msg=eliminado");
    exit;
}

// Obtener productos
$productos = $pdo->query("
    SELECT p.*, c.nombre AS categoria_nombre 
    FROM productos p 
    JOIN categorias c ON p.categoria_id = c.id
    ORDER BY p.id ASC
")->fetchAll();

$categorias = $pdo->query("SELECT * FROM categorias")->fetchAll();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Dashboard - Canelita Admin</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: sans-serif; background: #f5f5f5; }
        .sidebar { width: 220px; background: #3b1f0f; min-height: 100vh; position: fixed; top: 0; left: 0; padding: 30px 0; }
        .sidebar h2 { color: #c8702a; text-align: center; margin-bottom: 30px; font-size: 1.2rem; }
        .sidebar a { display: block; color: #ddd; padding: 12px 24px; text-decoration: none; font-size: 0.95rem; }
        .sidebar a:hover, .sidebar a.active { background: #c8702a; color: white; }
        .sidebar .logout { position: absolute; bottom: 20px; width: 100%; }
        .main { margin-left: 220px; padding: 30px; }
        .topbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
        .topbar h1 { font-size: 1.5rem; color: #3b1f0f; }
        .btn { padding: 10px 18px; border-radius: 8px; border: none; cursor: pointer; font-size: 0.9rem; font-weight: 600; text-decoration: none; display: inline-block; }
        .btn-primary { background: #c8702a; color: white; }
        .btn-primary:hover { background: #a85a1e; }
        .btn-danger { background: #e74c3c; color: white; font-size: 0.8rem; padding: 6px 12px; }
        .btn-edit { background: #3498db; color: white; font-size: 0.8rem; padding: 6px 12px; }
        .alert-success { background: #d4edda; color: #155724; padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
        th { background: #3b1f0f; color: white; padding: 14px 16px; text-align: left; font-size: 0.85rem; }
        td { padding: 12px 16px; border-bottom: 1px solid #f0f0f0; font-size: 0.9rem; vertical-align: middle; }
        tr:hover td { background: #fdf6f0; }
        .badge { padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 600; }
        .badge-yes { background: #d4edda; color: #155724; }
        .badge-no { background: #f8d7da; color: #721c24; }
        img.thumb { width: 50px; height: 50px; object-fit: cover; border-radius: 8px; }

        /* Modal */
        .modal-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999; justify-content: center; align-items: center; }
        .modal-overlay.open { display: flex; }
        .modal { background: white; padding: 32px; border-radius: 12px; width: 500px; max-width: 95vw; }
        .modal h3 { margin-bottom: 20px; color: #3b1f0f; }
        .form-group { margin-bottom: 14px; }
        .form-group label { display: block; font-size: 0.85rem; font-weight: 600; margin-bottom: 5px; color: #555; }
        .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 9px 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 0.95rem; }
        .form-group textarea { resize: vertical; }
        .modal-footer { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }
        .btn-secondary { background: #ddd; color: #333; }
    </style>
</head>
<body>

<div class="sidebar">
    <h2>🍽️ Canelita</h2>
    <a href="dashboard.php" class="active">📦 Productos</a>
    <a href="pedidos.php" class="active">🧾 Pedidos</a>  <!-- AGREGAR -->
    <div class="logout">
        <a href="logout.php">🚪 Cerrar sesión</a>
    </div>
</div>

<div class="main">
    <div class="topbar">
        <h1>Gestión de Productos</h1>
        <button class="btn btn-primary" onclick="abrirModal()">+ Nuevo Producto</button>
    </div>

    <?php if (isset($_GET['msg'])): ?>
        <div class="alert-success">
            <?= $_GET['msg'] === 'guardado' ? '✅ Producto guardado correctamente.' : '' ?>
            <?= $_GET['msg'] === 'eliminado' ? '🗑️ Producto eliminado.' : '' ?>
        </div>
    <?php endif; ?>

    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Imagen</th>
                <th>Nombre</th>
                <th>Categoría</th>
                <th>Precio</th>
                <th>Destacado</th>
                <th>Acciones</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($productos as $p): ?>
            <tr>
                <td><?= $p['id'] ?></td>
                <td><img class="thumb" src="../<?= htmlspecialchars($p['imagen']) ?>" alt="" onerror="this.src='https://via.placeholder.com/50'" /></td>
                <td><?= htmlspecialchars($p['nombre']) ?></td>
                <td><?= htmlspecialchars($p['categoria_nombre']) ?></td>
                <td>S/ <?= number_format($p['precio'], 2) ?></td>
                <td><span class="badge <?= $p['destacado'] ? 'badge-yes' : 'badge-no' ?>"><?= $p['destacado'] ? 'Sí' : 'No' ?></span></td>
                <td style="display:flex; gap:6px;">
                    <button class="btn btn-edit" onclick='abrirModalEditar(<?= json_encode($p) ?>)'>✏️ Editar</button>
                    <a class="btn btn-danger" href="?eliminar=<?= $p['id'] ?>" onclick="return confirm('¿Eliminar este producto?')">🗑️</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Modal Crear/Editar -->
<div class="modal-overlay" id="modalOverlay">
    <div class="modal">
        <h3 id="modalTitulo">Nuevo Producto</h3>
        <form method="POST" action="guardar_producto.php">
            <input type="hidden" name="id" id="prod-id" value="" />
            <div class="form-group">
                <label>Nombre *</label>
                <input type="text" name="nombre" id="prod-nombre" required />
            </div>
            <div class="form-group">
                <label>Descripción</label>
                <textarea name="descripcion" id="prod-descripcion" rows="3"></textarea>
            </div>
            <div class="form-group">
                <label>Precio *</label>
                <input type="number" step="0.01" name="precio" id="prod-precio" required />
            </div>
            <div class="form-group">
                <label>Categoría *</label>
                <select name="categoria_id" id="prod-categoria">
                    <?php foreach ($categorias as $cat): ?>
                        <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['nombre']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>URL de Imagen</label>
                <input type="text" name="imagen" id="prod-imagen" placeholder="img/platos/foto.jpg" />
            </div>
            <div class="form-group">
                <label>¿Destacado?</label>
                <select name="destacado" id="prod-destacado">
                    <option value="0">No</option>
                    <option value="1">Sí</option>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="cerrarModal()">Cancelar</button>
                <button type="submit" class="btn btn-primary">Guardar</button>
            </div>
        </form>
    </div>
</div>

<script>
function abrirModal() {
    document.getElementById('modalTitulo').textContent = 'Nuevo Producto';
    document.getElementById('prod-id').value = '';
    document.getElementById('prod-nombre').value = '';
    document.getElementById('prod-descripcion').value = '';
    document.getElementById('prod-precio').value = '';
    document.getElementById('prod-imagen').value = '';
    document.getElementById('prod-destacado').value = '0';
    document.getElementById('modalOverlay').classList.add('open');
}

function abrirModalEditar(p) {
    document.getElementById('modalTitulo').textContent = 'Editar Producto';
    document.getElementById('prod-id').value = p.id;
    document.getElementById('prod-nombre').value = p.nombre;
    document.getElementById('prod-descripcion').value = p.descripcion;
    document.getElementById('prod-precio').value = p.precio;
    document.getElementById('prod-imagen').value = p.imagen;
    document.getElementById('prod-destacado').value = p.destacado;
    document.getElementById('prod-categoria').value = p.categoria_id;
    document.getElementById('modalOverlay').classList.add('open');
}

function cerrarModal() {
    document.getElementById('modalOverlay').classList.remove('open');
}

document.getElementById('modalOverlay').addEventListener('click', function(e) {
    if (e.target === this) cerrarModal();
});
</script>

</body>
</html>