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

// Get product slug from URL
$product_slug = isset($_GET['product']) ? trim($_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 with improved meta description
$meta_title = !empty($product['meta_title']) ? 
    $product['meta_title'] : 
    $product['name'] . ' - ' . implode(' & ', array_column($product_categories, 'name')) . ' | ' . get_setting('site_name');

$meta_description = !empty($product['meta_description']) ? 
    $product['meta_description'] : 
    'Kupite ' . $product['name'] . ' ' . 
    (!empty($product['sale_price']) ? 'po ceni od samo ' . number_format($product['sale_price'], 0, ',', '.') . ' RSD' : '') . 
    '. ' . mb_substr(strip_tags($product['short_description']), 0, 150) . '... Besplatna isporuka, garancija 25 meseci.';

$meta_image = !empty($product_images[0]['image']) ? UPLOADS_URL . '/products/' . $product_images[0]['image'] : '';

// Get the current full URL for canonical
$current_url = SITE_URL . '/' . $product_slug;

// Product specifications as structured array
$specifications = !empty($product['specifications']) ? json_decode($product['specifications'], true) : [];
?>

<!-- Additional SEO meta tags -->
<link rel="canonical" href="<?php echo $current_url; ?>">

<!-- Open Graph and Twitter Card tags -->
<meta property="og:type" content="product">
<meta property="og:title" content="<?php echo htmlspecialchars($meta_title); ?>">
<meta property="og:description" content="<?php echo htmlspecialchars($meta_description); ?>">
<meta property="og:url" content="<?php echo $current_url; ?>">
<meta property="og:image" content="<?php echo $meta_image; ?>">
<meta property="og:price:amount" content="<?php echo $product['sale_price'] ? $product['sale_price'] : $product['price']; ?>">
<meta property="og:price:currency" content="RSD">
<meta property="og:availability" content="<?php echo (isset($product['stock']) && $product['stock'] > 0) ? 'instock' : 'oos'; ?>">
<meta property="product:brand" content="Hugong">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="<?php echo htmlspecialchars($meta_title); ?>">
<meta name="twitter:description" content="<?php echo htmlspecialchars($meta_description); ?>">
<meta name="twitter:image" content="<?php echo $meta_image; ?>">

<!-- Schema.org Product Data - Enhanced -->
<script type="application/ld+json">
{
  "@context": "https://schema.org/",
  "@type": "Product",
  "name": "<?php echo htmlspecialchars($product['name']); ?>",
  "image": [
    <?php foreach($product_images as $index => $image): ?>
    "<?php echo UPLOADS_URL . '/products/' . $image['image']; ?>"<?php echo ($index < count($product_images) - 1) ? ',' : ''; ?>
    <?php endforeach; ?>
  ],
  "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 $current_url; ?>",
    "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/<?php echo (isset($product['stock']) && $product['stock'] > 0) ? 'InStock' : 'OutOfStock'; ?>",
    "itemCondition": "https://schema.org/NewCondition"
  }
  <?php if ($product['rating_count'] > 0): ?>,
  "aggregateRating": {
    "@type": "AggregateRating",
    "ratingValue": "<?php echo $avg_rating; ?>",
    "reviewCount": "<?php echo $product['rating_count']; ?>"
  }
  <?php endif; ?>
}
</script>

<!-- Structured data for breadcrumbs -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [
    {
      "@type": "ListItem",
      "position": 1,
      "name": "Početna",
      "item": "<?php echo SITE_URL; ?>"
    },
    <?php $position = 2; foreach($product_categories as $index => $category): ?>
    {
      "@type": "ListItem",
      "position": <?php echo $position++; ?>,
      "name": "<?php echo htmlspecialchars($category['name']); ?>",
      "item": "<?php echo SITE_URL . '/' . $category['slug']; ?>"
    },
    <?php endforeach; ?>
    {
      "@type": "ListItem",
      "position": <?php echo $position; ?>,
      "name": "<?php echo htmlspecialchars($product['name']); ?>",
      "item": "<?php echo $current_url; ?>"
    }
  ]
}
</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 Gallery Column -->
            <div class="product-gallery-section">
                <div class="main-image-container">
                    <img src="<?php echo UPLOADS_URL . '/products/' . $product_images[0]['image']; ?>" 
                         alt="<?php echo htmlspecialchars($product_images[0]['alt_text'] ?? $product['name']); ?>" 
                         id="main-product-image">
                    
                    
                </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 htmlspecialchars($image['alt_text'] ?? $product['name'] . ' - thumbnail'); ?>">
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Product Info Section -->
            <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>
                    
                    <?php if ($product['rating_count'] > 0): ?>
                    <div class="product-rating">
                        <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-text">
                            <span><?php echo number_format($avg_rating, 1); ?></span>/5 
                            (<span><?php echo $product['rating_count']; ?></span> ocena)
                            <a href="#tab-reviews" class="scroll-to-reviews">Pogledaj recenzije</a>
                        </div>
                    </div>
                    <?php endif; ?>
                </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): ?>
                            <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" aria-hidden="true">
                                <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: ?>
                            <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" aria-hidden="true">
                                <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" aria-hidden="true">
                                <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">
                            <span>GARANTOVANO NAJNIŽA CENA</span>
                            <a href="#" class="price-match-trigger" data-product-id="<?php echo $product['id']; ?>">Našli ste jeftinije?</a>
                        </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" aria-hidden="true">
                                <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">
                            <span>BESPLATNA ISPORUKA</span>
                            <small>Za sve porudžbine</small>
                        </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; ?>
                    
                    <!-- Installment options if applicable -->
                    <?php if (($product['sale_price'] ? $product['sale_price'] : $product['price']) >= 5000): ?>
                    <div class="installment-options">
                        <div class="installment-badge">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                                <rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect>
                                <line x1="1" y1="10" x2="23" y2="10"></line>
                            </svg>
                            <span>Kupovina na rate</span>
                        </div>
                        
                        <div class="installment-info">
                            <span class="installment-amount">
                                <strong>Od <?php echo number_format(($product['sale_price'] ? $product['sale_price'] : $product['price']) / 9, 0, ',', '.'); ?> RSD</strong> mesečno
                            </span>
                            <a href="#" id="payment-options-trigger" class="toggle-details" data-price="<?php echo $product['sale_price'] ? $product['sale_price'] : $product['price']; ?>">Opcije plaćanja</a>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Product Benefits -->
                <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" aria-hidden="true">
                                <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" aria-hidden="true">
                                <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" aria-hidden="true">
                                <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>
        </div>
        
        <!-- Purchase and Shipping Options -->
        <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="<?php echo isset($product['stock']) ? $product['stock'] : 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']; ?>"
                        <?php echo (!isset($product['stock']) || $product['stock'] <= 0) ? 'disabled' : ''; ?>>
                    <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" aria-hidden="true">
                        <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>
                    <?php echo (!isset($product['stock']) || $product['stock'] <= 0) ? 'TRENUTNO NEDOSTUPNO' : '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" aria-hidden="true">
                            <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 širom Srbije
                    </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" aria-hidden="true">
                            <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" aria-hidden="true">
                        <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" aria-hidden="true">
                        <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 14 dana</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" aria-hidden="true">
                        <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" role="tablist">
                <button type="button" class="tab-btn active" id="tab-description-btn" data-tab="tab-description" role="tab" aria-selected="true" aria-controls="tab-description">Detaljan opis</button>
                <button type="button" class="tab-btn" id="tab-specifications-btn" data-tab="tab-specifications" role="tab" aria-selected="false" aria-controls="tab-specifications">Specifikacije</button>
                <button type="button" class="tab-btn" id="tab-declaration-btn" data-tab="tab-declaration" role="tab" aria-selected="false" aria-controls="tab-declaration">Deklaracija</button>
                <button type="button" class="tab-btn" id="tab-reviews-btn" data-tab="tab-reviews" role="tab" aria-selected="false" aria-controls="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" role="tabpanel" aria-labelledby="tab-description-btn">
                    <?php echo $product['description']; ?>
                </div>
                
                <!-- Specifications Tab Content -->
                <div id="tab-specifications" class="tab-content" role="tabpanel" aria-labelledby="tab-specifications-btn">
                    <?php
                    if (!empty($specifications) && is_array($specifications)): ?>
                    <div class="specifications-table">
                        <table>
                            <caption class="sr-only">Specifikacije proizvoda <?php echo htmlspecialchars($product['name']); ?></caption>
                            <tbody>
                                <?php foreach ($specifications as $spec): 
                                    if (isset($spec['name']) && isset($spec['value'])): ?>
                                <tr>
                                    <th scope="row"><?php echo htmlspecialchars($spec['name']); ?></th>
                                    <td><?php echo htmlspecialchars($spec['value']); ?></td>
                                </tr>
                                <?php endif; endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <p>Nema dostupnih specifikacija za ovaj proizvod.</p>
                    <?php endif; ?>
                </div>
                
                <!-- Declaration Tab Content -->
                <div id="tab-declaration" class="tab-content" role="tabpanel" aria-labelledby="tab-declaration-btn">
                    <div class="declaration-content">
                        <table class="declaration-table">
                            <caption class="sr-only">Deklaracija proizvoda <?php echo htmlspecialchars($product['name']); ?></caption>
                            <tbody>
                                <tr>
                                    <th scope="row">Naziv proizvoda:</th>
                                    <td><?php echo $product['name']; ?></td>
                                </tr>
                                <tr>
                                    <th scope="row">Uvoznik:</th>
                                    <td>Varcom-s d.o.o. Smederevo</td>
                                </tr>
                                <tr>
                                    <th scope="row">Zemlja porekla:</th>
                                    <td>Kina</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <!-- Reviews Tab Content -->
                <div id="tab-reviews" class="tab-content" role="tabpanel" aria-labelledby="tab-reviews-btn">
                    <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'] ?? $review['user_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 for="rating">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; ?>" aria-label="<?php echo $i; ?> zvezdica">&#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 -->
        <?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" aria-hidden="true">
                        <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" aria-label="<?php echo htmlspecialchars($related['name']); ?>"></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 htmlspecialchars($related['name']); ?>"
                                     loading="lazy">
                            </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" aria-hidden="true">
                        <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>

<!-- 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']; ?>"
            <?php echo (!isset($product['stock']) || $product['stock'] <= 0) ? 'disabled' : ''; ?>>
        <?php echo (!isset($product['stock']) || $product['stock'] <= 0) ? 'NEDOSTUPNO' : 'KUPI'; ?>
    </button>
</div>

<!-- Sadržaj modala za korekciju cene (nevidljiv, samo za JavaScript) -->
<div id="price-match-content" style="display: none;">
    <p>Ukoliko ste pronašli isti proizvod po nižoj ceni, pošaljite nam link i mi ćemo vam ponuditi najbolju cenu.</p>
    <form id="price-match-form" method="post" action="/ajax/price-match.php">
        <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
        <input type="hidden" name="product_name" value="<?php echo htmlspecialchars($product['name']); ?>">
        
        <div class="form-group">
            <label for="pm-name" class="required">Vaše ime</label>
            <input type="text" id="pm-name" name="name" required>
        </div>
        
        <div class="form-group">
            <label for="pm-email" class="required">Email adresa</label>
            <input type="email" id="pm-email" name="email" required>
        </div>
        
        <div class="form-group">
            <label for="pm-phone">Telefon</label>
            <input type="tel" id="pm-phone" name="phone">
        </div>
        
        <div class="form-group">
            <label for="pm-link" class="required">Link ka proizvodu sa nižom cenom</label>
            <input type="url" id="pm-link" name="competitor_url" required>
        </div>
        
        <div class="form-group">
            <label for="pm-price" class="required">Cena (RSD)</label>
            <input type="number" id="pm-price" name="competitor_price" required min="1">
        </div>
        
        <div class="form-group">
            <label for="pm-message">Dodatne napomene</label>
            <textarea id="pm-message" name="message" rows="3"></textarea>
        </div>
        
        <div class="form-actions">
            <button type="button" class="btn-cancel modal-cancel">Odustani</button>
            <button type="submit" class="btn-primary">Pošalji zahtev</button>
        </div>
    </form>
</div>

<!-- Sadržaj modala za opcije plaćanja (nevidljiv, samo za JavaScript) -->
<div id="payment-options-content" style="display: none;">
    <div class="payment-methods">
        <div class="payment-method">
            <div class="method-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="1" y="4" width="22" height="16" rx="2" ry="2"></rect>
                    <line x1="1" y1="10" x2="23" y2="10"></line>
                </svg>
            </div>
            <div class="method-details">
                <h4>Kreditne kartice - do 9 rata bez kamate</h4>
                <p>Plaćanje kreditnim karticama na do 9 mesečnih rata bez kamate i bez naknade.</p>
                <div class="available-cards">
                    <span class="card-icon">VISA</span>
                    <span class="card-icon">MasterCard</span>
                    <span class="card-icon">Dina</span>
                </div>
                <div class="rate-example">
                    <p>Za proizvod cene <strong id="modal-product-price">0</strong> RSD:</p>
                    <table class="rates-table">
                        <thead>
                            <tr>
                                <th>Broj rata</th>
                                <th>Iznos rate (RSD)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>3 rate</td>
                                <td id="rate-3">0</td>
                            </tr>
                            <tr>
                                <td>6 rata</td>
                                <td id="rate-6">0</td>
                            </tr>
                            <tr>
                                <td>9 rata</td>
                                <td id="rate-9">0</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <div class="payment-method">
            <div class="method-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="2" y="5" width="20" height="14" rx="2"></rect>
                    <line x1="2" y1="10" x2="22" y2="10"></line>
                </svg>
            </div>
            <div class="method-details">
                <h4>Čekovi građana - do 6 rata</h4>
                <p>Plaćanje čekovima građana na do 6 mesečnih rata bez kamate. Mesečne rate dospevaju na naplatu svakog 15. u mesecu.</p>
            </div>
        </div>
        
        <div class="payment-method">
            <div class="method-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="M2 9V6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9"></path>
                    <polyline points="1 9 8 15 15 9"></polyline>
                </svg>
            </div>
            <div class="method-details">
                <h4>Gotovina - dodatni popust 5%</h4>
                <p>Plaćanje gotovinom prilikom preuzimanja uz dodatni popust od 5%!</p>
                <p>Vaša cena uz popust: <strong id="cash-discount-price">0</strong> RSD</p>
            </div>
        </div>
        
        <div class="payment-method">
            <div class="method-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="3" width="18" height="18" rx="2" ry="2"></rect>
                    <circle cx="8.5" cy="8.5" r="1.5"></circle>
                    <circle cx="15.5" cy="8.5" r="1.5"></circle>
                    <path d="M7 15a4 4 0 0 0 4 4h2a4 4 0 0 0 4-4"></path>
                </svg>
            </div>
            <div class="method-details">
                <h4>Kredit do 36 rata</h4>
                <p>Kreditiranje preko banaka i kreditnih kalkulatora na do 36 mesečnih rata uz fiksnu kamatnu stopu.</p>
                <p>
                    <a href="/kreditni-kalkulator" class="credit-calculator-link">
                        Izračunajte rate preko kreditnog kalkulatora
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="5" y1="12" x2="19" y2="12"></line>
                            <polyline points="12 5 19 12 12 19"></polyline>
                        </svg>
                    </a>
                </p>
            </div>
        </div>
    </div>
</div>

<style>
/* Dinamički modalni prozori - stilovi */
.dynamic-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999999;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease, visibility 0.3s ease;
    padding: 20px;
}

.dynamic-modal.active {
    opacity: 1;
    visibility: visible;
}

.dynamic-modal-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    backdrop-filter: blur(3px);
}

.dynamic-modal-content {
    position: relative;
    background-color: #fff;
    width: 100%;
    max-width: 550px;
    max-height: 90vh;
    overflow-y: auto;
    border-radius: 10px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
    transform: translateY(30px);
    transition: transform 0.3s ease;
    z-index: 1;
    margin: 0 auto;
}

.dynamic-modal.active .dynamic-modal-content {
    transform: translateY(0);
}

.dynamic-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #eee;
    background-color: #f9f9f9;
}

.dynamic-modal-title {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.dynamic-modal-close {
    background: none;
    border: none;
    font-size: 28px;
    line-height: 1;
    color: #777;
    cursor: pointer;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.2s ease;
}

.dynamic-modal-close:hover {
    background-color: rgba(0, 0, 0, 0.1);
    color: #333;
}

.dynamic-modal-body {
    padding: 20px;
}

/* Stil za modal sa slikom */
.dynamic-modal.image-modal .dynamic-modal-content {
    background-color: transparent;
    box-shadow: none;
    max-width: 90%;
    overflow: visible;
}

.dynamic-modal.image-modal .dynamic-modal-close {
    position: absolute;
    top: -40px;
    right: 0;
    background-color: rgba(255, 255, 255, 0.25);
    color: white;
    width: 40px;
    height: 40px;
    border-radius: 50%;
}

.zoomed-image {
    max-width: 100%;
    max-height: 85vh;
    object-fit: contain;
    border-radius: 5px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
}

/* Forme unutar modala */
.dynamic-modal-body .form-group {
    margin-bottom: 16px;
}

.dynamic-modal-body label {
    display: block;
    margin-bottom: 6px;
    font-weight: 500;
    font-size: 14px;
}

.dynamic-modal-body .required:after {
    content: "*";
    color: #e53935;
    margin-left: 4px;
}

.dynamic-modal-body input[type="text"],
.dynamic-modal-body input[type="email"],
.dynamic-modal-body input[type="tel"],
.dynamic-modal-body input[type="url"],
.dynamic-modal-body input[type="number"],
.dynamic-modal-body textarea {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
    transition: border-color 0.2s ease;
}

.dynamic-modal-body input:focus,
.dynamic-modal-body textarea:focus {
    border-color: var(--primary-color, #f6cc00);
    outline: none;
    box-shadow: 0 0 0 3px rgba(246, 204, 0, 0.15);
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
}

.btn-cancel {
    padding: 10px 16px;
    background-color: #f5f5f5;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
}

.btn-cancel:hover {
    background-color: #e9e9e9;
}

.btn-primary {
    padding: 10px 16px;
    background-color: var(--primary-color, #f6cc00);
    color: var(--secondary-color, #333);
    border: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
}

.btn-primary:hover {
    background-color: var(--primary-dark, #e6b900);
    transform: translateY(-2px);
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
}

/* Stilovi za opcije plaćanja */
.payment-methods {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.payment-method {
    display: flex;
    gap: 16px;
    padding: 16px;
    background-color: #f9f9f9;
    border-radius: 8px;
    border: 1px solid #eee;
    transition: all 0.2s ease;
}

.payment-method:hover {
    border-color: #ddd;
    box-shadow: 0 3px 10px rgba(0,0,0,0.05);
}

.method-icon {
    flex-shrink: 0;
    width: 48px;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--primary-color, #f6cc00);
    color: var(--secondary-color, #333);
    border-radius: 50%;
}

.method-details {
    flex: 1;
}

.method-details h4 {
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: 600;
}

.method-details p {
    margin: 0 0 10px 0;
    font-size: 14px;
    color: #666;
    line-height: 1.5;
}

.available-cards {
    display: flex;
    gap: 8px;
    margin: 10px 0;
    flex-wrap: wrap;
}

.card-icon {
    display: inline-block;
    padding: 5px 10px;
    background-color: white;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 600;
}

.rate-example {
    background-color: white;
    padding: 12px;
    border-radius: 6px;
    border: 1px solid #eee;
    margin-top: 15px;
}

.rates-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
}

.rates-table th, 
.rates-table td {
    padding: 8px 12px;
    text-align: left;
    border: 1px solid #eee;
}

.rates-table th {
    background-color: #f5f5f5;
    font-weight: 600;
}

.credit-calculator-link {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    color: var(--primary-color, #f6cc00);
    font-weight: 500;
    text-decoration: none;
}

.credit-calculator-link:hover {
    text-decoration: underline;
}

/* Installment Options Trigger */
.toggle-details {
    display: inline-flex;
    align-items: center;
    color: var(--primary-color, #f6cc00);
    background-color: var(--primary-light, rgba(246, 204, 0, 0.1));
    text-decoration: none;
    padding: 6px 12px;
    border-radius: 4px;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.2s ease;
}

.toggle-details:hover {
    background-color: var(--primary-color, #f6cc00);
    color: var(--secondary-color, #333);
}

@media (max-width: 768px) {
    .dynamic-modal {
        padding: 15px;
    }

    .payment-method {
        flex-direction: column;
        gap: 10px;
    }
    
    .method-icon {
        margin-bottom: 5px;
    }
    
    .dynamic-modal-content {
        max-height: 85vh;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Fixed header functionality for mobile
    const setupMobileHeader = function() {
        const siteHeader = document.querySelector('.site-header');
        if (!siteHeader) return;
        
        const headerHeight = siteHeader.offsetHeight;
        const isMobile = window.innerWidth < 768;
        
        if (isMobile) {
            siteHeader.classList.add('fixed-header');
            document.body.style.paddingTop = headerHeight + 'px';
        } else {
            siteHeader.classList.remove('fixed-header');
            document.body.style.paddingTop = '0';
        }
    };
    
    // Initialize header
    setupMobileHeader();
    window.addEventListener('resize', setupMobileHeader);
    
    // Thumbnail gallery functionality
    const mainImage = document.getElementById('main-product-image');
    const thumbnails = document.querySelectorAll('.thumbnail');
    
    if (mainImage && thumbnails.length) {
        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');
            });
        });
    }
    
    // Tabs functionality
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');
    
    if (tabBtns.length && tabContents.length) {
        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');
                    b.setAttribute('aria-selected', 'false');
                });
                
                tabContents.forEach(c => c.classList.remove('active'));
                
                // Add active class to clicked button and content
                this.classList.add('active');
                this.setAttribute('aria-selected', 'true');
                
                const activeContent = document.getElementById(tabId);
                if (activeContent) {
                    activeContent.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);
            const maxStock = parseInt(quantityInput.getAttribute('max'), 10) || 99;
            if (value < maxStock) {
                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) {
        // Create FormData object
        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() {
            if (this.disabled) return;
            
            const productId = this.getAttribute('data-product-id');
            const quantity = document.getElementById('quantity').value;
            buyNow(productId, quantity);
        });
    }
    
    if (stickyBuyBtn) {
        stickyBuyBtn.addEventListener('click', function() {
            if (this.disabled) return;
            
            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');
            }
        });
    }
    
    // Scroll to reviews link
    const scrollToReviews = document.querySelector('.scroll-to-reviews');
    if (scrollToReviews) {
        scrollToReviews.addEventListener('click', function(e) {
            e.preventDefault();
            const reviewsTab = document.getElementById('tab-reviews-btn');
            if (reviewsTab) {
                reviewsTab.click();
                
                setTimeout(() => {
                    const tabsSection = document.querySelector('.product-tabs-section');
                    if (tabsSection) {
                        tabsSection.scrollIntoView({ behavior: 'smooth' });
                    }
                }, 100);
            }
        });
    }
    
    // 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 && leftHint && rightHint) {
        // 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
            if (dots.length) {
                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
        leftHint.addEventListener('click', function() {
            scrollContainer.scrollBy({
                left: -220,
                behavior: 'smooth'
            });
        });
        
        rightHint.addEventListener('click', function() {
            scrollContainer.scrollBy({
                left: 220,
                behavior: 'smooth'
            });
        });
        
        // Click on dots to scroll to position
        if (dots.length) {
            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'
                    });
                });
            });
        }
    }

    // ===== Dinamički modalni prozori =====
    
    // Funkcija za kreiranje modala
    function createModal(id, title, content, isImageModal = false) {
        // Prvo proverimo da li već postoji
        let modal = document.getElementById(id);
        
        // Ako postoji, uklonimo ga
        if (modal) {
            document.body.removeChild(modal);
        }
        
        // Kreiramo novi element modala
        modal = document.createElement('div');
        modal.id = id;
        modal.className = isImageModal ? 'dynamic-modal image-modal' : 'dynamic-modal';
        
        // Dodajemo HTML sadržaj
        modal.innerHTML = `
            <div class="dynamic-modal-backdrop"></div>
            <div class="dynamic-modal-content">
                ${isImageModal ? '' : `
                <div class="dynamic-modal-header">
                    <h3 class="dynamic-modal-title">${title}</h3>
                    <button type="button" class="dynamic-modal-close" aria-label="Zatvori">&times;</button>
                </div>`}
                <div class="dynamic-modal-body">
                    ${content}
                </div>
                ${isImageModal ? `<button type="button" class="dynamic-modal-close" aria-label="Zatvori">&times;</button>` : ''}
            </div>
        `;
        
        // Dodajemo u body
        document.body.appendChild(modal);
        
        // Dodajemo event listenere
        const closeBtn = modal.querySelector('.dynamic-modal-close');
        const backdrop = modal.querySelector('.dynamic-modal-backdrop');
        
        if (closeBtn) {
            closeBtn.addEventListener('click', () => {
                closeModal(id);
            });
        }
        
        if (backdrop) {
            backdrop.addEventListener('click', () => {
                closeModal(id);
            });
        }
        
        // Dodajemo forme event listenere ako postoje
        const form = modal.querySelector('form');
        const cancelBtn = modal.querySelector('.modal-cancel');
        
        if (form) {
            form.addEventListener('submit', function(e) {
                // Opciono: dodati validaciju forme ovde
                
                // Ako je sve u redu, forma će se normalno poslati
                // closeModal(id); // Ako želimo da zatvorimo modal pre slanja forme
            });
        }
        
        if (cancelBtn) {
            cancelBtn.addEventListener('click', () => {
                closeModal(id);
            });
        }
        
        return modal;
    }
    
    // Funkcija za otvaranje modala
    function openModal(id) {
        const modal = document.getElementById(id);
        if (!modal) return;
        
        // Postavimo stil za prikaz (display: flex)
        modal.style.display = 'flex';
        
        // Forsiramo reflow za početak animacije
        void modal.offsetWidth;
        
        // Dodajemo active klasu za animaciju
        modal.classList.add('active');
        
        // Sprečavamo scroll na body
        document.body.style.overflow = 'hidden';
        
        // Postavljamo fokus za pristupačnost
        setTimeout(() => {
            const closeBtn = modal.querySelector('.dynamic-modal-close');
            if (closeBtn) closeBtn.focus();
        }, 50);
    }
    
    // Funkcija za zatvaranje modala
    function closeModal(id) {
        const modal = document.getElementById(id);
        if (!modal) return;
        
        // Uklanjamo active klasu
        modal.classList.remove('active');
        
        // Čekamo da se završi animacija
        setTimeout(() => {
            // Sakrivamo modal
            modal.style.display = 'none';
            
            // Vraćamo scroll
            document.body.style.overflow = '';
            
            // Fokusiramo element koji je otvorio modal ako znamo koji je
            if (window.lastFocusedElement) {
                window.lastFocusedElement.focus();
                window.lastFocusedElement = null;
            }
        }, 300);
    }
    
    // Postavljamo globalne event handlere
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const activeModals = document.querySelectorAll('.dynamic-modal.active');
            activeModals.forEach(modal => {
                closeModal(modal.id);
            });
        }
    });
    
    // Modal za korekciju cene
    const priceMatchTrigger = document.querySelector('.price-match-trigger');
    
    if (priceMatchTrigger) {
        priceMatchTrigger.addEventListener('click', function(e) {
            e.preventDefault();
            window.lastFocusedElement = this;
            
            // Dobijamo sadržaj modala
            const content = document.getElementById('price-match-content').innerHTML;
            
            // Kreiramo i otvaramo modal
            createModal('price-match-modal', 'Zahtev za korekciju cene', content);
            openModal('price-match-modal');
            
            // Dodajemo event listener za formu nakon kreiranja modala
            const form = document.querySelector('#price-match-modal form');
            if (form) {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(this);
                    
                    fetch(this.action, {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Prikazujemo poruku uspeha
                            document.querySelector('#price-match-modal .dynamic-modal-body').innerHTML = `
                                <div class="success-message">
                                    <h4>Zahtev uspešno poslat!</h4>
                                    <p>Hvala na vašem zahtevu. Kontaktiraćemo vas uskoro sa najboljom ponudom.</p>
                                    <button class="btn-primary modal-ok">U redu</button>
                                </div>
                            `;
                            
                            // Dodajemo listener za OK dugme
                            document.querySelector('.modal-ok').addEventListener('click', function() {
                                closeModal('price-match-modal');
                            });
                        } else {
                            alert('Došlo je do greške: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Došlo je do greške pri komunikaciji sa serverom.');
                    });
                });
            }
        });
    }
    
    // Modal za opcije plaćanja
    const paymentOptionsTrigger = document.getElementById('payment-options-trigger');
    
    if (paymentOptionsTrigger) {
        paymentOptionsTrigger.addEventListener('click', function(e) {
            e.preventDefault();
            window.lastFocusedElement = this;
            
            // Dobijamo sadržaj modala
            const content = document.getElementById('payment-options-content').innerHTML;
            
            // Kreiramo i otvaramo modal
            createModal('payment-options-modal', 'Opcije plaćanja', content);
            openModal('payment-options-modal');
            
            // Izračunavamo i postavljamo cene rata
            const productPrice = parseFloat(this.getAttribute('data-price')) || 0;
            
            // Format brojeva sa srpskim lokalitetom
            const formatPrice = (price) => {
                return new Intl.NumberFormat('sr-RS').format(Math.ceil(price));
            };
            
            // Ažuriramo cene u modalu
            const modalProductPrice = document.getElementById('modal-product-price');
            if (modalProductPrice) {
                modalProductPrice.textContent = formatPrice(productPrice);
            }
            
            const rate3 = document.getElementById('rate-3');
            const rate6 = document.getElementById('rate-6');
            const rate9 = document.getElementById('rate-9');
            
            if (rate3 && rate6 && rate9) {
                rate3.textContent = formatPrice(productPrice / 3);
                rate6.textContent = formatPrice(productPrice / 6);
                rate9.textContent = formatPrice(productPrice / 9);
            }
            
            const cashDiscountPrice = document.getElementById('cash-discount-price');
            if (cashDiscountPrice) {
                const discountedPrice = productPrice * 0.95;
                cashDiscountPrice.textContent = formatPrice(discountedPrice);
            }
        });
    }
    

});
</script>

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