<?php
require_once 'includes/header.php';

// Get product slug from URL
$product_slug = isset($_GET['product']) ? $_GET['product'] : '';

// If no product slug provided, redirect to homepage
if (empty($product_slug)) {
    header('Location: /');
    exit;
}

// Get product data
$product = get_product_by_slug($product_slug);

// If product not found, show 404 page
if (!$product) {
    http_response_code(404);
    include '404.php';
    exit;
}

// Get product images
$product_images = get_rows("SELECT * FROM product_images WHERE product_id = ? ORDER BY sort_order ASC", [$product['id']]);

// If no images, add default image
if (empty($product_images)) {
    $product_images = [
        ['id' => 0, 'image' => 'default-product.jpg', 'alt_text' => $product['name']]
    ];
}

// Get product categories
$product_categories = get_rows("
    SELECT c.id, c.name, c.slug 
    FROM categories c 
    JOIN product_categories pc ON c.id = pc.category_id 
    WHERE pc.product_id = ?
", [$product['id']]);

// Get product reviews
$product_reviews = get_rows("
    SELECT r.*, u.name as user_name 
    FROM reviews r 
    LEFT JOIN users u ON r.user_id = u.id 
    WHERE r.product_id = ? AND r.status = 'approved' 
    ORDER BY r.created_at DESC
", [$product['id']]);

// Calculate average rating
$avg_rating = $product['rating_count'] > 0 ? round($product['rating_sum'] / $product['rating_count'], 1) : 0;

// Get recommended products
$recommended_products = get_recommended_products($product['id'], 4);

// Calculate discount percent if on sale
$discount_percent = 0;
if (!empty($product['sale_price']) && $product['price'] > 0) {
    $discount_percent = round((($product['price'] - $product['sale_price']) / $product['price']) * 100);
}

// Generate meta tags
$meta_title = !empty($product['meta_title']) ? $product['meta_title'] : $product['name'] . ' - ' . get_setting('site_name');
$meta_description = !empty($product['meta_description']) ? $product['meta_description'] : strip_tags($product['short_description']);
$meta_image = !empty($product_images[0]['image']) ? UPLOADS_URL . '/products/' . $product_images[0]['image'] : '';
?>

<!-- Schema.org Product Data -->
<script type="application/ld+json">
{
  "@context": "https://schema.org/",
  "@type": "Product",
  "name": "<?php echo htmlspecialchars($product['name']); ?>",
  "image": "<?php echo UPLOADS_URL . '/products/' . $product_images[0]['image']; ?>",
  "description": "<?php echo htmlspecialchars(strip_tags($product['short_description'])); ?>",
  "sku": "<?php echo $product['sku']; ?>",
  "brand": {
    "@type": "Brand",
    "name": "Hugong"
  },
  "offers": {
    "@type": "Offer",
    "url": "<?php echo SITE_URL . '/' . $product['slug']; ?>",
    "priceCurrency": "RSD",
    "price": "<?php echo $product['sale_price'] ? $product['sale_price'] : $product['price']; ?>",
    "priceValidUntil": "<?php echo date('Y-m-d', strtotime('+1 year')); ?>",
    "availability": "https://schema.org/InStock"
  }
  <?php if ($product['rating_count'] > 0): ?>,
  "aggregateRating": {
    "@type": "AggregateRating",
    "ratingValue": "<?php echo $avg_rating; ?>",
    "reviewCount": "<?php echo $product['rating_count']; ?>"
  }
  <?php endif; ?>
}
</script>

<!-- Breadcrumbs -->
<div class="breadcrumbs-wrapper">
    <div class="container">
        <nav class="breadcrumbs" aria-label="breadcrumb">
            <ol>
                <li><a href="/">Početna</a></li>
                <?php foreach($product_categories as $category): ?>
                <li><a href="/<?php echo $category['slug']; ?>"><?php echo $category['name']; ?></a></li>
                <?php endforeach; ?>
                <li class="active" aria-current="page"><?php echo $product['name']; ?></li>
            </ol>
        </nav>
    </div>
</div>

<div class="product-container">
    <div class="container">
        <!-- Main Product Section -->
        <div class="product-main-wrapper">
            <!-- Product Info Section (First on mobile) -->
            <div class="product-info-section">
                <div class="product-header">
                    <div class="product-brand">
                        <img src="/uploads/hugong-logo.png" alt="Hugong" width="120">
                    </div>
                    
                    <h1 class="product-title"><?php echo $product['name']; ?></h1>
                </div>
                
                <!-- Product Value Propositions -->
                <div class="value-propositions">
                    <div class="value-item <?php echo (isset($product['stock']) && $product['stock'] > 0) ? 'available' : 'unavailable'; ?>">
                        <div class="value-icon">
                            <?php if (isset($product['stock']) && $product['stock'] > 0): ?>
                            <!-- Zelena ikona kvačice za dostupne proizvode -->
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                                <polyline points="22 4 12 14.01 9 11.01"></polyline>
                            </svg>
                            <?php else: ?>
                            <!-- Crvena ikona X za nedostupne proizvode -->
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <circle cx="12" cy="12" r="10"></circle>
                                <line x1="15" y1="9" x2="9" y2="15"></line>
                                <line x1="9" y1="9" x2="15" y2="15"></line>
                            </svg>
                            <?php endif; ?>
                        </div>
                        <div class="value-text">
                            <?php echo (isset($product['stock']) && $product['stock'] > 0) ? 'DOSTUPNO' : 'NIJE DOSTUPAN'; ?>
                        </div>
                    </div>            
                    <div class="value-item price-guarantee">
                        <div class="value-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M12 1v22M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path>
                            </svg>
                        </div>
                        <div class="value-text">GARANTOVANO NAJNIŽA CENA</div>
                    </div>
                    
                    <div class="value-item free-shipping">
                        <div class="value-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <rect x="1" y="3" width="15" height="13"></rect>
                                <polygon points="16 8 20 8 23 11 23 16 16 16 16 8"></polygon>
                                <circle cx="5.5" cy="18.5" r="2.5"></circle>
                                <circle cx="18.5" cy="18.5" r="2.5"></circle>
                            </svg>
                        </div>
                        <div class="value-text">BESPLATNA ISPORUKA</div>
                    </div>
                </div>
                
                <!-- Product Price Section -->
                <div class="product-price-section">
                    <?php if (!empty($product['sale_price'])): ?>
                    <div class="price-wrapper sale">
                        <div class="current-price"><?php echo number_format($product['sale_price'], 0, ',', '.'); ?> RSD</div>
                        <div class="old-price"><?php echo number_format($product['price'], 0, ',', '.'); ?> RSD</div>
                        <div class="discount-badge">-<?php echo $discount_percent; ?>%</div>
                    </div>
                    <?php else: ?>
                    <div class="price-wrapper">
                        <div class="current-price"><?php echo number_format($product['price'], 0, ',', '.'); ?> RSD</div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Ikone garancije i dodatnih pogodnosti -->
                <div class="product-benefits">
                    <div class="benefit-item">
                        <div class="benefit-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                                <line x1="16" y1="2" x2="16" y2="6"></line>
                                <line x1="8" y1="2" x2="8" y2="6"></line>
                                <line x1="3" y1="10" x2="21" y2="10"></line>
                            </svg>
                        </div>
                        <div class="benefit-text">Garancija 25 meseci</div>
                    </div>
                    
                    <div class="benefit-item">
                        <div class="benefit-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"></path>
                            </svg>
                        </div>
                        <div class="benefit-text">Rezervni delovi 7 godina</div>
                    </div>
                    
                    <div class="benefit-item">
                        <div class="benefit-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"></path>
                            </svg>
                        </div>
                        <div class="benefit-text">HUGONG - najbolji u klasi</div>
                    </div>
                </div>
                
            </div>
            
            <!-- Product Gallery Column (Second on mobile) -->
            <div class="product-gallery-section">
                <div class="main-image-container">
                    <img src="<?php echo UPLOADS_URL . '/products/' . $product_images[0]['image']; ?>" 
                         alt="<?php echo $product_images[0]['alt_text'] ?? $product['name']; ?>" 
                         id="main-product-image">
                    
                    <div class="image-zoom-trigger" id="zoom-trigger">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <circle cx="11" cy="11" r="8"></circle>
                            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                            <line x1="11" y1="8" x2="11" y2="14"></line>
                            <line x1="8" y1="11" x2="14" y2="11"></line>
                        </svg>
                    </div>
                </div>
                
                <?php if (count($product_images) > 1): ?>
                <div class="product-thumbnails">
                    <?php foreach ($product_images as $index => $image): ?>
                    <div class="thumbnail <?php echo $index === 0 ? 'active' : ''; ?>" 
                         data-image="<?php echo UPLOADS_URL . '/products/' . $image['image']; ?>">
                        <img src="<?php echo UPLOADS_URL . '/products/' . $image['image']; ?>" 
                             alt="<?php echo $image['alt_text'] ?? $product['name'] . ' - thumbnail'; ?>">
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Purchase and Shipping Options - Position after gallery but before description -->
        <div class="product-actions-section">
            <!-- Purchase Options -->
            <div class="purchase-options">
                <div class="quantity-selector">
                    <label for="quantity">Količina:</label>
                    <div class="quantity-controls">
                        <button type="button" class="quantity-btn minus" aria-label="Smanji količinu">-</button>
                        <input type="number" id="quantity" name="quantity" value="1" min="1" max="99">
                        <button type="button" class="quantity-btn plus" aria-label="Povećaj količinu">+</button>
                    </div>
                </div>
                
                <button type="button" id="buy-now-btn" class="buy-button" data-product-id="<?php echo $product['id']; ?>">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="9" cy="21" r="1"></circle>
                        <circle cx="20" cy="21" r="1"></circle>
                        <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                    </svg>
                    KUPI ODMAH
                </button>
            </div>
            
            <!-- Shipping Options -->
            <div class="shipping-options">
                <div class="shipping-option">
                    <div class="option-text"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <rect x="1" y="3" width="15" height="13"></rect>
                            <polygon points="16 8 20 8 23 11 23 16 16 16 16 8"></polygon>
                            <circle cx="5.5" cy="18.5" r="2.5"></circle>
                            <circle cx="18.5" cy="18.5" r="2.5"></circle>
                        </svg> Poručite online i izaberite dostavu</div>
                </div>
                
                <div class="shipping-option">
                    <div class="option-text"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                            <polyline points="9 22 9 12 15 12 15 22"></polyline>
                        </svg> Preuzmite u magacinu na adresi Oskara Daviča 2, Kragujevac</div>
                </div>
            </div>
            
            <!-- Trust Badges -->
            <div class="trust-badges">
                <div class="trust-badge">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                        <line x1="16" y1="2" x2="16" y2="6"></line>
                        <line x1="8" y1="2" x2="8" y2="6"></line>
                        <line x1="3" y1="10" x2="21" y2="10"></line>
                    </svg>
                    <span>Originalna garancija</span>
                </div>
                
                <div class="trust-badge">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3H14z"></path>
                        <path d="M7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"></path>
                    </svg>
                    <span>Povrat robe</span>
                </div>
                
                <div class="trust-badge">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                        <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                    </svg>
                    <span>Sigurno plaćanje</span>
                </div>
            </div>
        </div>
        
        <!-- Product Short Description -->
        <div class="product-description-section">
            <div class="description-title">Kratak opis proizvoda</div>
            <div class="short-description">
                <?php echo $product['short_description']; ?>
            </div>
            
            <?php if (!empty($product['features'])): 
                $features = explode("\n", $product['features']);
            ?>
            <div class="product-features">
                <div class="features-title">Ključne karakteristike</div>
                <ul class="features-list">
                    <?php foreach($features as $feature): 
                        if (!empty(trim($feature))): ?>
                    <li><?php echo trim($feature); ?></li>
                    <?php endif; endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Product Tabs Section -->
        <div class="product-tabs-section">
            <div class="tabs-nav">
                <button type="button" class="tab-btn active" data-tab="tab-description">Detaljan opis</button>
                <button type="button" class="tab-btn" data-tab="tab-specifications">Specifikacije</button>
                <button type="button" class="tab-btn" data-tab="tab-declaration">Deklaracija</button>
                <button type="button" class="tab-btn" data-tab="tab-reviews">Recenzije (<?php echo count($product_reviews); ?>)</button>
            </div>
            
            <div class="tabs-content">
                <!-- Description Tab Content -->
                <div id="tab-description" class="tab-content active">
                    <?php echo $product['description']; ?>
                </div>
                
                <!-- Specifications Tab Content -->
                <div id="tab-specifications" class="tab-content">
                    <?php
                    if (!empty($product['specifications'])) {
                        $specifications = json_decode($product['specifications'], true);
                        
                        if (!empty($specifications) && is_array($specifications)): ?>
                        <div class="specifications-table">
                            <table>
                                <?php foreach ($specifications as $spec): 
                                    if (isset($spec['name']) && isset($spec['value'])): ?>
                                <tr>
                                    <th><?php echo htmlspecialchars($spec['name']); ?></th>
                                    <td><?php echo htmlspecialchars($spec['value']); ?></td>
                                </tr>
                                <?php endif; endforeach; ?>
                            </table>
                        </div>
                        <?php else: ?>
                        <p>Nema dostupnih specifikacija za ovaj proizvod.</p>
                        <?php endif;
                    } else { ?>
                        <p>Nema dostupnih specifikacija za ovaj proizvod.</p>
                    <?php } ?>
                </div>
                
                <!-- Declaration Tab Content -->
                <div id="tab-declaration" class="tab-content">
                    <div class="declaration-content">
                        <table class="declaration-table">
                            <tr>
                                <th>Naziv proizvoda:</th>
                                <td><?php echo $product['name']; ?></td>
                            </tr>
                            <tr>
                                <th>Uvoznik:</th>
                                <td>Varcom-s d.o.o. Smederevo</td>
                            </tr>
                            <tr>
                                <th>Zemlja porekla:</th>
                                <td>Kina</td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <!-- Reviews Tab Content -->
                <div id="tab-reviews" class="tab-content">
                    <div class="reviews-section">
                        <?php if ($product['rating_count'] > 0): ?>
                        <div class="rating-summary">
                            <div class="rating-average">
                                <div class="average-number"><?php echo number_format($avg_rating, 1); ?></div>
                                <div class="stars">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <span class="star <?php echo $i <= $avg_rating ? 'filled' : ''; ?>">&#9733;</span>
                                    <?php endfor; ?>
                                </div>
                                <div class="rating-count"><?php echo $product['rating_count']; ?> <?php echo $product['rating_count'] == 1 ? 'ocena' : 'ocene'; ?></div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($product_reviews)): ?>
                        <div class="reviews-list">
                            <?php foreach ($product_reviews as $review): ?>
                            <div class="review-item">
                                <div class="review-header">
                                    <div class="reviewer-name"><?php echo htmlspecialchars($review['name']); ?></div>
                                    <div class="review-date"><?php echo date('d.m.Y.', strtotime($review['created_at'])); ?></div>
                                </div>
                                <div class="review-rating">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <span class="star <?php echo $i <= $review['rating'] ? 'filled' : ''; ?>">&#9733;</span>
                                    <?php endfor; ?>
                                </div>
                                <div class="review-content">
                                    <?php echo nl2br(htmlspecialchars($review['comment'])); ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php else: ?>
                        <p class="no-reviews">Još uvek nema recenzija za ovaj proizvod.</p>
                        <?php endif; ?>
                        
                        <div class="write-review">
                            <button type="button" id="write-review-btn" class="btn-secondary">Napišite recenziju</button>
                            
                            <div id="review-form-container" style="display: none;">
                                <h3>Vaša ocena proizvoda</h3>
                                
                                <?php if (is_logged_in()): ?>
                                <form id="review-form" action="/submit-review.php" method="post">
                                    <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                                    
                                    <div class="form-group">
                                        <label>Vaša ocena</label>
                                        <div class="rating-input">
                                            <?php for ($i = 5; $i >= 1; $i--): ?>
                                            <input type="radio" id="star<?php echo $i; ?>" name="rating" value="<?php echo $i; ?>" <?php echo $i == 5 ? 'checked' : ''; ?>>
                                            <label for="star<?php echo $i; ?>">&#9733;</label>
                                            <?php endfor; ?>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="review-comment">Vaš komentar</label>
                                        <textarea id="review-comment" name="comment" rows="5" required></textarea>
                                    </div>
                                    
                                    <div class="form-actions">
                                        <button type="button" id="cancel-review" class="btn-cancel">Odustani</button>
                                        <button type="submit" class="btn-submit">Pošalji recenziju</button>
                                    </div>
                                </form>
                                <?php else: ?>
                                <div class="login-prompt">
                                    <p>Morate biti prijavljeni da biste ostavili recenziju.</p>
                                    <a href="/login.php" class="btn-link">Prijavite se</a>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Similar Products Section - Enhanced Display -->
        <?php if (!empty($recommended_products)): ?>
        <div class="similar-products-section">
            <h2 class="section-title">Slični proizvodi</h2>
            
            <div class="recommended-products-container">
                <div class="scroll-hint left">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <polyline points="15 18 9 12 15 6"></polyline>
                    </svg>
                </div>
                
                <div class="recommended-products-wrapper">
                    <div class="recommended-products-scroll">
                        <?php foreach($recommended_products as $related): ?>
                        <div class="product-card">
                            <a href="/<?php echo $related['slug']; ?>" class="card-link-overlay"></a>
                            
                            <?php if (!empty($related['sale_price'])): 
                                $related_discount = round((($related['price'] - $related['sale_price']) / $related['price']) * 100);
                            ?>
                            <div class="product-discount">-<?php echo $related_discount; ?>%</div>
                            <?php endif; ?>
                            
                            <div class="product-image">
                                <img src="<?php echo !empty($related['image']) ? UPLOADS_URL . '/products/' . $related['image'] : '/assets/images/no-image.jpg'; ?>" 
                                     alt="<?php echo $related['name']; ?>">
                            </div>
                            
                            <div class="product-details">
                                <h3 class="product-name">
                                    <span><?php echo $related['name']; ?></span>
                                </h3>
                                
                                <div class="product-price">
                                    <?php if (!empty($related['sale_price'])): ?>
                                    <div class="price-wrapper">
                                        <span class="price-old"><?php echo number_format($related['price'], 0, ',', '.'); ?> RSD</span>
                                        <span class="price-current"><?php echo number_format($related['sale_price'], 0, ',', '.'); ?> RSD</span>
                                    </div>
                                    <?php else: ?>
                                    <span class="price-current"><?php echo number_format($related['price'], 0, ',', '.'); ?> RSD</span>
                                    <?php endif; ?>
                                </div>
                                
                                <span class="btn-view">VIDI VIŠE ></span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <div class="scroll-hint right active">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <polyline points="9 18 15 12 9 6"></polyline>
                    </svg>
                </div>
            </div>
            
            <div class="scroll-dots">
                <span class="dot active"></span>
                <span class="dot"></span>
                <?php if(count($recommended_products) > 2): ?>
                <span class="dot"></span>
                <?php endif; ?>
                <?php if(count($recommended_products) > 3): ?>
                <span class="dot"></span>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Image Zoom Modal -->
<div id="image-modal" class="modal">
    <div class="modal-overlay"></div>
    <div class="modal-content">
        <button type="button" class="modal-close" aria-label="Zatvori">&times;</button>
        <img src="" alt="" id="zoomed-image">
    </div>
</div>

<!-- Sticky Buy Now for Mobile -->
<div class="sticky-cart">
    <div class="sticky-product-info">
        <div class="sticky-product-name"><?php echo $product['name']; ?></div>
        <div class="sticky-product-price">
            <?php echo $product['sale_price'] ? number_format($product['sale_price'], 0, ',', '.') : number_format($product['price'], 0, ',', '.'); ?> RSD
        </div>
    </div>
    <button type="button" class="sticky-buy-btn" data-product-id="<?php echo $product['id']; ?>">KUPI</button>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Fixed header functionality for mobile
    const siteHeader = document.querySelector('.site-header');
    const headerHeight = siteHeader ? siteHeader.offsetHeight : 0;
    
    // Function to check if we're on mobile
    function isMobile() {
        return window.innerWidth < 768;
    }
    
    // Function to set fixed header on mobile
    function setupMobileHeader() {
        if (siteHeader && isMobile()) {
            siteHeader.classList.add('fixed-header');
            document.body.style.paddingTop = headerHeight + 'px';
        } else if (siteHeader) {
            siteHeader.classList.remove('fixed-header');
            document.body.style.paddingTop = '0';
        }
    }
    
    // Initial setup
    setupMobileHeader();
    
    // Update on resize
    window.addEventListener('resize', setupMobileHeader);
    
    // Thumbnail gallery functionality
    const mainImage = document.getElementById('main-product-image');
    const thumbnails = document.querySelectorAll('.thumbnail');
    
    thumbnails.forEach(thumb => {
        thumb.addEventListener('click', function() {
            const imageUrl = this.getAttribute('data-image');
            
            // Update main image
            mainImage.src = imageUrl;
            
            // Remove active class from all thumbnails
            thumbnails.forEach(t => t.classList.remove('active'));
            
            // Add active class to clicked thumbnail
            this.classList.add('active');
        });
    });
    
    // Image zoom modal
    const modal = document.getElementById('image-modal');
    const zoomedImage = document.getElementById('zoomed-image');
    const zoomTrigger = document.getElementById('zoom-trigger');
    const modalClose = document.querySelector('.modal-close');
    const modalOverlay = document.querySelector('.modal-overlay');
    
    function openModal(imageUrl, altText) {
        zoomedImage.src = imageUrl;
        zoomedImage.alt = altText || '';
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
    
    function closeModal() {
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }
    
    // Open modal on zoom icon click
    if (zoomTrigger) {
        zoomTrigger.addEventListener('click', function() {
            openModal(mainImage.src, mainImage.alt);
        });
    }
    
    // Also allow clicking directly on the main image
    if (mainImage) {
        mainImage.addEventListener('click', function() {
            openModal(this.src, this.alt);
        });
    }
    
    // Close modal events
    if (modalClose) {
        modalClose.addEventListener('click', closeModal);
    }
    
    if (modalOverlay) {
        modalOverlay.addEventListener('click', closeModal);
    }
    
    // Close on escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && modal.classList.contains('active')) {
            closeModal();
        }
    });
    
    // Tabs functionality
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');
    
    tabBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const tabId = this.getAttribute('data-tab');
            
            // Remove active class from all buttons and content
            tabBtns.forEach(b => b.classList.remove('active'));
            tabContents.forEach(c => c.classList.remove('active'));
            
            // Add active class to clicked button and content
            this.classList.add('active');
            document.getElementById(tabId).classList.add('active');
        });
    });
    
    // Quantity controls
    const minusBtn = document.querySelector('.quantity-btn.minus');
    const plusBtn = document.querySelector('.quantity-btn.plus');
    const quantityInput = document.getElementById('quantity');
    
    if (minusBtn && plusBtn && quantityInput) {
        minusBtn.addEventListener('click', function() {
            let value = parseInt(quantityInput.value);
            if (value > 1) {
                quantityInput.value = value - 1;
            }
        });
        
        plusBtn.addEventListener('click', function() {
            let value = parseInt(quantityInput.value);
            if (value < 99) {
                quantityInput.value = value + 1;
            }
        });
    }
    
    // Review form toggle
    const writeReviewBtn = document.getElementById('write-review-btn');
    const reviewFormContainer = document.getElementById('review-form-container');
    const cancelReviewBtn = document.getElementById('cancel-review');
    
    if (writeReviewBtn && reviewFormContainer) {
        writeReviewBtn.addEventListener('click', function() {
            reviewFormContainer.style.display = 'block';
            writeReviewBtn.style.display = 'none';
        });
    }
    
    if (cancelReviewBtn && reviewFormContainer && writeReviewBtn) {
        cancelReviewBtn.addEventListener('click', function() {
            reviewFormContainer.style.display = 'none';
            writeReviewBtn.style.display = 'inline-block';
        });
    }
    
    // Buy Now functionality
    const buyNowBtn = document.getElementById('buy-now-btn');
    const stickyBuyBtn = document.querySelector('.sticky-buy-btn');
    
function buyNow(productId, quantity) {
    // Kreirajte FormData objekat umesto JSON-a
    const formData = new FormData();
    formData.append('product_id', productId);
    formData.append('quantity', quantity);
    
    fetch('/add-to-cart.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            window.location.href = '/checkout';
        } else {
            alert('Greška prilikom dodavanja u korpu: ' + (data.message || 'Nepoznata greška'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Došlo je do greške pri komunikaciji sa serverom.');
    });
}
    
    if (buyNowBtn) {
        buyNowBtn.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            const quantity = document.getElementById('quantity').value;
            buyNow(productId, quantity);
        });
    }
    
    if (stickyBuyBtn) {
        stickyBuyBtn.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            const quantity = document.getElementById('quantity').value;
            buyNow(productId, quantity);
        });
    }
    
    // Sticky cart visibility on scroll
    const stickyCart = document.querySelector('.sticky-cart');
    const productInfoSection = document.querySelector('.product-info-section');
    
    if (stickyCart && productInfoSection) {
        window.addEventListener('scroll', function() {
            const rect = productInfoSection.getBoundingClientRect();
            
            if (rect.bottom < 0) {
                stickyCart.classList.add('visible');
            } else {
                stickyCart.classList.remove('visible');
            }
        });
    }
    
    // Recommended products scroll functionality
    const scrollContainer = document.querySelector('.recommended-products-scroll');
    const leftHint = document.querySelector('.scroll-hint.left');
    const rightHint = document.querySelector('.scroll-hint.right');
    const dots = document.querySelectorAll('.scroll-dots .dot');
    
    if (scrollContainer) {
        // Show/hide scroll hints
        scrollContainer.addEventListener('scroll', function() {
            const maxScroll = scrollContainer.scrollWidth - scrollContainer.clientWidth;
            
            if (scrollContainer.scrollLeft > 10) {
                leftHint.classList.add('active');
            } else {
                leftHint.classList.remove('active');
            }
            
            if (scrollContainer.scrollLeft < maxScroll - 10) {
                rightHint.classList.add('active');
            } else {
                rightHint.classList.remove('active');
            }
            
            // Update dots
            const scrollProgress = scrollContainer.scrollLeft / maxScroll;
            const activeDotIndex = Math.min(
                Math.floor(scrollProgress * dots.length),
                dots.length - 1
            );
            
            dots.forEach((dot, index) => {
                dot.classList.toggle('active', index === activeDotIndex);
            });
        });
        
        // Scroll left/right on hint click
        if (leftHint) {
            leftHint.addEventListener('click', function() {
                scrollContainer.scrollBy({
                    left: -220,
                    behavior: 'smooth'
                });
            });
        }
        
        if (rightHint) {
            rightHint.addEventListener('click', function() {
                scrollContainer.scrollBy({
                    left: 220,
                    behavior: 'smooth'
                });
            });
        }
        
        // Click on dots to scroll to position
        dots.forEach((dot, index) => {
            dot.addEventListener('click', function() {
                const maxScroll = scrollContainer.scrollWidth - scrollContainer.clientWidth;
                const scrollTo = (maxScroll / (dots.length - 1)) * index;
                
                scrollContainer.scrollTo({
                    left: scrollTo,
                    behavior: 'smooth'
                });
            });
        });
    }
});
</script>

<?php require_once 'includes/footer.php'; ?>