{% extends "base.html" %}

{% block title %}{{ product.name }} - Golden Uniforms{% endblock %}

{% block content %}
<div class="container py-4">
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{{ url_for('index') }}">Home</a></li>
            <li class="breadcrumb-item"><a href="{{ url_for('products') }}">Products</a></li>
            <li class="breadcrumb-item"><a href="{{ url_for('products', category_id=product.category_id) }}">{{ product.category_ref.name }}</a></li>
            <li class="breadcrumb-item active">{{ product.name }}</li>
        </ol>
    </nav>
    
    <div class="row">
        <div class="col-md-6 mb-4">
            <div class="product-image bg-light d-flex align-items-center justify-content-center" style="height: 500px;">
                {% if product.image_url %}
                    <img src="{{ product.image_url }}" alt="{{ product.name }}" class="img-fluid" style="max-height: 100%; max-width: 100%; object-fit: cover;">
                {% else %}
                    <i class="fas fa-image fa-5x text-muted"></i>
                {% endif %}
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="product-details">
                <h1 class="mb-3">{{ product.name }}</h1>
                
                <div class="mb-3">
                    {% if product.is_featured %}
                        <span class="badge bg-orange me-2">Featured</span>
                    {% endif %}
                    {% if product.is_clearance %}
                        <span class="badge bg-danger me-2">On Sale</span>
                    {% endif %}
                    <span class="badge bg-secondary">{{ product.category_ref.name }}</span>
                    {% if product.subcategory_ref %}
                        <span class="badge bg-light text-dark">{{ product.subcategory_ref.name }}</span>
                    {% endif %}
                </div>
                
                <h2 class="text-orange mb-4">KES {{ "%.2f"|format(product.price) }}</h2>
                
                {% if product.description %}
                <div class="mb-4">
                    <h5>Description</h5>
                    <p>{{ product.description }}</p>
                </div>
                {% endif %}
                
                <!-- Stock and Purchase Section -->
                <div class="product-purchase-section p-4 border rounded mb-4" style="background: #f8f9fa;">
                    <div class="mb-3">
                        <h6 class="fw-bold">Availability</h6>
                        {% if product.stock_quantity > 0 %}
                            <span class="text-success fs-6"><i class="fas fa-check-circle me-1"></i> In Stock</span>
                            <small class="text-muted ms-2">({{ product.stock_quantity }} available)</small>
                        {% else %}
                            <span class="text-danger fs-6"><i class="fas fa-times-circle me-1"></i> Out of Stock</span>
                        {% endif %}
                    </div>
                    
                    <!-- Color Selection -->
                    {% if product.variants %}
                    <div class="mb-4">
                        <h6 class="fw-bold mb-3">Available Colors</h6>
                        <div class="color-options d-flex flex-wrap gap-2">
                            {% for variant in product.variants %}
                            <div class="color-option" data-variant-id="{{ variant.id }}" data-color="{{ variant.color }}" data-price="{{ variant.get_final_price() }}" data-stock="{{ variant.stock_quantity }}" data-image="{{ variant.image_url or product.image_url }}">
                                <div class="color-swatch d-flex align-items-center gap-2 p-2 border rounded cursor-pointer" style="border: 2px solid transparent !important;">
                                    <div class="color-circle" style="width: 24px; height: 24px; border-radius: 50%; background-color: {{ variant.color_code }}; border: 1px solid #ddd;"></div>
                                    <span class="color-name">{{ variant.color }}</span>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                        <input type="hidden" id="selected-variant-id" name="variant_id" value="">
                    </div>
                    {% endif %}
                    
                    {% if product.stock_quantity > 0 or (product.variants and product.variants|selectattr("stock_quantity", "gt", 0)|list) %}
                    <form method="POST" action="{{ url_for('add_to_cart', product_id=product.id) }}" class="add-to-cart-form">
                        <div class="row align-items-end">
                            <div class="col-md-4 mb-3">
                                <label for="quantity" class="form-label fw-bold">Quantity</label>
                                <div class="quantity-selector">
                                    <button type="button" class="btn btn-outline-secondary quantity-btn" data-action="decrease">-</button>
                                    <input type="number" id="quantity" name="quantity" value="1" min="1" max="{{ product.stock_quantity }}" class="form-control quantity-input text-center">
                                    <button type="button" class="btn btn-outline-secondary quantity-btn" data-action="increase">+</button>
                                </div>
                            </div>
                            <div class="col-md-8 mb-3">
                                <button type="submit" class="btn btn-orange btn-lg w-100 add-to-cart-btn">
                                    <i class="fas fa-cart-plus me-2"></i>Add to Cart
                                </button>
                            </div>
                        </div>
                        
                        <!-- Total Price Display -->
                        <div class="total-price-display mt-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="fw-bold">Total Price:</span>
                                <span class="h5 text-orange mb-0" id="total-price">KES {{ "%.2f"|format(product.price) }}</span>
                            </div>
                        </div>
                    </form>
                    
                    <!-- Additional Actions -->
                    <div class="mt-3 d-flex gap-2">
                        <button class="btn btn-outline-dark flex-fill" type="button">
                            <i class="fas fa-heart me-2"></i>Add to Wishlist
                        </button>
                        <button class="btn btn-outline-info flex-fill" type="button" data-bs-toggle="modal" data-bs-target="#shareModal">
                            <i class="fas fa-share-alt me-2"></i>Share
                        </button>
                    </div>
                    {% else %}
                    <div class="out-of-stock-section text-center py-3">
                        <button class="btn btn-secondary btn-lg" disabled>
                            <i class="fas fa-times me-2"></i>Out of Stock
                        </button>
                        <p class="mt-2 mb-0 text-muted">This item is currently unavailable</p>
                    </div>
                    {% endif %}
                </div>
                
                <!-- Sticky Add to Cart Bar (Mobile) -->
                {% if product.stock_quantity > 0 %}
                <div class="sticky-add-to-cart d-none" id="stickyCartBar">
                    <div class="container">
                        <div class="row align-items-center">
                            <div class="col-4">
                                <div class="product-mini-info">
                                    {% if product.image_url %}
                                        <img src="{{ product.image_url }}" alt="{{ product.name }}" class="sticky-product-image">
                                    {% else %}
                                        <div class="sticky-product-placeholder">
                                            <i class="fas fa-image"></i>
                                        </div>
                                    {% endif %}
                                    <div class="sticky-product-details">
                                        <div class="sticky-product-name">{{ product.name[:20] }}{% if product.name|length > 20 %}...{% endif %}</div>
                                        <div class="sticky-product-price">KES {{ "%.0f"|format(product.price) }}</div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-8">
                                <form method="POST" action="{{ url_for('add_to_cart', product_id=product.id) }}" class="sticky-cart-form">
                                    <div class="d-flex align-items-center gap-2">
                                        <div class="quantity-selector-mini">
                                            <button type="button" class="btn btn-sm btn-outline-secondary quantity-btn-mini" data-action="decrease">-</button>
                                            <input type="number" name="quantity" value="1" min="1" max="{{ product.stock_quantity }}" class="form-control form-control-sm quantity-input-mini text-center">
                                            <button type="button" class="btn btn-sm btn-outline-secondary quantity-btn-mini" data-action="increase">+</button>
                                        </div>
                                        <button type="submit" class="btn btn-orange flex-fill">
                                            <i class="fas fa-cart-plus me-1"></i>Add to Cart
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                {% endif %}
                
                <div class="product-info">
                    <h6>Product Information</h6>
                    <ul class="list-unstyled">
                        <li><strong>Category:</strong> {{ product.category_ref.name }}</li>
                        {% if product.subcategory_ref %}
                        <li><strong>Subcategory:</strong> {{ product.subcategory_ref.name }}</li>
                        {% endif %}
                        <li><strong>Product ID:</strong> #{{ product.id }}</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Related Products -->
    {% if related_products %}
    <section class="mt-5">
        <h3 class="mb-4">Related Products</h3>
        <div class="row">
            {% for related_product in related_products %}
            <div class="col-md-3 mb-4">
                <div class="card product-card h-100 shadow-sm">
                    <div class="card-img-top bg-light d-flex align-items-center justify-content-center" style="height: 200px;">
                        {% if related_product.image_url %}
                            <img src="{{ related_product.image_url }}" alt="{{ related_product.name }}" class="img-fluid" style="max-height: 100%; max-width: 100%; object-fit: cover;">
                        {% else %}
                            <i class="fas fa-image fa-2x text-muted"></i>
                        {% endif %}
                    </div>
                    <div class="card-body d-flex flex-column">
                        <h6 class="card-title">{{ related_product.name }}</h6>
                        <div class="d-flex justify-content-between align-items-center mt-auto">
                            <span class="text-orange fw-bold">KES {{ "%.2f"|format(related_product.price) }}</span>
                            <a href="{{ url_for('product_detail', product_id=related_product.id) }}" class="btn btn-outline-orange btn-sm">View</a>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </section>
    {% endif %}
</div>

<style>
.color-option {
    cursor: pointer;
}

.color-swatch {
    transition: all 0.3s ease;
    border: 2px solid transparent !important;
}

.color-option:hover .color-swatch {
    border-color: #ff6b35 !important;
    background-color: rgba(255, 107, 53, 0.1);
}

.color-option.selected .color-swatch {
    border-color: #ff6b35 !important;
    background-color: rgba(255, 107, 53, 0.15);
}

.cursor-pointer {
    cursor: pointer;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const colorOptions = document.querySelectorAll('.color-option');
    const selectedVariantInput = document.getElementById('selected-variant-id');
    const productImage = document.querySelector('.product-image img');
    const priceElement = document.getElementById('total-price');
    const quantityInput = document.querySelector('#quantity');
    const stockInfo = document.querySelector('.text-success, .text-danger');
    const stockText = document.querySelector('.text-muted');
    const addToCartForms = document.querySelectorAll('.add-to-cart-form, .sticky-cart-form');
    
    let basePrice = {{ product.price }};
    let selectedVariant = null;

    // Color selection functionality
    colorOptions.forEach(option => {
        option.addEventListener('click', function() {
            // Remove selected class from all options
            colorOptions.forEach(opt => opt.classList.remove('selected'));
            
            // Add selected class to clicked option
            this.classList.add('selected');
            
            // Get variant data
            const variantId = this.dataset.variantId;
            const variantPrice = parseFloat(this.dataset.price);
            const variantStock = parseInt(this.dataset.stock);
            const variantImage = this.dataset.image;
            
            selectedVariant = {
                id: variantId,
                price: variantPrice,
                stock: variantStock,
                image: variantImage
            };
            
            // Update hidden input
            selectedVariantInput.value = variantId;
            
            // Update product image if variant has specific image
            if (variantImage && productImage) {
                productImage.src = variantImage;
            }
            
            // Update price
            basePrice = variantPrice;
            updateTotalPrice();
            
            // Update stock info
            updateStockInfo(variantStock);
            
            // Update quantity input max value
            if (quantityInput) {
                quantityInput.max = variantStock;
                if (parseInt(quantityInput.value) > variantStock) {
                    quantityInput.value = variantStock;
                }
            }
            
            // Update all forms with variant ID
            addToCartForms.forEach(form => {
                let variantInput = form.querySelector('input[name="variant_id"]');
                if (!variantInput) {
                    variantInput = document.createElement('input');
                    variantInput.type = 'hidden';
                    variantInput.name = 'variant_id';
                    form.appendChild(variantInput);
                }
                variantInput.value = variantId;
            });
        });
    });
    
    function updateTotalPrice() {
        if (priceElement && quantityInput) {
            const quantity = parseInt(quantityInput.value) || 1;
            const total = basePrice * quantity;
            priceElement.textContent = `KES ${total.toFixed(2)}`;
        }
    }
    
    function updateStockInfo(stock) {
        if (stockInfo && stockText) {
            if (stock > 0) {
                stockInfo.className = 'text-success fs-6';
                stockInfo.innerHTML = '<i class="fas fa-check-circle me-1"></i> In Stock';
                stockText.textContent = `(${stock} available)`;
            } else {
                stockInfo.className = 'text-danger fs-6';
                stockInfo.innerHTML = '<i class="fas fa-times-circle me-1"></i> Out of Stock';
                stockText.textContent = '';
            }
        }
    }
    
    // Quantity change handlers
    const quantityInputs = document.querySelectorAll('.quantity-input, .quantity-input-mini');
    quantityInputs.forEach(input => {
        input.addEventListener('change', updateTotalPrice);
        input.addEventListener('input', updateTotalPrice);
    });
    
    // Auto-select first available variant
    if (colorOptions.length > 0) {
        colorOptions[0].click();
    }
});
</script>
{% endblock %}
