<?php
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/navbar.php';
require_once __DIR__ . '/../config/db.php';



$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT p.*, c.name AS category FROM products p LEFT JOIN categories c ON c.id=p.category_id WHERE p.id=:id");
$stmt->execute([':id'=>$id]);
$p = $stmt->fetch();

if (!$p) {
    echo "<div class='container my-4'><div class='alert alert-danger'>Producto no encontrado</div></div>";
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

$img = !empty($p['image_url']) ? $p['image_url'] : (!empty($p['image']) ? (BASE_URL . '/../assets/img/' . $p['image']) : 'https://picsum.photos/seed/noimg/600/400');
?>

<div class="container my-4">
    <div class="row">
        <?php
// Obtener todas las imágenes del producto
$stmtImgs = $pdo->prepare("SELECT image FROM product_images WHERE product_id = :pid");
$stmtImgs->execute([':pid' => $p['id']]);
$images = $stmtImgs->fetchAll(PDO::FETCH_COLUMN);

if (!$images) {
    $images[] = 'https://picsum.photos/seed/noimg/600/400';
}
?>

<div class="col-md-5">
    <?php foreach($images as $img): ?>
        <img src="<?= BASE_URL . '/../assets/img/' . $img ?>" class="img-fluid rounded mb-2" alt="<?= htmlspecialchars($p['name']) ?>">
    <?php endforeach; ?>
</div>

        <div class="col-md-7">
            <h1 class="h4"><?= htmlspecialchars($p['name']) ?></h1>
            <p class="text-muted"><?= htmlspecialchars($p['category'] ?? 'General') ?></p>
            <p class="h5">$ <?= number_format((float)$p['price'],2,',','.') ?></p>
            <p><?= nl2br(htmlspecialchars($p['description'])) ?></p>
            <a href="../api/add_to_cart.php?action=add&id=<?= (int)$p['id'] ?>" class="btn btn-primary">Agregar al carrito</a>
        </div>
    </div>
</div>
<?php $producto_id = $p['id'];
include __DIR__ . '/comentarios.php';
 ?>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>