<?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

$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';
}

// Primera imagen como predeterminada
$mainImage = $images[0];
?>

<div class="col-md-5">
    <div class="mb-3">
        <!-- Imagen principal uniforme -->
        <img id="mainProductImage" src="<?= BASE_URL . '/../assets/img/' . $mainImage ?>" 
             class="img-fluid rounded" 
             alt="<?= htmlspecialchars($p['name']) ?>" 
             style="width:100%; height:400px; object-fit:cover;">
    </div>

    <!-- Miniaturas uniformes -->
    <div class="d-flex flex-wrap gap-2">
        <?php foreach ($images as $img): ?>
            <img src="<?= BASE_URL . '/../assets/img/' . $img ?>" 
                 class="img-thumbnail" 
                 style="width:70px; height:70px; object-fit:cover; cursor:pointer;" 
                 onclick="document.getElementById('mainProductImage').src='<?= BASE_URL . '/../assets/img/' . $img ?>'">
        <?php endforeach; ?>
    </div>
</div>


<?php $producto_id = $p['id'];
include __DIR__ . '/comentarios.php';
?>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>