<?php
require_once 'includes/config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

// Provera da li je korpa prazna
$cart = get_cart();
if (empty($cart)) {
    header('Location: /');  // Preusmjeravanje na početnu
    exit;
}

// Get cart items
$cart_items = [];
$cart_total = 0;

foreach ($cart as $product_id => $quantity) {
    $product = get_product($product_id);
    if ($product) {
        $price = !empty($product['sale_price']) ? $product['sale_price'] : $product['price'];
        $subtotal = $price * $quantity;
        $cart_total += $subtotal;
        
        // Get product image
        $product_image = get_row("SELECT image FROM product_images WHERE product_id = ? LIMIT 1", [$product_id]);
        $image_url = !empty($product_image) ? UPLOADS_URL . '/products/' . $product_image['image'] : '/assets/images/no-image.jpg';
        
        $cart_items[] = [
            'id' => $product_id,
            'name' => $product['name'],
            'price' => $price,
            'formatted_price' => format_price($price),
            'quantity' => $quantity,
            'subtotal' => $subtotal,
            'formatted_subtotal' => format_price($subtotal),
            'image' => $image_url
        ];
    }
}

// Izračunavanje troškova dostave
$free_shipping_threshold = 15000;
$standard_shipping_cost = 500;
$shipping_cost = ($cart_total >= $free_shipping_threshold) ? 0 : $standard_shipping_cost;
$amount_for_free_shipping = max(0, $free_shipping_threshold - $cart_total);
$is_free_shipping = $shipping_cost === 0;

// Get user data if logged in
$user_data = [];
if (is_logged_in()) {
    $user_data = get_row("SELECT * FROM users WHERE id = ?", [$_SESSION['user_id']]);
}

// Get recommended accessories
$accessories = get_rows("
    SELECT p.id, p.name, p.price, p.sale_price, pi.image 
    FROM products p 
    LEFT JOIN (
        SELECT product_id, image, MIN(id) as min_id 
        FROM product_images 
        GROUP BY product_id
    ) pi ON p.id = pi.product_id 
    WHERE p.id IN (SELECT id FROM products WHERE name LIKE '%dodatak%' OR name LIKE '%oprema%')
    AND p.status = 'active'
    LIMIT 3
");

if (empty($accessories)) {
    // If no accessories found, get random products from other categories
    $accessories = get_rows("
        SELECT p.id, p.name, p.price, p.sale_price, pi.image 
        FROM products p 
        LEFT JOIN (
            SELECT product_id, image, MIN(id) as min_id 
            FROM product_images 
            GROUP BY product_id
        ) pi ON p.id = pi.product_id 
        WHERE p.id NOT IN (" . implode(',', array_keys($cart)) . ")
        AND p.status = 'active'
        ORDER BY RAND()
        LIMIT 3
    ");
}

// Generisanje jedinstvenog ID-a sesije za poklon vaučer
if (!isset($_SESSION['voucher_session_id'])) {
    $_SESSION['voucher_session_id'] = bin2hex(random_bytes(16));
    $_SESSION['voucher_start_time'] = time();
}

// Specijalni kod poklon vaučera
$voucher_code = 'HVALA2000';
?>
<!DOCTYPE html>
<html lang="sr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Završi kupovinu - <?php echo get_setting('site_name', 'Hugong Aparati'); ?></title>
    <meta name="description" content="Brza i sigurna kupovina - samo jedan korak do vašeg novog Hugong aparata za zavarivanje. Besplatna isporuka, garancija 24 meseca.">
    <meta name="robots" content="noindex, follow">
    
    <!-- Favicon -->
    <link rel="icon" href="/favicon.ico">
    <link rel="apple-touch-icon" href="/apple-touch-icon.png">
    
    <!-- CSS -->
    <link rel="stylesheet" href="/assets/css/new/variables.css">
    <link rel="stylesheet" href="/assets/css/new/base.css">
    <link rel="stylesheet" href="/assets/css/new/layout.css">
    <link rel="stylesheet" href="/assets/css/new/components.css">
    <link rel="stylesheet" href="/assets/css/new/pages/category.css">
    <link rel="stylesheet" href="/assets/css/new/pages/checkout.css">
    <link rel="stylesheet" href="/assets/css/new/responsive.css">
    
    <style>
        .is-invalid {
            border-color: #dc3545 !important;
            background-color: rgba(220, 53, 69, 0.05) !important;
        }
        
        .is-valid {
            border-color: #28a745 !important;
            background-color: rgba(40, 167, 69, 0.05) !important;
        }
        
        .error-message {
            color: #dc3545;
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }
        
        .is-invalid {
            border-color: #dc3545 !important;
            box-shadow: 0 0 0 1px #dc3545 !important;
            background-color: rgba(220, 53, 69, 0.05) !important;
        }
        
        .is-valid {
            border-color: #28a745 !important;
            box-shadow: 0 0 0 1px #28a745 !important;
            background-color: rgba(40, 167, 69, 0.05) !important;
        }
        
        .error-message {
            color: #dc3545;
            font-size: 0.85rem;
            margin-top: 0.25rem;
            margin-bottom: 0.5rem;
            font-weight: 500;
            display: flex;
            align-items: center;
        }
        
        .error-message:before {
            content: '';
            display: inline-block;
            width: 16px;
            height: 16px;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23dc3545' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cline x1='12' y1='8' x2='12' y2='12'%3E%3C/line%3E%3Cline x1='12' y1='16' x2='12.01' y2='16'%3E%3C/line%3E%3C/svg%3E");
            background-size: contain;
            background-repeat: no-repeat;
            margin-right: 6px;
        }
        
        /* Stilovi za prijatnije animacije prilikom skrolovanja */
        html {
            scroll-behavior: smooth;
        }
        
        /* Dodatni stilovi za validaciju tokom fokusa */
        .is-invalid:focus {
            box-shadow: 0 0 0 3px rgba(220, 53, 69, 0.25) !important;
        }
        
        /* Unapređena specijalna ponuda */
        .special-offer {
            background: linear-gradient(135deg, #fff8e1 0%, #fff4cc 100%);
            border: 2px solid #ffd700;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
            position: relative;
            box-shadow: 0 4px 15px rgba(255, 215, 0, 0.2);
        }
        
        .special-offer-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .special-offer-icon {
            background-color: #fff;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #ffa000;
            box-shadow: 0 2px 8px rgba(255, 160, 0, 0.2);
        }
        
        .special-offer-title {
            font-weight: 700;
            font-size: 18px;
            color: #7f4e00;
            margin: 0;
        }
        
        .special-offer-desc {
            font-size: 15px;
            color: #7f4e00;
            margin-bottom: 15px;
            line-height: 1.5;
        }
        
        .countdown-timer {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .countdown-item {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .countdown-value {
            font-size: 20px;
            font-weight: 700;
            color: #333;
            background-color: white;
            border-radius: 6px;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
        }
        
        .countdown-label {
            font-size: 12px;
            color: #7f4e00;
            margin-top: 5px;
            font-weight: 500;
        }
        
        .special-offer-status {
            text-align: center;
            font-weight: 600;
            color: #28a745;
            margin-top: 10px;
            font-size: 14px;
        }
        
        .special-offer-expiring {
            color: #dc3545;
            animation: pulse 1s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.7; }
            100% { opacity: 1; }
        }
        
        /* Tooltip za objašnjenje specijalne ponude */
        .offer-tooltip {
            position: relative;
            display: inline-block;
            cursor: help;
            margin-left: 5px;
            color: #999;
        }
        
        .offer-tooltip .tooltip-text {
            visibility: hidden;
            width: 250px;
            background-color: #555;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 8px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            transform: translateX(-50%);
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 12px;
            font-weight: normal;
        }
        
        .offer-tooltip .tooltip-text::after {
            content: "";
            position: absolute;
            top: 100%;
            left: 50%;
            margin-left: -5px;
            border-width: 5px;
            border-style: solid;
            border-color: #555 transparent transparent transparent;
        }
        
        .offer-tooltip:hover .tooltip-text {
            visibility: visible;
            opacity: 1;
        }
        
        /* Expiring notification overlay */
        .expiring-notification {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .notification-content {
            background-color: white;
            width: 90%;
            max-width: 450px;
            border-radius: 8px;
            padding: 25px;
            text-align: center;
            box-shadow: 0 5px 25px rgba(0,0,0,0.2);
        }
        
        .notification-title {
            color: #dc3545;
            font-size: 22px;
            font-weight: 700;
            margin-bottom: 15px;
        }
        
        .notification-message {
            font-size: 16px;
            margin-bottom: 20px;
            line-height: 1.5;
        }
        
        .notification-button {
            display: inline-block;
            background-color: #f6cc00;
            color: #333;
            padding: 12px 25px;
            border-radius: 6px;
            font-weight: 600;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
            border: none;
        }
        
        .notification-button:hover {
            background-color: #e6b900;
        }
        
        /* Stilovi za prikaz troškova dostave */
        .free-shipping-note {
            color: #dc3545;
            font-size: 13px;
        }

        .shipping-note {
            font-size: 12px;
            color: #555;
            margin-top: 3px;
        }
    </style>
</head>
<body id="no-padding-top">
    <!-- Header -->
    <header class="checkout-header">
        <div class="container">
            <a href="/" class="logo"><?php echo get_setting('site_name', 'HUGONG APARATI'); ?></a>
            
            <div class="security-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">
                    <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>
                Sigurna kupovina
            </div>
            
            <!-- Novo dodato dugme -->
            <a href="/" class="continue-shopping-btn">
                ← Nastavak kupovine
            </a>
        </div>
    </header>
    
    <!-- Checkout Content -->
    <div class="checkout-content">
        <div class="container">
            <div class="checkout-grid">
                <!-- Order form -->
                <div class="checkout-form">
                    <form id="checkout-form" action="/process-order.php" method="post">
                        <h2 class="form-title">
                            <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="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                <circle cx="12" cy="7" r="4"></circle>
                            </svg>
                            Podaci za dostavu
                        </h2>
                        
                        <div class="form-section">
                            <div class="form-group">
                                <label for="name" class="required">Ime i prezime</label>
                                <input type="text" id="name" name="name" required value="<?php echo isset($user_data['name']) ? $user_data['name'] : ''; ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="phone" class="required">Telefon</label>
                                <input type="tel" id="phone" name="phone" required value="<?php echo isset($user_data['phone']) ? $user_data['phone'] : ''; ?>">
                            </div>
    
                            <div class="form-group">
                                <label for="email" class="required">Email adresa</label>
                                <input type="email" id="email" name="email" required value="<?php echo isset($user_data['email']) ? $user_data['email'] : ''; ?>">
                            </div>
                        </div>
                        
                        <div class="form-section">
                            <h2 class="form-title">
                                <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="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                                    <circle cx="12" cy="10" r="3"></circle>
                                </svg>
                                Adresa za dostavu
                            </h2>
                            
                            <div class="form-group">
                                <label for="address" class="required">Ulica i broj</label>
                                <input type="text" id="address" name="address" required value="<?php echo isset($user_data['address']) ? $user_data['address'] : ''; ?>">
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="city" class="required">Grad</label>
                                    <input type="text" id="city" name="city" required value="<?php echo isset($user_data['city']) ? $user_data['city'] : ''; ?>">
                                </div>
                                <div class="form-group">
                                    <label for="zip" class="required">Poštanski broj</label>
                                    <input type="text" id="zip" name="zip" required value="<?php echo isset($user_data['zip']) ? $user_data['zip'] : ''; ?>">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-section">
                            <h2 class="form-title">
                                <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="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>
                                Način dostave
                            </h2>
                            
                            <div class="delivery-options">
                                <div class="delivery-option selected" data-shipping-cost="<?php echo $shipping_cost; ?>">
                                    <input type="radio" name="shipping_method" id="delivery-courier" class="delivery-radio" value="courier" checked>
                                    <div class="delivery-info">
                                        <div class="delivery-title">Kurirska služba</div>
                                        <div class="delivery-desc">Isporuka na kućnu adresu u roku od 1-3 radna dana.</div>
                                        <div class="delivery-price">
                                            <?php if($is_free_shipping): ?>
                                                Besplatno
                                            <?php else: ?>
                                                <?php echo format_price($shipping_cost); ?>
                                                <div class="shipping-note">Besplatno za porudžbine preko <?php echo number_format($free_shipping_threshold, 0, ',', '.'); ?> RSD</div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="delivery-option" data-shipping-cost="0">
                                    <input type="radio" name="shipping_method" id="delivery-pickup" class="delivery-radio" value="pickup">
                                    <div class="delivery-info">
                                        <div class="delivery-title">Lično preuzimanje</div>
                                        <div class="delivery-desc">Preuzimanje u Kragujevcu, ul. Oskara Daviča 2 (po prethodnom dogovoru)</div>
                                        <div class="delivery-price">Besplatno</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-section">
                            <h2 class="form-title">
                                <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>
                                Način plaćanja
                            </h2>
                            
                            <div class="payment-options">
                                <div class="payment-option selected">
                                    <input type="radio" name="payment_method" value="cash" checked hidden>
                                    <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="4" width="20" height="16" rx="2"></rect>
                                        <path d="M7 15h0M2 9h20"></path>
                                    </svg>
                                    <div class="payment-option-title">Pouzeće</div>
                                    <div class="payment-option-desc">Plaćanje gotovinom prilikom preuzimanja</div>
                                </div>
                                
                                <div class="payment-option">
                                    <input type="radio" name="payment_method" value="bank" hidden>
                                    <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 11 12 14 22 4"></polyline>
                                        <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path>
                                    </svg>
                                    <div class="payment-option-title">Predračun</div>
                                    <div class="payment-option-desc">Uplata na račun</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="notes">Napomena</label>
                            <textarea id="notes" name="notes" rows="3" placeholder="Unesite napomenu vezanu za porudžbinu (opciono)"></textarea>
                        </div>
                        
                        <!-- Skrivena polja za poklon vaučer -->
                        <input type="hidden" name="base_price" id="base-price" value="<?php echo $cart_total; ?>">
                        <input type="hidden" name="gift_voucher_eligible" id="gift-voucher-eligible" value="1">
                        <input type="hidden" name="voucher_code" id="voucher-code" value="<?php echo $voucher_code; ?>">
                        <input type="hidden" name="voucher_session_id" value="<?php echo $_SESSION['voucher_session_id']; ?>">
                        <input type="hidden" name="voucher_start_time" value="<?php echo $_SESSION['voucher_start_time']; ?>">
                        <input type="hidden" name="shipping_cost" id="shipping-cost-input" value="<?php echo $shipping_cost; ?>">
                    </form>
                </div>
                
                <!-- Order summary -->
                <div class="order-summary">
                    <h3 class="summary-title">Vaša porudžbina</h3>
                    
                    <!-- Specijalna ponuda sa tajmerom -->
                    <div class="special-offer">
                        <div class="special-offer-header">
                            <div class="special-offer-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 2L2 7l10 5 10-5-10-5z"></path>
                                    <path d="M2 17l10 5 10-5"></path>
                                    <path d="M2 12l10 5 10-5"></path>
                                </svg>
                            </div>
                            <h4 class="special-offer-title">
                                POSEBNA PONUDA ZA VAS!
                                <span class="offer-tooltip">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" 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>
                                        <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>
                                        <line x1="12" y1="17" x2="12.01" y2="17"></line>
                                    </svg>
                                    <span class="tooltip-text">Ovu ponudu možete iskoristiti samo ako završite porudžbinu u narednih 15 minuta.</span>
                                </span>
                            </h4>
                        </div>
                        <div class="special-offer-desc">
                            Završite porudžbinu u narednih <strong id="time-remaining-text">15 minuta</strong> i dobijate <strong>poklon vaučer u vrednosti od 2.000 RSD</strong> za sledeću kupovinu!
                        </div>
                        <div class="countdown-timer">
                            <div class="countdown-item">
                                <div class="countdown-value" id="countdown-minutes">15</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-status" id="offer-status">
                            Požurite, ponuda važi samo ograničeno vreme!
                        </div>
                    </div>
                    
                    <div class="product-list">
                        <?php foreach ($cart_items as $item): ?>
                        <div class="product-item" data-product-id="<?php echo $item['id']; ?>">
                            <div class="product-image-container">
                                <img src="<?php echo $item['image']; ?>" alt="<?php echo $item['name']; ?>" class="product-image">
                            </div>
                            <div class="product-details">
                                <div class="product-name"><?php echo $item['name']; ?></div>
                                <div class="product-price-row">
                                    <div class="quantity-wrapper">
                                        <div class="quantity">
                                            <button type="button" class="quantity-btn minus-btn">-</button>
                                            <input type="number" class="quantity-input" value="<?php echo $item['quantity']; ?>" min="1" max="10" readonly>
                                            <button type="button" class="quantity-btn plus-btn">+</button>
                                        </div>
                                    </div>
                                    <div class="price-wrapper">
                                        <div class="product-price" data-unit-price="<?php echo $item['price']; ?>"><?php echo $item['formatted_subtotal']; ?></div>
                                    </div>
                                </div>
                                <?php if (count($cart_items) > 1): ?>
                                <button type="button" class="remove-product-btn" data-product-id="<?php echo $item['id']; ?>">
                                    <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="18" y1="6" x2="6" y2="18"></line>
                                        <line x1="6" y1="6" x2="18" y2="18"></line>
                                    </svg>
                                    Ukloni
                                </button>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Upsell section -->
                    <?php if (!empty($accessories)): ?>
                    <div class="upsell-section">
                        <h4 class="upsell-title">Preporučeni dodaci (opciono):</h4>
                        <div class="upsell-products">
                            <?php foreach ($accessories as $accessory): ?>
                            <div class="upsell-product" data-product-id="<?php echo $accessory['id']; ?>" data-price="<?php echo $accessory['sale_price'] ? $accessory['sale_price'] : $accessory['price']; ?>">
                                <img src="<?php echo !empty($accessory['image']) ? UPLOADS_URL . '/products/' . $accessory['image'] : '/assets/images/no-image.jpg'; ?>" alt="<?php echo $accessory['name']; ?>">
                                <div class="upsell-product-name"><?php echo $accessory['name']; ?></div>
                                <div class="upsell-product-price">
                                    <?php echo $accessory['sale_price'] ? format_price($accessory['sale_price']) : format_price($accessory['price']); ?>
                                </div>
                                <button type="button" class="upsell-add" aria-label="Dodaj u korpu">
                                    <span>+</span>
                                </button>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="summary-totals">
                        <div class="summary-line">
                            <span>Cena proizvoda:</span>
                            <span id="cart-subtotal"><?php echo format_price($cart_total); ?></span>
                        </div>
                        <div class="summary-line">
                            <span>Dodaci:</span>
                            <span id="accessories-total">0,00 rsd</span>
                        </div>
                        <div class="summary-line">
                            <span>Dostava:</span>
                            <span id="shipping-cost"><?php echo $is_free_shipping ? 'Besplatno' : format_price($shipping_cost); ?></span>
                        </div>
                        <?php if(!$is_free_shipping): ?>
                        <div class="summary-line free-shipping-note">
                            <span>Do besplatne dostave:</span>
                            <span><?php echo format_price($amount_for_free_shipping); ?></span>
                        </div>
                        <?php endif; ?>
                        <div class="total-line">
                            <span>Ukupno:</span>
                            <span id="grand-total"><?php echo format_price($cart_total + $shipping_cost); ?></span>
                        </div>
                    </div>

                    <div class="money-back-banner">
                        <div class="guarantee-content">
                            <div class="guarantee-title">Zagarantovan povrat novca u roku od 14 dana</div>
                            <div class="guarantee-desc">Ne pitamo zašto! Potpuno bez rizika za vas.</div>
                        </div>
                    </div>
                    
                    <button type="button" class="checkout-btn" id="place-order">
                        POTVRDITE PORUDŽBINU
                    </button>
                    
                    <div class="trust-elements">
                        <div class="trust-item">
                            <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">
                                <circle cx="12" cy="12" r="10"></circle>
                                <polyline points="16 12 12 8 8 12"></polyline>
                                <line x1="12" y1="16" x2="12" y2="8"></line>
                            </svg>
                            Besplatna dostava
                        </div>
                        <div class="trust-item">
                            <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">
                                <path d="M20.42 4.58a5.4 5.4 0 0 0-7.65 0l-.77.78-.77-.78a5.4 5.4 0 0 0-7.65 0C1.46 6.7 1.33 10.28 4 13l8 8 8-8c2.67-2.72 2.54-6.3.42-8.42z"></path>
                            </svg>
                            Garancija kvaliteta
                        </div>
                        <div class="trust-item">
                            <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">
                                <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>
                            Sigurna kupovina
                        </div>
                        <div class="trust-item">
                            <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">
                                <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>
                            24 meseca garancije
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Back to top button -->
    <button id="back-to-top" aria-label="Nazad na vrh">
        <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">
            <polyline points="18 15 12 9 6 15"></polyline>
        </svg>
    </button>
    
    <!-- Notification when time is almost up -->
    <div class="expiring-notification" id="expiring-notification">
        <div class="notification-content">
            <div class="notification-title">Vaš poklon vaučer uskoro ističe!</div>
            <div class="notification-message">
                Ostalo vam je manje od <strong>3 minuta</strong> da završite porudžbinu i dobijete poklon vaučer u vrednosti od 2.000 RSD.
            </div>
            <button class="notification-button" id="notification-continue">Nastavite kupovinu</button>
        </div>
    </div>
    
    <!-- JavaScript -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Selektori za elemente
        const quantityControls = document.querySelectorAll('.product-item .quantity');
        const upsellProducts = document.querySelectorAll('.upsell-product');
        const cartSubtotalElement = document.getElementById('cart-subtotal');
        const accessoriesTotalElement = document.getElementById('accessories-total');
        const grandTotalElement = document.getElementById('grand-total');
        const shippingCostElement = document.getElementById('shipping-cost');
        const basePriceInput = document.getElementById('base-price');
        const shippingCostInput = document.getElementById('shipping-cost-input');
        const removeButtons = document.querySelectorAll('.remove-product-btn');
        const deliveryOptions = document.querySelectorAll('.delivery-option');
        const paymentOptions = document.querySelectorAll('.payment-option');
        const checkoutForm = document.getElementById('checkout-form');
        const placeOrderBtn = document.getElementById('place-order');
        
        // Elementi za tajmer ponude
        const countdownMinutes = document.getElementById('countdown-minutes');
        const countdownSeconds = document.getElementById('countdown-seconds');
        const offerStatus = document.getElementById('offer-status');
        const timeRemainingText = document.getElementById('time-remaining-text');
        const giftVoucherEligible = document.getElementById('gift-voucher-eligible');
        const expiringNotification = document.getElementById('expiring-notification');
        const notificationContinue = document.getElementById('notification-continue');
        
        // Konstante za tajmer
        const OFFER_DURATION_MINUTES = 15;
        const NOTIFICATION_THRESHOLD_MINUTES = 3;
        const SESSION_ID = '<?php echo $_SESSION['voucher_session_id']; ?>';
        const SERVER_START_TIME = <?php echo $_SESSION['voucher_start_time']; ?>;
        
        // Konstante za dostavu
        const FREE_SHIPPING_THRESHOLD = <?php echo $free_shipping_threshold; ?>;
        const STANDARD_SHIPPING_COST = <?php echo $standard_shipping_cost; ?>;
        
        // Email validacija
        const emailInput = document.getElementById('email');
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        
        // Flag za praćenje da li je email input bio fokusiran
        let emailWasFocused = false;
        
        if (emailInput) {
            // Prati da li je email polje bilo fokusirano
            emailInput.addEventListener('focus', function() {
                emailWasFocused = true;
            });
            
            // Dodaj event listener za email polje
            emailInput.addEventListener('blur', function() {
                validateEmail();
            });
            
            // Validacija email-a dok korisnik kuca
            emailInput.addEventListener('input', function() {
                if (emailInput.classList.contains('is-invalid') || emailWasFocused) {
                    validateEmail();
                }
            });
        }
        
        // Funkcija za validaciju email-a
        function validateEmail() {
            const email = emailInput.value.trim();
            
            // Ako je polje prazno i nikad nije bilo fokusirano, ne prikazujemo grešku
            if (email === '' && !emailWasFocused) {
                emailInput.classList.remove('is-invalid');
                emailInput.classList.remove('is-valid');
                
                // Ukloni poruku o grešci ako postoji
                const errorEl = emailInput.nextElementSibling;
                if (errorEl && errorEl.classList.contains('error-message')) {
                    errorEl.remove();
                }
                return true;
            }
            
            // Ako je polje bilo fokusirano i sad je prazno, tretiraj kao grešku
            if (email === '' && emailWasFocused) {
                emailInput.classList.remove('is-valid');
                emailInput.classList.add('is-invalid');
                
                // Dodaj poruku o grešci ako ne postoji
                let errorEl = emailInput.nextElementSibling;
                if (!errorEl || !errorEl.classList.contains('error-message')) {
                    errorEl = document.createElement('div');
                    errorEl.classList.add('error-message');
                    errorEl.innerHTML = 'Molimo unesite email adresu';
                    emailInput.parentNode.insertBefore(errorEl, emailInput.nextSibling);
                } else {
                    errorEl.innerHTML = 'Molimo unesite email adresu';
                }
                return false;
            }
            
            // Provera formata email-a
            if (emailPattern.test(email)) {
                emailInput.classList.remove('is-invalid');
                emailInput.classList.add('is-valid');
                
                // Ukloni poruku o grešci ako postoji
                const errorEl = emailInput.nextElementSibling;
                if (errorEl && errorEl.classList.contains('error-message')) {
                    errorEl.remove();
                }
                return true;
            } else {
                emailInput.classList.remove('is-valid');
                emailInput.classList.add('is-invalid');
                
                // Dodaj poruku o grešci ako ne postoji
                let errorEl = emailInput.nextElementSibling;
                if (!errorEl || !errorEl.classList.contains('error-message')) {
                    errorEl = document.createElement('div');
                    errorEl.classList.add('error-message');
                    errorEl.innerHTML = 'Unesite ispravnu email adresu';
                    emailInput.parentNode.insertBefore(errorEl, emailInput.nextSibling);
                } else {
                    errorEl.innerHTML = 'Unesite ispravnu email adresu';
                }
                return false;
            }
        }

        // Dodaj event listenere za opcije isporuke
        if (deliveryOptions.length) {
            deliveryOptions.forEach(option => {
                option.addEventListener('click', function() {
                    // Ukloni selektovan stil sa svih opcija
                    deliveryOptions.forEach(opt => {
                        opt.classList.remove('selected');
                        const radio = opt.querySelector('input[type="radio"]');
                        if (radio) radio.checked = false;
                    });
                    
                    // Dodaj selektovan stil trenutnoj opciji
                    this.classList.add('selected');
                    
                    // Označi radio dugme
                    const radio = this.querySelector('input[type="radio"]');
                    if (radio) radio.checked = true;
                    
                    // Ažuriraj ukupne cene
                    updateTotals();
                });
            });
        }

        // Dodaj event listenere za opcije plaćanja
        if (paymentOptions.length) {
            paymentOptions.forEach(option => {
                option.addEventListener('click', function() {
                    // Ukloni selektovan stil sa svih opcija
                    paymentOptions.forEach(opt => {
                        opt.classList.remove('selected');
                        const radio = opt.querySelector('input[type="radio"]');
                        if (radio) radio.checked = false;
                    });
                    
                    // Dodaj selektovan stil trenutnoj opciji
                    this.classList.add('selected');
                    
                    // Označi radio dugme
                    const radio = this.querySelector('input[type="radio"]');
                    if (radio) radio.checked = true;
                });
            });
        }

        // Dodaj event listenere za remove dugmad
        if (removeButtons.length) {
            removeButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const productId = this.getAttribute('data-product-id');
                    if (!productId) {
                        console.error('Product ID nije pronađen!');
                        return;
                    }
                    
                    // Klasični AJAX zahtev umesto fetch
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', '/remove-from-cart.php', true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState === 4) {
                            if (xhr.status === 200) {
                                window.location.reload();
                            } else {
                                console.error('Greška prilikom uklanjanja artikla');
                            }
                        }
                    };
                    xhr.send('product_id=' + encodeURIComponent(productId));
                });
            });
        }

        // Dodaj event listenere za dugmad za količinu
        if (quantityControls.length) {
            quantityControls.forEach(control => {
                const minusBtn = control.querySelector('.minus-btn');
                const plusBtn = control.querySelector('.plus-btn');
                const input = control.querySelector('.quantity-input');
                const productItem = control.closest('.product-item');
                const productId = productItem.getAttribute('data-product-id');
                
                if (minusBtn) {
                    minusBtn.addEventListener('click', function() {
                        let value = parseInt(input.value);
                        if (value > 1) {
                            value--;
                            input.value = value;
                            
                            // Pošalji zahtev za ažuriranje količine
                            const xhr = new XMLHttpRequest();
                            xhr.open('POST', '/update-cart.php', true);
                            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                            xhr.onreadystatechange = function() {
                                if (xhr.readyState === 4) {
                                    if (xhr.status === 200) {
                                        updateTotals();
                                    } else {
                                        console.error('Greška prilikom ažuriranja količine');
                                    }
                                }
                            };
                            xhr.send('product_id=' + encodeURIComponent(productId) + '&quantity=' + encodeURIComponent(value));
                        }
                    });
                }
                
                if (plusBtn) {
                    plusBtn.addEventListener('click', function() {
                        let value = parseInt(input.value);
                        value++;
                        input.value = value;
                        
                        // Pošalji zahtev za ažuriranje količine
                        const xhr = new XMLHttpRequest();
                        xhr.open('POST', '/update-cart.php', true);
                        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                        xhr.onreadystatechange = function() {
                            if (xhr.readyState === 4) {
                                if (xhr.status === 200) {
                                    updateTotals();
                                } else {
                                    console.error('Greška prilikom ažuriranja količine');
                                }
                            }
                        };
                        xhr.send('product_id=' + encodeURIComponent(productId) + '&quantity=' + encodeURIComponent(value));
                    });
                }
            });
        }

        // Funkcionalnost za dodavanje preporučenih dodataka
        if (upsellProducts.length) {
            upsellProducts.forEach(product => {
                const addBtn = product.querySelector('.upsell-add');
                
                // Omogući klik na ceo proizvod
                product.addEventListener('click', function() {
                    toggleUpsellProduct(this);
                });
                
                // Poseban event listener za dugme
                if (addBtn) {
                    addBtn.addEventListener('click', function(e) {
                        e.stopPropagation(); // Sprečava propagaciju do parent elementa
                        toggleUpsellProduct(product);
                    });
                }
            });
        }

        // Funkcija za prebacivanje stanja dodataka
        function toggleUpsellProduct(product) {
            product.classList.toggle('selected');
            
            const addBtn = product.querySelector('.upsell-add');
            if (product.classList.contains('selected')) {
                addBtn.innerHTML = '<span>✓</span>';
            } else {
                addBtn.innerHTML = '<span>+</span>';
            }
            
            // Ažuriraj ukupne cene
            updateTotals();
        }
        
        // Funkcija za proveru besplatne dostave
        function checkFreeShipping(subtotal) {
            return subtotal >= FREE_SHIPPING_THRESHOLD;
        }
        
        // Funkcija za ažuriranje informacija o besplatnoj dostavi
        function updateFreeShippingInfo(subtotal) {
            const amountForFreeShipping = Math.max(0, FREE_SHIPPING_THRESHOLD - subtotal);
            
            // Dodaj ili ukloni napomenu o besplatnoj dostavi
            let freeShippingNoteEl = document.querySelector('.free-shipping-note');
            
            if (amountForFreeShipping > 0) {
                // Ako nije besplatna dostava, prikaži napomenu
                if (!freeShippingNoteEl) {
                    freeShippingNoteEl = document.createElement('div');
                    freeShippingNoteEl.className = 'summary-line free-shipping-note';
                    freeShippingNoteEl.innerHTML = `
                        <span>Do besplatne dostave:</span>
                        <span>${formatPrice(amountForFreeShipping)}</span>
                    `;
                    
                    // Dodaj napomenu pre total-line
                    const totalLine = document.querySelector('.total-line');
                    if (totalLine) {
                        totalLine.parentNode.insertBefore(freeShippingNoteEl, totalLine);
                    }
                } else {
                    // Ažuriraj postojeću napomenu
                    const valueSpan = freeShippingNoteEl.querySelector('span:last-child');
                    if (valueSpan) {
                        valueSpan.textContent = formatPrice(amountForFreeShipping);
                    }
                }
            } else if (freeShippingNoteEl) {
                // Ukloni napomenu ako je dostava besplatna
                freeShippingNoteEl.remove();
            }
        }

        // Funkcija za ažuriranje ukupnih cena
        function updateTotals() {
            // Izračunaj ukupnu cenu proizvoda
            let cartSubtotal = 0;
            document.querySelectorAll('.product-item').forEach(item => {
                const priceElement = item.querySelector('.product-price');
                const quantityInput = item.querySelector('.quantity-input');
                const unitPrice = parseFloat(priceElement.getAttribute('data-unit-price') || 0);
                const quantity = parseInt(quantityInput.value || 1);
                
                // Izračunaj subtotal za ovaj proizvod
                const itemSubtotal = unitPrice * quantity;
                
                // Ažuriraj prikazanu cenu za ovaj proizvod
                priceElement.textContent = formatPrice(itemSubtotal);
                
                cartSubtotal += itemSubtotal;
            });
            
            // Izračunaj cenu dodataka
            let accessoriesTotal = 0;
            document.querySelectorAll('.upsell-product.selected').forEach(product => {
                const price = parseFloat(product.getAttribute('data-price') || 0);
                accessoriesTotal += price;
            });
            
            // Proveri da li je dostava besplatna na osnovu ukupne cene
            const totalBeforeShipping = cartSubtotal + accessoriesTotal;
            const isFreeShipping = checkFreeShipping(totalBeforeShipping);
            
            // Dobavi troškove dostave za izabranu opciju
            const selectedDeliveryOption = document.querySelector('.delivery-option.selected');
            let shippingCost = 0;
            
            if (selectedDeliveryOption && selectedDeliveryOption.getAttribute('data-shipping-cost')) {
                if (selectedDeliveryOption.querySelector('input').value === 'courier' && !isFreeShipping) {
                    shippingCost = STANDARD_SHIPPING_COST;
                } else {
                    shippingCost = 0;
                }
            }
            
            // Ažuriraj prikaz troškova dostave
            if (selectedDeliveryOption && selectedDeliveryOption.querySelector('input').value === 'courier') {
                // Ažuriraj izgled opcije kurirske dostave
                const deliveryPrice = selectedDeliveryOption.querySelector('.delivery-price');
                
                if (deliveryPrice) {
                    if (isFreeShipping) {
                        deliveryPrice.innerHTML = 'Besplatno';
                    } else {
                        deliveryPrice.innerHTML = formatPrice(STANDARD_SHIPPING_COST) + 
                                                '<div class="shipping-note">Besplatno za porudžbine preko ' + 
                                                formatPrice(FREE_SHIPPING_THRESHOLD) + '</div>';
                    }
                }
                
                // Postavi atribut cene dostave
                selectedDeliveryOption.setAttribute('data-shipping-cost', isFreeShipping ? '0' : STANDARD_SHIPPING_COST);
            }
            
            // Ažuriraj prikazane cene
            if (cartSubtotalElement) {
                cartSubtotalElement.textContent = formatPrice(cartSubtotal);
            }
            
            if (accessoriesTotalElement) {
                accessoriesTotalElement.textContent = formatPrice(accessoriesTotal);
            }
            
            if (shippingCostElement) {
                shippingCostElement.textContent = shippingCost > 0 ? formatPrice(shippingCost) : 'Besplatno';
            }
            
            // Ažuriraj informacije o besplatnoj dostavi
            updateFreeShippingInfo(totalBeforeShipping);
            
            if (grandTotalElement) {
                const grandTotal = totalBeforeShipping + shippingCost;
                grandTotalElement.textContent = formatPrice(grandTotal);
            }
            
            // Ažuriraj hidden inputs
            if (basePriceInput) {
                basePriceInput.value = cartSubtotal;
            }
            
            if (shippingCostInput) {
                shippingCostInput.value = shippingCost;
            }
        }

        // Formatiranje cena
        function formatPrice(price) {
            return price.toFixed(2).replace('.', ',') + ' RSD';
        }

        // ============================================================
        // FUNKCIONALNOST POKLON VAUČERA
        // ============================================================
        
        // Funkcija za dobijanje preostalog vremena iz localStorage ili sa servera
        function getTimeRemaining() {
            // Prvo proveri da li je spreman localStorage (ako korisnik osveži stranicu)
            try {
                const savedData = localStorage.getItem('voucherTimerData');
                if (savedData) {
                    const data = JSON.parse(savedData);
                    // Verifikuj da je sesija ista
                    if (data.sessionId === SESSION_ID) {
                        // Uzmi vreme iz localStorage i izračunaj preostalo vreme
                        const currentTime = Math.floor(Date.now() / 1000);
                        const elapsedTime = currentTime - data.startTime;
                        const remainingSeconds = Math.max(0, OFFER_DURATION_MINUTES * 60 - elapsedTime);
                        return remainingSeconds;
                    }
                }
            } catch (e) {
                console.error('Greška pri čitanju iz localStorage', e);
            }
            
            // Ako nema localStorage ili je druga sesija, koristi serversko vreme
            const currentTime = Math.floor(Date.now() / 1000);
            const elapsedTime = currentTime - SERVER_START_TIME;
            return Math.max(0, OFFER_DURATION_MINUTES * 60 - elapsedTime);
        }
        
        // Funkcija za čuvanje vremena u localStorage
        function saveTimerState(secondsRemaining) {
            try {
                const startTime = Math.floor(Date.now() / 1000) - (OFFER_DURATION_MINUTES * 60 - secondsRemaining);
                localStorage.setItem('voucherTimerData', JSON.stringify({
                    sessionId: SESSION_ID,
                    startTime: startTime
                }));
            } catch (e) {
                console.error('Greška pri pisanju u localStorage', e);
            }
        }
        
        // Inicijalizuj tajmer ponude
        let secondsRemaining = getTimeRemaining();
        
        // Sačuvaj početno stanje
        saveTimerState(secondsRemaining);
        
        // Da li je vaučer još uvek važeći
        let isVoucherValid = secondsRemaining > 0;
        
        // Ažuriraj skriveno polje na početku
        giftVoucherEligible.value = isVoucherValid ? '1' : '0';
        
        // Funkcija za ažuriranje tajmera
        function updateTimer() {
            if (secondsRemaining <= 0) {
                // Isteklo vreme
                countdownMinutes.textContent = '00';
                countdownSeconds.textContent = '00';
                timeRemainingText.textContent = '0 minuta';
                offerStatus.textContent = 'Ponuda je istekla. Nažalost, više ne možete dobiti poklon vaučer.';
                offerStatus.classList.add('special-offer-expiring');
                isVoucherValid = false;
                giftVoucherEligible.value = '0';
                
                // Samo jednom prikaži poruku o isteku
                if (localStorage.getItem('voucherExpiredNotified') !== 'true') {
                    localStorage.setItem('voucherExpiredNotified', 'true');
                    alert('Vaša specijalna ponuda je istekla. Nažalost, više ne možete dobiti poklon vaučer, ali i dalje možete završiti porudžbinu.');
                }
                
                return;
            }
            
            // Ako je preostalo manje od NOTIFICATION_THRESHOLD_MINUTES minuta a nije prikazano upozorenje
            if (secondsRemaining <= NOTIFICATION_THRESHOLD_MINUTES * 60 && 
                localStorage.getItem('voucherWarningShown') !== 'true' && 
                isVoucherValid) {
                // Označi da je prikazano upozorenje
                localStorage.setItem('voucherWarningShown', 'true');
                // Prikaži upozorenje
                expiringNotification.style.display = 'flex';
            }
            
            // Ažuriraj prikaz vremena
            const minutes = Math.floor(secondsRemaining / 60);
            const seconds = secondsRemaining % 60;
            
            countdownMinutes.textContent = minutes < 10 ? '0' + minutes : minutes;
            countdownSeconds.textContent = seconds < 10 ? '0' + seconds : seconds;
            
            // Formatiranje teksta
            if (minutes === 1) {
                timeRemainingText.textContent = '1 minut';
            } else {
                timeRemainingText.textContent = minutes + ' minuta';
            }
            
            // Postavi boju na crveno ako je preostalo manje od 5 minuta
            if (secondsRemaining <= 300) {
                offerStatus.textContent = 'Požurite! Vaša specijalna ponuda uskoro ističe!';
                offerStatus.classList.add('special-offer-expiring');
            }
            
            // Smanji preostalo vreme
            secondsRemaining--;
            
            // Sačuvaj stanje tajmera
            saveTimerState(secondsRemaining);
        }
        
        // Inicijalno ažuriranje tajmera
        updateTimer();
        
        // Inicijalno ažuriranje totala
        updateTotals();
        
        // Postavi interval za tajmer
        const timerInterval = setInterval(updateTimer, 1000);
        
        // Zatvori notifikaciju
        if (notificationContinue) {
            notificationContinue.addEventListener('click', function() {
                expiringNotification.style.display = 'none';
            });
        }
        
        // Završi interval kada korisnik napusti stranicu
        window.addEventListener('beforeunload', function() {
            clearInterval(timerInterval);
        });
        
        // Modifikovana funkcija validateForm
        function validateForm() {
            const requiredFields = checkoutForm.querySelectorAll('[required]');
            let isValid = true;
            let firstInvalidField = null;
            
            // Proveri obavezna polja
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    
                    // Dodaj poruku o grešci ako ne postoji
                    let errorEl = field.nextElementSibling;
                    if (!errorEl || !errorEl.classList.contains('error-message')) {
                        errorEl = document.createElement('div');
                        errorEl.classList.add('error-message');
                        errorEl.innerHTML = 'Ovo polje je obavezno';
                        field.parentNode.insertBefore(errorEl, field.nextSibling);
                    }
                    
                    if (!firstInvalidField) {
                        firstInvalidField = field;
                    }
                    
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                    
                    // Ukloni poruku o grešci ako postoji
                    const errorEl = field.nextElementSibling;
                    if (errorEl && errorEl.classList.contains('error-message')) {
                        errorEl.remove();
                    }
                }
            });
            
            // Proveri email adresu, čak i ako nije obavezna
            if (!validateEmail()) {
                isValid = false;
                if (!firstInvalidField) {
                    firstInvalidField = emailInput;
                }
            }
            
            // Ako ima grešaka, skroluj do prvog polja sa greškom
            if (firstInvalidField) {
                scrollToElement(firstInvalidField);
                firstInvalidField.focus();
            }

            return isValid;
        }
        
        // Funkcija za skrolovanje do elementa
        function scrollToElement(element) {
            // Izračunaj poziciju elementa relativno u odnosu na dokument
            const elementRect = element.getBoundingClientRect();
            const absoluteElementTop = elementRect.top + window.pageYOffset;
            
            // Skroluj do elementa (malo iznad njega za bolju vidljivost)
            window.scrollTo({
                top: absoluteElementTop - 100,
                behavior: 'smooth'
            });
        }
        
        // Event listener za dugme za naručivanje
        if (placeOrderBtn) {
            placeOrderBtn.addEventListener('click', function(e) {
                e.preventDefault();

                // Validacija forme
                if (!validateForm()) {
                    return;
                }

                // Dodaj sve odabrane dodatke kao skrivena polja
                const selectedAccessories = document.querySelectorAll('.upsell-product.selected');
                if (selectedAccessories.length > 0) {
                    const accessoriesArray = [];
                    selectedAccessories.forEach(product => {
                        accessoriesArray.push(product.getAttribute('data-product-id'));
                    });
                    
                    const accessoriesInput = document.createElement('input');
                    accessoriesInput.type = 'hidden';
                    accessoriesInput.name = 'accessories';
                    accessoriesInput.value = JSON.stringify(accessoriesArray);
                    checkoutForm.appendChild(accessoriesInput);
                }
                
                // Ponovo ažuriraj status vaučera pre slanja
                giftVoucherEligible.value = isVoucherValid ? '1' : '0';
                
                // Pošalji formu
                checkoutForm.submit();
            });
        }
    });
    </script>
</body>
</html>