<?php
// Aktiviranje output buffering-a za rešavanje header problema
ob_start();

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, DATE_FORMAT(r.created_at, '%Y-%m-%d') as review_date
    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);

// If get_recommended_products doesn't handle images correctly, adjust the results here
if (!empty($recommended_products)) {
    foreach ($recommended_products as $key => $rec_product) {
        // Check if image is missing and fetch it
        if (!isset($rec_product['image'])) {
            $rec_image = get_rows("
                SELECT image 
                FROM product_images 
                WHERE product_id = ? 
                ORDER BY sort_order ASC 
                LIMIT 1
            ", [$rec_product['id']]);
            
            $recommended_products[$key]['image'] = !empty($rec_image) ? $rec_image[0]['image'] : 'default-product.jpg';
        }
    }
}

// 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'] : '';

// Get primary category for canonical URL
$primary_category = !empty($product_categories) ? $product_categories[0]['slug'] : '';
$canonical_url = SITE_URL . '/' . $product['slug'];

// Set stock status for display
$stock_status = 'in-stock';
$stock_message = 'Dostupno odmah';
$stock_count_message = '';

// Stock is considered low if less than 10 items
if (isset($product['stock']) && $product['stock'] <= 10 && $product['stock'] > 0) {
    $stock_status = 'low-stock';
    $stock_message = 'Još samo nekoliko na zalihama';
    $stock_count_message = 'Još samo ' . $product['stock'] . ' komada na stanju!';
} elseif (isset($product['stock']) && $product['stock'] <= 0) {
    $stock_status = 'out-of-stock';
    $stock_message = 'Trenutno nije dostupno';
}

// Special offer setup with session
$special_offer_active = false;
$time_remaining = 0;
$special_offer_id = 'special_offer_' . $product['id'];

// Check if special offer exists in session
if (!isset($_SESSION[$special_offer_id])) {
    // Set special offer expiry time (7 minutes from now)
    $_SESSION[$special_offer_id] = time() + (7 * 60);
    $special_offer_active = true;
    $time_remaining = 7 * 60;
} else {
    // Calculate remaining time
    $expiry_time = $_SESSION[$special_offer_id];
    $current_time = time();
    
    if ($expiry_time > $current_time) {
        $special_offer_active = true;
        $time_remaining = $expiry_time - $current_time;
    }
}

// Create variable to store in session when adding to cart
$special_offer_code = 'HVALA2000';

// Get recently viewed products from cookie
$recently_viewed = isset($_COOKIE['recently_viewed']) ? json_decode($_COOKIE['recently_viewed'], true) : [];

// Add current product to recently viewed
if (!in_array($product['id'], $recently_viewed)) {
    array_unshift($recently_viewed, $product['id']);
    // Keep only last 5 products
    $recently_viewed = array_slice($recently_viewed, 0, 5);
    // Save to cookie
    setcookie('recently_viewed', json_encode($recently_viewed), time() + 30 * 24 * 60 * 60, '/');
}

// Get recently viewed products data excluding current
$recently_viewed_products = [];
if (count($recently_viewed) > 1) {
    $recently_viewed_ids = array_filter($recently_viewed, function($id) use ($product) {
        return $id != $product['id'];
    });
    
    if (!empty($recently_viewed_ids)) {
        $placeholders = implode(',', array_fill(0, count($recently_viewed_ids), '?'));
        $recently_viewed_products = get_rows("
            SELECT id, name, slug, price, sale_price
            FROM products 
            WHERE id IN ($placeholders) AND status = 'active'
            LIMIT 4
        ", $recently_viewed_ids);
        
        // Fetch images for recently viewed products
        if (!empty($recently_viewed_products)) {
            foreach ($recently_viewed_products as $key => $recent_product) {
                $recent_image = get_rows("
                    SELECT image 
                    FROM product_images 
                    WHERE product_id = ? 
                    ORDER BY sort_order ASC 
                    LIMIT 1
                ", [$recent_product['id']]);
                
                // Add image to the product array
                $recently_viewed_products[$key]['image'] = !empty($recent_image) ? $recent_image[0]['image'] : 'default-product.jpg';
            }
        }
    }
}

// Calculate shipping cost
$current_price = !empty($product['sale_price']) ? $product['sale_price'] : $product['price'];
$free_shipping_threshold = 15000;
$standard_shipping_cost = 500;
$shipping_cost = ($current_price >= $free_shipping_threshold) ? 0 : $standard_shipping_cost;
$amount_for_free_shipping = max(0, $free_shipping_threshold - $current_price);

// Define payment methods to display
$payment_methods = [
    ["name" => "Visa", "image" => "/assets/images/payment/visa.png"],
    ["name" => "Mastercard", "image" => "/assets/images/payment/mastercard.png"],
    ["name" => "PayPal", "image" => "/assets/images/payment/paypal.png"],
    ["name" => "Pouzeće", "image" => "/assets/images/payment/cash.png"]
];

// Dynamic social proof system based on product properties
// In a real implementation, this would be based on actual data from the database
// For now, we'll simulate different levels based on some product properties

// Determine product popularity level (this would be from actual data in a real implementation)
$popularity_level = 'medium'; // Default level

// Use product properties to determine popularity
if (isset($product['rating_count']) && $product['rating_count'] > 10 && $avg_rating >= 4.5) {
    $popularity_level = 'high';
} elseif (isset($product['stock']) && $product['stock'] < 5 && $product['stock'] > 0) {
    // Low stock might indicate high demand
    $popularity_level = 'high';
} elseif (isset($product['sold_count']) && $product['sold_count'] > 50) {
    // If this product has been sold many times
    $popularity_level = 'high';
} elseif (isset($product['views_count']) && $product['views_count'] < 20) {
    // If this product has very few views
    $popularity_level = 'low';
}

// Define social proofs based on popularity level
$social_proofs = [];

switch ($popularity_level) {
    case 'high':
        $social_proofs = [
            [
                'icon' => 'fa-fire', 
                'text' => 'Naš najprodavaniji model u kategoriji'
            ],
            [
                'icon' => 'fa-users', 
                'text' => 'Izbor profesionalaca'
            ],
            [
                'icon' => 'fa-certificate', 
                'text' => 'Jedan od 3 najtraženija proizvoda'
            ]
        ];
        break;
    
    case 'medium':
        $social_proofs = [
            [
                'icon' => 'fa-thumbs-up', 
                'text' => 'Vrlo popularan model'
            ],
            [
                'icon' => 'fa-star', 
                'text' => isset($product_categories[0]) ? 'Dobar izbor u kategoriji ' . $product_categories[0]['name'] : 'Dobar izbor za profesionalce'
            ],
            [
                'icon' => 'fa-check-circle', 
                'text' => 'Odličan odnos cene i kvaliteta'
            ]
        ];
        break;
    
    case 'low':
        $social_proofs = [
            [
                'icon' => 'fa-gem', 
                'text' => 'Ekskluzivan model za zahtevne korisnike'
            ],
            [
                'icon' => 'fa-bullseye', 
                'text' => 'Specijalizovan za specifične potrebe'
            ],
            [
                'icon' => 'fa-medal', 
                'text' => isset($product_categories[0]) ? 'Odličan izbor za ' . $product_categories[0]['name'] : 'Odličan izbor za specifične namene'
            ]
        ];
        break;
}

// Schema.org data
?>

<!DOCTYPE html>
<html lang="sr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($meta_title); ?></title>
    <meta name="description" content="<?php echo htmlspecialchars($meta_description); ?>">
    
    <!-- Canonical URL to prevent duplicate content -->
    <link rel="canonical" href="<?php echo $canonical_url; ?>">
    
    <!-- Open Graph / Facebook meta 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 $canonical_url; ?>">
    <meta property="og:image" content="<?php echo $meta_image; ?>">
    <meta property="og:site_name" content="<?php echo htmlspecialchars(get_setting('site_name')); ?>">
    
    <!-- Twitter Card meta tags -->
    <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; ?>">
    
    <!-- Preload key resources -->
    <link rel="preload" href="<?php echo UPLOADS_URL . '/products/' . $product_images[0]['image']; ?>" as="image">
    
    <!-- Add Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    
    <!-- Additional CSS for CRO elements -->
    <style>
        /* Stock status indicators */
        .stock-indicator {
            display: flex;
            align-items: center;
            padding: 8px 12px;
            border-radius: 4px;
            margin: 15px 0;
            font-weight: 500;
        }
        .stock-indicator.in-stock {
            background-color: rgba(40, 167, 69, 0.1);
            color: #28a745;
            border-left: 4px solid #28a745;
        }
        .stock-indicator.low-stock {
            background-color: rgba(255, 193, 7, 0.1);
            color: #dc3545;
            border-left: 4px solid #ffc107;
        }
        .stock-indicator.out-of-stock {
            background-color: rgba(220, 53, 69, 0.1);
            color: #dc3545;
            border-left: 4px solid #dc3545;
        }
        .stock-indicator i {
            margin-right: 8px;
        }
        .stock-count {
            font-weight: 700;
            color: #dc3545;
        }
        
        /* Wishlist button */
        .wishlist-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            background-color: white;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px 15px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
        }
        .wishlist-btn:hover {
            background-color: #f8f9fa;
            border-color: #c1c9d0;
        }
        .wishlist-btn i {
            color: #dc3545;
        }
        
        /* Special offer banner with timer */
        .special-offer {
            background-color: #fff8e1;
            border: 1px solid #ffeeba;
            border-radius: 4px;
            padding: 15px;
            margin: 15px 0;
            text-align: center;
        }
        .special-offer-title {
            font-weight: 600;
            font-size: 16px;
            color: #dc3545;
            margin-bottom: 10px;
        }
        .special-offer-desc {
            font-size: 14px;
            color: #333;
            margin-bottom: 12px;
        }
        .countdown-timer {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-bottom: 10px;
        }
        .countdown-item {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .countdown-value {
            font-size: 18px;
            font-weight: 700;
            color: #333;
            background-color: white;
            border-radius: 4px;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .countdown-label {
            font-size: 12px;
            color: #666;
            margin-top: 4px;
        }
        .special-offer-action {
            font-size: 14px;
            font-weight: 600;
            color: #28a745;
        }
        
        /* Social proof */
        .social-proof {
            margin: 15px 0;
            padding: 12px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }
        .proof-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            font-size: 14px;
        }
        .proof-item:last-child {
            margin-bottom: 0;
        }
        .proof-item i {
            color: #28a745;
            margin-right: 8px;
        }
        
        /* Payment methods */
        .payment-methods {
            margin: 15px 0;
        }
        .payment-methods-title {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 10px;
        }
        .payment-icons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        .payment-icon {
            height: 24px;
            width: auto;
            filter: grayscale(0.4);
            transition: filter 0.2s;
        }
        .payment-icon:hover {
            filter: grayscale(0);
        }
        
        /* Shipping calculator */
        .shipping-calculator {
            margin: 15px 0;
            padding: 12px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }
        .shipping-calculator-title {
            font-weight: 500;
            margin-bottom: 10px;
        }
        .zipcode-input-group {
            display: flex;
            max-width: 300px;
        }
        .zipcode-input-group input {
            flex-grow: 1;
            border: 1px solid #dee2e6;
            border-right: none;
            border-radius: 4px 0 0 4px;
            padding: 8px 12px;
        }
        .zipcode-input-group button {
            background-color: #f6cc00;
            color: #343a40;
            border: none;
            border-radius: 0 4px 4px 0;
            padding: 0 12px;
            font-weight: 500;
            cursor: pointer;
        }
        #shipping-result {
            margin-top: 10px;
            font-size: 14px;
        }
        
        /* Buy button enhancements */
        .buy-button {
            width: 100%;
            padding: 16px;
            background-color: #f6cc00;
            color: #343a40;
            border: none;
            border-radius: 8px;
            font-size: 18px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            position: relative;
            overflow: hidden;
        }
        .buy-button:hover {
            background-color: #e6b900;
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }
        .buy-button::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 5px;
            height: 5px;
            background: rgba(255, 255, 255, 0.5);
            opacity: 0;
            border-radius: 100%;
            transform: scale(1, 1) translate(-50%);
            transform-origin: 50% 50%;
        }
        .buy-button:focus:not(:active)::after {
            animation: ripple 1s ease-out;
        }
        @keyframes ripple {
            0% {
                transform: scale(0, 0);
                opacity: 0;
            }
            20% {
                transform: scale(25, 25);
                opacity: 0.5;
            }
            100% {
                opacity: 0;
                transform: scale(40, 40);
            }
        }
        
        /* Recently viewed products */
        .recently-viewed-section {
            margin: 30px 0;
        }
        .recently-viewed-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
            position: relative;
            padding-bottom: 10px;
        }
        .recently-viewed-title::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 50px;
            height: 3px;
            background-color: #f6cc00;
        }
        .recently-viewed-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
        }
        
        /* Enhanced product benefits section */
        .enhanced-benefits {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin: 20px 0;
        }
        .benefit-card {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            transition: all 0.2s;
        }
        .benefit-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 10px rgba(0,0,0,0.05);
        }
        .benefit-icon {
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #fff;
            border-radius: 50%;
            margin-bottom: 10px;
            color: #f6cc00;
            font-size: 20px;
        }
        .benefit-title {
            font-weight: 600;
            margin-bottom: 5px;
            font-size: 15px;
        }
        .benefit-text {
            font-size: 13px;
            color: #666;
            line-height: 1.4;
        }
        
        /* FAQ Section */
        .faq-section {
            margin: 30px 0;
        }
        .faq-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
        }
        .faq-item {
            margin-bottom: 10px;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            overflow: hidden;
        }
        .faq-question {
            padding: 12px 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #f8f9fa;
            font-weight: 600;
            cursor: pointer;
        }
        .faq-answer {
            padding: 0 15px;
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s, padding 0.3s;
        }
        .faq-item.active .faq-answer {
            padding: 15px;
            max-height: 200px;
        }
        
        /* Enhanced sticky cart for mobile */
        .sticky-cart {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background-color: white;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            padding: 10px 15px;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            z-index: 999;
            transform: translateY(100%);
            transition: transform 0.3s;
        }
        .sticky-cart.visible {
            transform: translateY(0);
        }
        .sticky-product-info {
            display: flex;
            align-items: center;
        }
        .sticky-product-image {
            width: 40px;
            height: 40px;
            border-radius: 4px;
            margin-right: 10px;
            object-fit: contain;
        }
        .sticky-product-details {
            overflow: hidden;
        }
        .sticky-product-name {
            font-weight: 600;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 14px;
        }
        .sticky-product-price {
            font-weight: 700;
            color: #dc3545;
            font-size: 15px;
        }
        .sticky-buy-btn {
            background-color: #f6cc00;
            color: #343a40;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            font-weight: 700;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .sticky-buy-btn:hover {
            background-color: #e6b900;
        }
        
        /* Save contact modal */
        .save-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .save-modal-content {
            background-color: white;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            padding: 25px;
            position: relative;
        }
        .save-modal-close {
            position: absolute;
            top: 10px;
            right: 15px;
            font-size: 24px;
            background: none;
            border: none;
            cursor: pointer;
            color: #aaa;
        }
        .save-modal-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 15px;
            color: #343a40;
        }
        .save-modal-description {
            font-size: 14px;
            color: #666;
            margin-bottom: 20px;
            line-height: 1.5;
        }
        .save-form-group {
            margin-bottom: 15px;
        }
        .save-form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            font-size: 14px;
        }
        .save-form-group input {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            font-size: 14px;
        }
        .save-form-submit {
            width: 100%;
            padding: 12px;
            background-color: #f6cc00;
            color: #343a40;
            border: none;
            border-radius: 4px;
            font-weight: 600;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        /* Shipping info tooltip */
        .shipping-info {
            margin-bottom: 5px;
            font-size: 13px;
            color: #666;
        }
        .shipping-info i {
            margin-right: 5px;
            color: #17a2b8;
        }
        
        /* Utilities */
        .visually-hidden {
            position: absolute;
            width: 1px;
            height: 1px;
            margin: -1px;
            padding: 0;
            overflow: hidden;
            clip: rect(0, 0, 0, 0);
            border: 0;
        }
        
        /* Desktop specific styles */
        @media (min-width: 992px) {
            .payment-methods, .shipping-calculator {
                text-align: center;
            }
            
            .payment-icons, .zipcode-input-group {
                justify-content: center;
                margin: 0 auto;
            }
            
            .enhanced-benefits {
                grid-template-columns: repeat(3, 1fr);
            }
            
            .recently-viewed-grid {
                grid-template-columns: repeat(4, 1fr);
            }
        }
        
        @media (max-width: 992px) {
            .recently-viewed-grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }
        
        @media (max-width: 768px) {
            .enhanced-benefits {
                grid-template-columns: 1fr;
            }
            .countdown-value {
                font-size: 16px;
                width: 36px;
                height: 36px;
            }
            .countdown-label {
                font-size: 11px;
            }
            .recently-viewed-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>

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

    <main class="product-container">
        <div class="container">
            <!-- Main Product Section -->
            <div class="product-main-wrapper">
                <!-- Product Gallery Section (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 htmlspecialchars($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 htmlspecialchars($image['alt_text'] ?? $product['name'] . ' - thumbnail'); ?>">
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- 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 htmlspecialchars($product['name']); ?></h1>
                    </div>
                    
                    <!-- Dynamic Social Proof -->
                    <div class="social-proof">
                        <?php foreach($social_proofs as $proof): ?>
                        <div class="proof-item">
                            <i class="fas <?php echo $proof['icon']; ?>"></i>
                            <span><?php echo $proof['text']; ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Stock Status Indicator -->
                    <div class="stock-indicator <?php echo $stock_status; ?>">
                        <?php if ($stock_status === 'in-stock'): ?>
                            <i class="fas fa-check-circle"></i>
                            <span><?php echo $stock_message; ?></span>
                        <?php elseif ($stock_status === 'low-stock'): ?>
                            <i class="fas fa-exclamation-circle"></i>
                            <span><?php echo $stock_message; ?> - <span class="stock-count"><?php echo $stock_count_message; ?></span></span>
                        <?php else: ?>
                            <i class="fas fa-times-circle"></i>
                            <span><?php echo $stock_message; ?></span>
                        <?php endif; ?>
                    </div>
                    
                    <!-- 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>
                    
                    <!-- Special Offer with Voucher and Timer -->
                    <?php if ($special_offer_active): ?>
                    <div class="special-offer">
                        <div class="special-offer-title">
                            <i class="fas fa-gift"></i> POSEBNA PONUDA ZA VAS!
                        </div>
                        <div class="special-offer-desc">
                            Poručite u narednih <strong>7 minuta</strong> i dobijate <strong>poklon vaučer u vrednosti od 2.000 RSD</strong> za sledeću kupovinu!
                        </div>
                        <div class="countdown-timer" data-seconds-remaining="<?php echo $time_remaining; ?>">
                            <div class="countdown-item">
                                <div class="countdown-value" id="countdown-minutes">07</div>
                                <div class="countdown-label">Minuta</div>
                            </div>
                            <div class="countdown-item">
                                <div class="countdown-value" id="countdown-seconds">00</div>
                                <div class="countdown-label">Sekundi</div>
                            </div>
                        </div>
                        <div class="special-offer-action">
                            Požurite, ponuda važi samo ograničeno vreme!
                        </div>
                    </div>
                    <?php endif; ?>
                    
                </div>
            </div>
            
            <!-- Purchase and Shipping Options - Enhanced for CRO -->
            <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>
                    
                    <div style="display: flex; gap: 10px; margin-bottom: 15px; width: 100%;">
                        <button type="button" id="buy-now-btn" class="buy-button" data-product-id="<?php echo $product['id']; ?>" data-special-offer="<?php echo $special_offer_active ? '1' : '0'; ?>">
                            <i class="fas fa-shopping-cart"></i>
                            KUPI ODMAH
                        </button>
                        
                        <button type="button" id="save-product-btn" class="wishlist-btn" data-product-id="<?php echo $product['id']; ?>">
                            <i class="far fa-heart"></i>
                            <span class="wishlist-text">Sačuvaj</span>
                        </button>
                    </div>
                    
                    <!-- Payment Methods - Centered on desktop -->
                    <div class="payment-methods">
                        <div class="payment-methods-title">Prihvaćene metode plaćanja:</div>
                        <div class="payment-icons">
                            <?php foreach($payment_methods as $method): ?>
                            <img src="<?php echo $method['image']; ?>" alt="<?php echo $method['name']; ?>" class="payment-icon" title="<?php echo $method['name']; ?>">
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Shipping Calculator - Centered on desktop -->
                <div class="shipping-calculator">
                    <div class="shipping-calculator-title">Izračunajte troškove dostave:</div>
                    <div class="shipping-info">
                        <i class="fas fa-info-circle"></i> Besplatna dostava za porudžbine preko 15.000 RSD
                    </div>
                    <div class="zipcode-input-group">
                        <input type="text" id="shipping-zipcode" placeholder="Unesite poštanski broj">
                        <button type="button" id="calculate-shipping-btn">Izračunaj</button>
                    </div>
                    <div id="shipping-result">
                        <!-- Initially empty, will be filled via JavaScript -->
                    </div>
                </div>
                
                <!-- Shipping Options -->
                <div class="shipping-options">
                    <div class="shipping-option">
                        <div class="option-text"><i class="fas fa-truck"></i> Poručite online i izaberite dostavu - Besplatna dostava za porudžbine preko 15.000 RSD</div>
                    </div>
                    
                    <div class="shipping-option">
                        <div class="option-text"><i class="fas fa-store"></i> Preuzmite u magacinu na adresi Oskara Daviča 2, Kragujevac - Besplatno</div>
                    </div>
                </div>
                
                <!-- Enhanced Trust Badges -->
                <div class="enhanced-benefits">
                    <div class="benefit-card">
                        <div class="benefit-icon">
                            <i class="fas fa-shield-alt"></i>
                        </div>
                        <div class="benefit-title">Garancija 25 meseci</div>
                        <div class="benefit-text">Originalna garancija proizvođača</div>
                    </div>
                    
                    <div class="benefit-card">
                        <div class="benefit-icon">
                            <i class="fas fa-tools"></i>
                        </div>
                        <div class="benefit-title">Rezervni delovi</div>
                        <div class="benefit-text">Dostupni rezervni delovi 7 godina</div>
                    </div>
                    
                    <div class="benefit-card">
                        <div class="benefit-icon">
                            <i class="fas fa-undo"></i>
                        </div>
                        <div class="benefit-title">Povrat robe</div>
                        <div class="benefit-text">Jednostavan povrat u roku od 14 dana</div>
                    </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 - With FAQ added -->
            <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>
                    <button type="button" class="tab-btn" data-tab="tab-faq">Česta pitanja</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 htmlspecialchars($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['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>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>
                    
                    <!-- FAQ Tab Content -->
                    <div id="tab-faq" class="tab-content">
                        <div class="faq-section">
                            <div class="faq-item">
                                <div class="faq-question">
                                    <span>Koji je garantni rok za ovaj proizvod?</span>
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                                <div class="faq-answer">
                                    <p>Garantni rok za ovaj proizvod je 25 meseci od datuma kupovine. Garancija pokriva sve fabričke nedostatke i kvarove koji nastanu pri normalnoj upotrebi uređaja.</p>
                                </div>
                            </div>
                            
                            <div class="faq-item">
                                <div class="faq-question">
                                    <span>Da li je moguće vratiti proizvod ako nisam zadovoljan?</span>
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                                <div class="faq-answer">
                                    <p>Da, proizvod možete vratiti u roku od 14 dana od prijema ukoliko niste zadovoljni. Proizvod mora biti nekorišćen, u originalnom pakovanju sa svim pripadajućim delovima i dokumentacijom.</p>
                                </div>
                            </div>
                            
                            <div class="faq-item">
                                <div class="faq-question">
                                    <span>Koliko traje isporuka?</span>
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                                <div class="faq-answer">
                                    <p>Isporuka se vrši u roku od 2-3 radna dana na teritoriji Srbije. Za veće gradove (Beograd, Novi Sad, Niš) isporuka je obično u roku od 24h.</p>
                                </div>
                            </div>
                            
                            <div class="faq-item">
                                <div class="faq-question">
                                    <span>Da li je dostupna usluga servisiranja nakon isteka garancije?</span>
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                                <div class="faq-answer">
                                    <p>Da, obezbeđujemo servisiranje i rezervne delove 7 godina nakon kupovine proizvoda. Za više informacija o servisiranju, kontaktirajte našu tehničku podršku.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Recently Viewed Products -->
            <?php if (!empty($recently_viewed_products)): ?>
            <div class="recently-viewed-section">
                <h2 class="recently-viewed-title">Nedavno pregledani proizvodi</h2>
                
                <div class="recently-viewed-grid">
                    <?php foreach($recently_viewed_products as $recent): ?>
                    <div class="product-card">
                        <a href="/<?php echo $recent['slug']; ?>" class="card-link-overlay"></a>
                        
                        <?php if (!empty($recent['sale_price'])): 
                            $recent_discount = round((($recent['price'] - $recent['sale_price']) / $recent['price']) * 100);
                        ?>
                        <div class="product-discount">-<?php echo $recent_discount; ?>%</div>
                        <?php endif; ?>
                        
                        <div class="product-image">
                            <img src="<?php echo !empty($recent['image']) ? UPLOADS_URL . '/products/' . $recent['image'] : '/assets/images/no-image.jpg'; ?>" 
                                 alt="<?php echo htmlspecialchars($recent['name']); ?>"
                                 loading="lazy">
                        </div>
                        
                        <div class="product-details">
                            <h3 class="product-name">
                                <span><?php echo htmlspecialchars($recent['name']); ?></span>
                            </h3>
                            
                            <div class="product-price">
                                <?php if (!empty($recent['sale_price'])): ?>
                                <div class="price-wrapper">
                                    <span class="price-old"><?php echo number_format($recent['price'], 0, ',', '.'); ?> RSD</span>
                                    <span class="price-current"><?php echo number_format($recent['sale_price'], 0, ',', '.'); ?> RSD</span>
                                </div>
                                <?php else: ?>
                                <span class="price-current"><?php echo number_format($recent['price'], 0, ',', '.'); ?> RSD</span>
                                <?php endif; ?>
                            </div>
                            
                            <span class="btn-view">VIDI VIŠE ></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- 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 htmlspecialchars($related['name']); ?>"
                                         loading="lazy">
                                </div>
                                
                                <div class="product-details">
                                    <h3 class="product-name">
                                        <span><?php echo htmlspecialchars($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>
    </main>

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

    <!-- Save Product Contact Form Modal -->
    <div id="save-product-modal" class="save-modal">
        <div class="save-modal-content">
            <button type="button" class="save-modal-close">&times;</button>
            <h3 class="save-modal-title">Sačuvajte ovaj proizvod</h3>
            <p class="save-modal-description">Ostavite svoju email adresu ili broj telefona kako biste sačuvali ovaj proizvod i dobili specijalnu ponudu samo za vas!</p>
            
            <form id="save-product-form">
                <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                
                <div class="save-form-group">
                    <label for="save-email">Email adresa</label>
                    <input type="email" id="save-email" name="email" placeholder="Vaša email adresa">
                </div>
                
                <div class="save-form-group">
                    <label for="save-phone">Broj telefona (opciono)</label>
                    <input type="tel" id="save-phone" name="phone" placeholder="Vaš broj telefona">
                </div>
                
                <div class="save-form-group">
                    <label>
                        <input type="checkbox" name="consent" required>
                        Slažem se da me kontaktirate u vezi sa ovim proizvodom i specijalnim ponudama
                    </label>
                </div>
                
                <button type="submit" class="save-form-submit">Sačuvaj proizvod</button>
            </form>
        </div>
    </div>

    <!-- Enhanced Sticky Buy Now for Mobile -->
    <div class="sticky-cart">
        <div class="sticky-product-info">
            <img src="<?php echo UPLOADS_URL . '/products/' . $product_images[0]['image']; ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" class="sticky-product-image">
            <div class="sticky-product-details">
                <div class="sticky-product-name"><?php echo htmlspecialchars($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>
        </div>
        <button type="button" class="sticky-buy-btn" data-product-id="<?php echo $product['id']; ?>" data-special-offer="<?php echo $special_offer_active ? '1' : '0'; ?>">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');
        });
    });
    
    // FAQ accordion functionality
    const faqItems = document.querySelectorAll('.faq-item');
    
    faqItems.forEach(item => {
        const question = item.querySelector('.faq-question');
        
        question.addEventListener('click', function() {
            // Toggle active class
            item.classList.toggle('active');
            
            // Update icon
            const icon = question.querySelector('i');
            if (item.classList.contains('active')) {
                icon.classList.remove('fa-chevron-down');
                icon.classList.add('fa-chevron-up');
            } else {
                icon.classList.remove('fa-chevron-up');
                icon.classList.add('fa-chevron-down');
            }
        });
    });
    
    // 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';
        });
    }
    
    // Countdown Timer
    const countdownContainer = document.querySelector('.countdown-timer');
    if (countdownContainer) {
        const secondsRemaining = parseInt(countdownContainer.getAttribute('data-seconds-remaining'));
        let countdown = secondsRemaining;
        
        function updateCountdown() {
            if (countdown <= 0) {
                // Hide the offer when time is up
                const specialOffer = document.querySelector('.special-offer');
                if (specialOffer) {
                    specialOffer.style.display = 'none';
                }
                
                // Update buy buttons to remove special offer data
                const buyButtons = document.querySelectorAll('[data-special-offer]');
                buyButtons.forEach(btn => {
                    btn.setAttribute('data-special-offer', '0');
                });
                
                return;
            }
            
            const minutes = Math.floor(countdown / 60);
            const seconds = countdown % 60;
            
            document.getElementById('countdown-minutes').innerHTML = minutes < 10 ? '0' + minutes : minutes;
            document.getElementById('countdown-seconds').innerHTML = seconds < 10 ? '0' + seconds : seconds;
            
            countdown--;
        }
        
        // Initial update
        updateCountdown();
        
        // Update every second
        setInterval(updateCountdown, 1000);
    }
    
    // Save product modal functionality
    const saveProductBtn = document.getElementById('save-product-btn');
    const saveProductModal = document.getElementById('save-product-modal');
    const saveModalClose = document.querySelector('.save-modal-close');
    const saveProductForm = document.getElementById('save-product-form');
    
    if (saveProductBtn && saveProductModal) {
        saveProductBtn.addEventListener('click', function() {
            saveProductModal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        });
    }
    
    if (saveModalClose) {
        saveModalClose.addEventListener('click', function() {
            saveProductModal.style.display = 'none';
            document.body.style.overflow = '';
        });
    }
    
    // Close modal when clicking outside of it
    window.addEventListener('click', function(e) {
        if (e.target === saveProductModal) {
            saveProductModal.style.display = 'none';
            document.body.style.overflow = '';
        }
    });
    
    // Save product form submission
    if (saveProductForm) {
        saveProductForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Get form data
            const formData = new FormData(this);
            
            // Simulate API call (replace with actual implementation)
            setTimeout(function() {
                // Close modal
                saveProductModal.style.display = 'none';
                document.body.style.overflow = '';
                
                // Show success message
                alert('Hvala! Sačuvali smo proizvod za vas i poslali specijalnu ponudu na vašu email adresu.');
                
                // Update button state
                const saveBtn = document.getElementById('save-product-btn');
                if (saveBtn) {
                    saveBtn.innerHTML = '<i class="fas fa-heart"></i><span class="wishlist-text">Sačuvano</span>';
                    saveBtn.classList.add('in-wishlist');
                }
            }, 500);
            
            // In a real implementation, you would send this data to your server
            // fetch('/save-product.php', {
            //     method: 'POST',
            //     body: formData
            // })
            // .then(response => response.json())
            // .then(data => {
            //     if (data.success) {
            //         // Success handling
            //     }
            // });
        });
    }
    
    // Shipping Calculator - Improved functionality
    const calculateShippingBtn = document.getElementById('calculate-shipping-btn');
    const shippingZipcode = document.getElementById('shipping-zipcode');
    const shippingResult = document.getElementById('shipping-result');
    
    // Get product price and thresholds
    const productPrice = <?php echo $current_price; ?>;
    const freeShippingThreshold = <?php echo $free_shipping_threshold; ?>;
    const standardShippingCost = <?php echo $standard_shipping_cost; ?>;
    
    function updateShippingCost(zipcode) {
        if (!zipcode || zipcode.length < 5) {
            shippingResult.innerHTML = '<span style="color: #dc3545;">Molimo unesite važeći poštanski broj</span>';
            return;
        }
        
        // Show loading
        shippingResult.innerHTML = '<span>Izračunavanje troškova dostave...</span>';
        
        // Simulate API call with delay
        setTimeout(function() {
            let shippingCost = productPrice >= freeShippingThreshold ? 0 : standardShippingCost;
            
            if (shippingCost === 0) {
                shippingResult.innerHTML = '<span style="color: #28a745;">✓ Besplatna dostava za Vašu porudžbinu</span>';
            } else {
                const amountNeeded = freeShippingThreshold - productPrice;
                shippingResult.innerHTML = `
                    <span>Troškovi dostave: ${shippingCost.toLocaleString('sr-RS')} RSD</span>
                    <div style="margin-top: 5px; color: #dc3545;">
                        Dodajte proizvode u vrednosti od ${amountNeeded.toLocaleString('sr-RS')} RSD za besplatnu dostavu.
                    </div>
                `;
            }
        }, 500);
    }
    
    if (calculateShippingBtn && shippingZipcode && shippingResult) {
        calculateShippingBtn.addEventListener('click', function() {
            updateShippingCost(shippingZipcode.value);
        });
        
        shippingZipcode.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                updateShippingCost(this.value);
            }
        });
    }
    
    // Buy Now functionality with special offer handling
    const buyNowBtn = document.getElementById('buy-now-btn');
    const stickyBuyBtn = document.querySelector('.sticky-buy-btn');
    
    function buyNow(productId, quantity, hasSpecialOffer) {
        // Create FormData object
        const formData = new FormData();
        formData.append('product_id', productId);
        formData.append('quantity', quantity);
        
        // Add special offer information if active
        if (hasSpecialOffer === '1') {
            formData.append('special_offer', 'HVALA2000');
        }
        
        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) {
                // Store special offer in session before redirecting
                if (hasSpecialOffer === '1') {
                    // You might need an extra AJAX call to store this in session
                    fetch('/store-special-offer.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'code=HVALA2000'
                    }).then(() => {
                        window.location.href = '/checkout';
                    });
                } else {
                    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;
            const hasSpecialOffer = this.getAttribute('data-special-offer');
            buyNow(productId, quantity, hasSpecialOffer);
        });
    }
    
    if (stickyBuyBtn) {
        stickyBuyBtn.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            const quantity = document.getElementById('quantity').value;
            const hasSpecialOffer = this.getAttribute('data-special-offer');
            buyNow(productId, quantity, hasSpecialOffer);
        });
    }
    
    // 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'; ?>