<?php
require_once 'connection.php';

$laptop_id = $_GET['id'] ?? 0;

$stmt = $pdo->prepare("SELECT brand, model FROM laptops WHERE id = ?");
$stmt->execute([$laptop_id]);
$laptop = $stmt->fetch();

$stmt = $pdo->prepare("SELECT image_url FROM laptop_images WHERE laptop_id = ? ORDER BY sort_order");
$stmt->execute([$laptop_id]);
$images = $stmt->fetchAll();

if (empty($images)) {
    echo '<div class="alert alert-info">No gallery images available for this product.</div>';
    exit();
}
?>

<div class="modal-gallery">
    <div class="gallery-main-image">
        <img id="mainGalleryImage" src="<?php echo $images[0]['image_url']; ?>" alt="<?php echo htmlspecialchars($laptop['brand'] . ' ' . $laptop['model']); ?>" style="max-width: 100%; max-height: 400px; object-fit: contain;">
    </div>
    
    <div class="gallery-thumbnails text-center">
        <?php foreach($images as $index => $img): ?>
            <img src="<?php echo $img['image_url']; ?>" 
                 class="gallery-thumb <?php echo $index == 0 ? 'active' : ''; ?>" 
                 onclick="setMainImage(this, '<?php echo $img['image_url']; ?>')"
                 style="width: 80px; height: 80px; object-fit: cover; cursor: pointer; margin: 5px;">
        <?php endforeach; ?>
    </div>
</div>

<script>
function setMainImage(element, imageUrl) {
    document.getElementById('mainGalleryImage').src = imageUrl;
    document.querySelectorAll('.gallery-thumb').forEach(thumb => {
        thumb.classList.remove('active');
    });
    element.classList.add('active');
}
</script>