<?php
// market.php
require __DIR__ . '/market_bootstrap.php';

$pdo = market_pdo();

$st = $pdo->query("
    SELECT p.*,
           u.nombre AS u_nombre,
           u.apellido AS u_apellido,
           (SELECT archivo FROM market_productos_fotos f 
            WHERE f.producto_id = p.id AND f.es_portada = 1
            ORDER BY f.id ASC LIMIT 1) AS portada
    FROM market_productos p
    JOIN market_usuarios u ON u.id = p.usuario_id
    WHERE p.estado = 'activo'
    ORDER BY p.created_at DESC
");
$productos = $st->fetchAll(PDO::FETCH_ASSOC);

$logged = market_is_logged();
$U      = market_current_user();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <title>Marketplace de Fe.Tr.A</title>
    <?php require __DIR__ . '/_head_assets.php'; ?>
    <style>
        /* ======== LAYOUT GENERAL ======== */
        .mk-hero {
            padding: 3rem 0 2.5rem;
            background: linear-gradient(135deg,#0055a5,#00a2ff);
            color: #fff;
        }
        .mk-hero h1 {
            font-weight: 800;
            font-size: 2.1rem;
            margin-bottom: .4rem;
        }
        .mk-hero p {
            margin-bottom: 0;
            opacity: .96;
            font-size: .95rem;
        }
        .mk-hero-actions .btn {
            margin-left: .5rem;
            margin-top: .3rem;
            font-weight: 600;
            border-radius: 999px;
            font-size: .8rem;
            padding: .35rem .9rem;
        }

        .mk-main {
            padding: 2rem 0 3rem;
            background: #f4f6fb;
        }

        .mk-user-strip {
            background: #fff;
            border-radius: .75rem;
            padding: .9rem 1.2rem;
            margin-bottom: 1.7rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: .75rem;
            box-shadow: 0 6px 18px rgba(0,0,0,0.06);
            font-size: .9rem;
        }
        .mk-user-strip strong { font-weight: 700; }

        .mk-user-strip .btn-group .btn {
            font-weight: 600;
            border-radius: 999px;
            font-size: .8rem;
            padding: .3rem .85rem;
        }

        /* ======== GRID DE PRODUCTOS ======== */
        .mk-grid-empty {
            text-align: center;
            padding: 3rem 1rem;
            border-radius: 1rem;
            background: #fff;
            border: 1px dashed #d2d6e0;
            box-shadow: 0 10px 25px rgba(0,0,0,0.04);
        }
        .mk-grid-empty i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #b3bac9;
        }

        /* Parrilla tipo MercadoLibre (2–4 columnas según ancho) */
        .mk-products-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 1.5rem;
        }

        .mk-card {
            border: 1px solid #dde1eb;      /* 🔹 borde gris claro marcado */
            border-radius: 1.4rem;
            overflow: hidden;
            box-shadow: 0 6px 16px rgba(0,0,0,0.06);
            background: #fff;
            display: flex;
            flex-direction: column;
            min-height: 320px;              /* 🔹 tamaño homogéneo */
        }

        .mk-card-img-wrap {
            position: relative;
            background: #f4f5f8;
            height: 190px;                  /* 🔹 misma altura para todas */
            padding: .35rem .4rem;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }
        .mk-card-img-wrap img {
            max-width: 100%;
            max-height: 100%;
            width: auto;
            height: auto;
            object-fit: contain;            /* 🔹 según su contenido, sin recorte */
            display: block;
            transition: transform .25s ease;
        }
        .mk-card:hover .mk-card-img-wrap img {
            transform: scale(1.02);
        }

        .mk-card-badge {
            position: absolute;
            top: .7rem;
            left: .8rem;
            background: rgba(0,0,0,0.78);
            color: #fff;
            padding: .25rem .8rem;
            border-radius: 999px;
            font-size: .75rem;
            font-weight: 600;
        }
        .mk-badge-consultar {
            background: #ffc107;
            color: #3a2a00;
        }

        .mk-card-body {
            padding: .8rem .9rem .6rem;
            display: flex;
            flex-direction: column;
            flex: 1 1 auto;
        }
        .mk-card-title {
            font-size: .96rem;
            font-weight: 700;
            margin-bottom: .18rem;
            color: #1f2933;
        }
        .mk-card-location {
            font-size: .78rem;
            color: #6c757d;
        }
        .mk-card-desc {
            margin-top: .4rem;
            font-size: .8rem;
            color: #444;
            flex: 1 1 auto;
        }

        .mk-card-footer {
            padding: .6rem .9rem .8rem;
            border-top: 1px solid #eceff4;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: .78rem;
        }
        .mk-card-footer small {
            color: #6c757d;
        }

        .btn-mk-cta {
            font-weight: 600;
            border-radius: 999px;
            font-size: .8rem;
            padding: .32rem .9rem;
        }

        @media (max-width: 575.98px) {
            .mk-hero {
                text-align: center;
            }
            .mk-hero-actions {
                text-align: center !important;
            }
            .mk-user-strip {
                align-items: flex-start;
            }
        }
        /* Espaciado hacia abajo */
.botones-market {
    margin-top: 18px;
}

/* Estilo general */
.btn-market {
    border-radius: 14px !important;
    padding: 7px 18px !important;
    font-weight: 600;
    letter-spacing: 0.3px;
    margin-left: 8px;
    transition: 0.25s ease-in-out;
    border: none !important;
}

/* ESTILOS VERDES */
.btn-market.btn-light,
.btn-market.btn-outline-light,
.btn-market.btn-success {
    background: linear-gradient(135deg, #4caf50, #2e7d32);
    color: #fff !important;
    box-shadow: 0 3px 8px rgba(46, 125, 50, 0.3);
}

/* Hover */
.btn-market:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 14px rgba(46, 125, 50, 0.35) !important;
    opacity: 0.95;
}
/* Estilo base general */
.btn-market {
    border-radius: 14px !important;
    padding: 7px 18px !important;
    font-weight: 600;
    letter-spacing: 0.3px;
    margin-left: 8px;
    transition: 0.25s ease-in-out;
    border: none !important;
    color: #fff !important;
}

/* ==== AZUL (Mi perfil) ==== */
.btn-azul {
    background: linear-gradient(135deg, #1976d2, #0d47a1);
    box-shadow: 0 3px 8px rgba(13, 71, 161, 0.3);
}
.btn-azul:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(13, 71, 161, 0.45);
}

/* ==== ROJO (Cerrar sesión) ==== */
.btn-rojo {
    background: linear-gradient(135deg, #e53935, #b71c1c);
    box-shadow: 0 3px 8px rgba(183, 28, 28, 0.3);
}
.btn-rojo:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(183, 28, 28, 0.45);
}

/* ==== VERDE (Iniciar sesión) ==== */
.btn-verde {
    background: linear-gradient(135deg, #4caf50, #2e7d32);
    box-shadow: 0 3px 8px rgba(46, 125, 50, 0.3);
}
.btn-verde:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(46, 125, 50, 0.45);
}

/* ==== VERDE CLARO (Crear cuenta) ==== */
.btn-verde-claro {
    background: linear-gradient(135deg, #81c784, #4caf50);
    box-shadow: 0 3px 8px rgba(76, 175, 80, 0.25);
}
.btn-verde-claro:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(76, 175, 80, 0.35);
}
/* ==== CTA VER DETALLES (verde intenso) ==== */
.btn-cta {
    background: linear-gradient(135deg, #43a047, #1b5e20);
    box-shadow: 0 3px 8px rgba(27, 94, 32, 0.35);
    color: #fff !important;
}
.btn-cta:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(27, 94, 32, 0.45);
}
.mk-user-strip {
    background: #f1f8e9;           /* Verde MUY suave, seguro */
    color: #2e7d32;               /* Verde oscuro */
    padding: 10px 14px;
    border-radius: 8px;
    border: 1px solid #dcedc8;    /* Borde sutil */
    margin-bottom: 15px;
    font-size: 0.95rem;
}
.btn-azul-oscuro {
    background: linear-gradient(135deg, #15324c, #0e2234);
    color: #fff !important;
    box-shadow: 0 3px 8px rgba(21, 50, 76, 0.35);
    border: none !important;
}

.btn-azul-oscuro:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(21, 50, 76, 0.45);
}
.btn-verde {
    background: linear-gradient(135deg, #4caf50, #2e7d32);
    color: #fff !important;
    box-shadow: 0 3px 8px rgba(46, 125, 50, 0.3);
}
.btn-verde:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(46, 125, 50, 0.45);
}
.titulo-market {
    display: flex;
    align-items: center;
    gap: 10px; /* separa el texto del logo */
}

.logo-market {
    height: 40px; /* ajustá el tamaño que quieras */
    width: auto;
}

    </style>
</head>
<body>
<?php require __DIR__ . '/_navbar.php'; ?>
<!-- DATE BAR -->
<div class="datebar">
  <div class="container inner"><span id="fecha-hoy">—</span></div>
</div>
<style>
/* Fecha */
.datebar{background:var(--navy);color:#fff;font-weight:600}
.datebar .inner{height:40px;display:flex;align-items:center}
</style>
<section class="mk-hero">
    <div class="container">
        <div class="row align-items-center g-3">
            <div class="col-md-7">
              <h1 class="titulo-market">
                  Marketplace de 
                  <img src="img/fetra.png" alt="Fe.Tr.A" class="logo-market">
              </h1>
                <p>Compra, vendé o intercambiá productos y servicios con la comunidad de transportistas.</p>
            </div>
            <div class="col-md-5 text-md-end mk-hero-actions botones-market">


    <?php if ($logged): ?>
        <!--<a href="nuevo_producto_market.php" class="btn btn-success btn-sm btn-market">
            <i class="fas fa-plus-circle me-1"></i> Publicar producto
        </a>-->
    <?php else: ?>
        <a href="crear_usuario_market.php" class="btn btn-outline-light btn-sm btn-market">
            <i class="fas fa-user-plus me-1"></i> Crear cuenta para publicar
        </a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<main class="mk-main">
    <div class="container">

        <div class="mk-user-strip">
            <div>
                <?php if ($logged && $U): ?>
                    Estás conectado como <strong><?= htmlspecialchars($U['nombre'].' '.$U['apellido'], ENT_QUOTES, 'UTF-8') ?></strong>.
                <?php else: ?>
                    No iniciaste sesión. Para ver datos de contacto y publicar avisos, necesitás una cuenta.
                <?php endif; ?>
            </div>
            <div class="btn-group" role="group">
              <?php if ($logged && $U): ?>
          
                  <a href="perfil_market.php" class="btn btn-outline-primary btn-sm btn-market btn-azul">
                      <i class="fas fa-user me-1"></i> Mi perfil
                  </a>
          
                  <!-- NUEVO BOTÓN VERDE PUBLICAR -->
                  <a href="nuevo_producto_market.php" class="btn btn-success btn-sm btn-market btn-verde">
                      <i class="fas fa-plus-circle me-1"></i> Publicar nuevo producto
                  </a>
          
                  <a href="logout_market.php" class="btn btn-outline-danger btn-sm btn-market btn-rojo">
                      <i class="fas a-sign-out-alt me-1"></i> Cerrar sesión
                  </a>
          
              <?php else: ?>
          
                  <a href="login_market.php" class="btn btn-primary btn-sm btn-market btn-verde">
                      <i class="fas fa-sign-in-alt me-1"></i> Iniciar sesión
                  </a>
          
                  <a href="crear_usuario_market.php" class="btn btn-outline-secondary btn-sm btn-market btn-azul-oscuro">
                      <i class="fas fa-user-plus me-1"></i> Crear cuenta
                  </a>
          
              <?php endif; ?>

            </div>
        </div>

        <?php if (!$productos): ?>
            <div class="mk-grid-empty">
                <i class="fas fa-box-open"></i>
                <h3 class="h5 mb-2">Todavía no hay publicaciones</h3>
                <p class="text-muted mb-3">Cuando alguien publique un producto o servicio, va a aparecer acá.</p>
                <?php if ($logged): ?>
                    <a href="nuevo_producto_market.php" class="btn btn-success btn-sm btn-mk-cta">
                        <i class="fas fa-plus-circle me-1"></i> Publicar primer producto
                    </a>
                <?php else: ?>
                    <a href="crear_usuario_market.php" class="btn btn-primary btn-sm btn-mk-cta">
                        <i class="fas fa-user-plus me-1"></i> Crear cuenta para publicar
                    </a>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="mk-products-grid">
                <?php foreach ($productos as $P): ?>
                    <article class="mk-card">
                        <div class="mk-card-img-wrap">
                            <?php if (!empty($P['portada'])): ?>
                                <img src="<?= htmlspecialchars($P['portada'], ENT_QUOTES, 'UTF-8') ?>"
                                     alt="<?= htmlspecialchars($P['titulo'], ENT_QUOTES, 'UTF-8') ?>">
                            <?php else: ?>
                                <img src="https://via.placeholder.com/600x400?text=Sin+imagen"
                                     alt="Sin imagen">
                            <?php endif; ?>

                            <?php if ($P['modo_precio'] === 'consultar'): ?>
                                <span class="mk-card-badge mk-badge-consultar">Consultar precio</span>
                            <?php elseif ($P['precio'] !== null && $P['precio'] !== ''): ?>
                                <span class="mk-card-badge">
                                    $ <?= number_format((float)$P['precio'], 0, ',', '.') ?>
                                </span>
                            <?php endif; ?>
                        </div>

                        <div class="mk-card-body">
                            <div class="mk-card-title">
                                <?= htmlspecialchars($P['titulo'], ENT_QUOTES, 'UTF-8') ?>
                            </div>

                            <?php if (!empty($P['ubicacion'])): ?>
                                <div class="mk-card-location">
                                    <i class="fas fa-map-marker-alt me-1"></i>
                                    <?= htmlspecialchars($P['ubicacion'], ENT_QUOTES, 'UTF-8') ?>
                                </div>
                            <?php endif; ?>

                            <?php
                            $desc = trim((string)$P['descripcion']);
                            if ($desc !== '') {
                                $orig = $desc;
                                $desc = mb_substr($desc, 0, 140, 'UTF-8');
                                if (mb_strlen($orig, 'UTF-8') > 140) {
                                    $desc .= '…';
                                }
                            }
                            ?>
                            <?php if ($desc): ?>
                                <div class="mk-card-desc">
                                    <?= nl2br(htmlspecialchars($desc, ENT_QUOTES, 'UTF-8')) ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="mk-card-footer">
                            <small>
                                <i class="fas fa-user me-1"></i>
                                <?= htmlspecialchars($P['u_nombre'].' '.$P['u_apellido'], ENT_QUOTES, 'UTF-8') ?>
                            </small>
                            <a href="ver_producto_market.php?id=<?= (int)$P['id'] ?>"
         class="btn btn-primary btn-sm btn-market btn-cta">
          Ver detalles
      </a>

                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</main>

<?php require __DIR__ . '/_footer.php'; ?>
<?php require __DIR__ . '/_navbar_script.php'; ?>
<script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
</body>
</html>
