{% extends "dashboard/base.html" %}
{% load humanize %}

{% block page_title %}Edit Upcoming Sale -- {{ sale.title }}{% endblock %}
{% block header_actions %}
<a href="{% url 'dashboard:sale_manage' sale.id %}" class="btn btn--secondary btn--sm">Cancel</a>
{% endblock %}

{% block dashboard_content %}
{% if error %}
<div class="alert alert--error mb-6" style="background:#FEE2E2; color:#991B1B; padding:var(--space-4); border-radius:var(--radius-md); border:1px solid #FCA5A5;">
    <strong>Error:</strong> {{ error }}
</div>
{% endif %}

<form method="POST" action="{% url 'dashboard:sale_edit' sale.id %}" id="sale-edit-form">
    {% csrf_token %}

    <!-- 1. General Details -->
    <div class="dash-card mb-6">
        <div class="dash-card__header">
            <h3 class="dash-card__title">Sale Settings</h3>
        </div>
        <div class="dash-card__body">
            <div class="form-group mb-4">
                <label class="form-label" for="title">Sale Title *</label>
                <input type="text" id="title" name="title" class="form-input" required value="{{ sale.title }}">
            </div>

            <div class="grid grid--2 gap-4 mb-4">
                <div class="form-group">
                    <label class="form-label">Pricing Model (Booked)</label>
                    <input type="text" class="form-input" value="{{ sale.get_pricing_model_display }}" disabled style="background:var(--color-border-light); cursor:not-allowed;">
                    <span class="form-help text-xs text-muted mt-1" style="display:block;">Pricing model is fixed and cannot be changed after booking.</span>
                </div>

                <div>
                    <div class="form-group mb-3">
                        <label class="form-label">Start Date & Time *</label>
                        <div class="flex gap-2">
                            <input type="date" name="start_date" class="form-input" required value="{{ sale.start_at|date:'Y-m-d' }}">
                            <input type="time" name="start_time" class="form-input" value="{{ sale.start_at|date:'H:i' }}" style="max-width:110px;">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">End Date & Time *</label>
                        <div class="flex gap-2">
                            <input type="date" name="end_date" class="form-input" required value="{{ sale.end_at|date:'Y-m-d' }}">
                            <input type="time" name="end_time" class="form-input" value="{{ sale.end_at|date:'H:i' }}" style="max-width:110px;">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 2. Products in Sale -->
    <div class="dash-card mb-6">
        <div class="dash-card__header">
            <h3 class="dash-card__title">Manage Products & Pricing</h3>
        </div>
        <div class="dash-card__body">
            {% if products %}
            <div class="flex flex-col gap-4">
                {% for product in products %}
                <div class="card card--flat product-select-row" data-base-price="{{ product.base_price }}" style="padding:var(--space-4);">
                    <div class="flex items-center gap-3 mb-3 flex-wrap">
                        <input type="checkbox" name="product_ids" value="{{ product.id }}" id="prod_{{ product.id }}" {% if product.sale_item %}checked{% endif %} style="width:20px; height:20px; cursor:pointer;">
                        {% if product.primary_image %}
                        <img src="{{ product.primary_image.image.url }}" alt="" style="width:48px; height:48px; border-radius:var(--radius-sm); object-fit:cover;">
                        {% else %}
                        <div style="width:48px; height:48px; border-radius:var(--radius-sm); background:var(--color-border-light); display:flex; align-items:center; justify-content:center; color:var(--color-text-muted); font-size:10px;">No img</div>
                        {% endif %}
                        <div style="flex:1;">
                            <label for="prod_{{ product.id }}" style="font-weight:700; cursor:pointer; font-size:var(--font-size-base);">{{ product.name }}</label>
                            <span class="text-xs text-muted" style="display:block;">Base Price: GHS {{ product.base_price|floatformat:2 }}</span>
                        </div>
                    </div>

                    <div class="grid grid--3 gap-3 pt-3" style="border-top:1px solid var(--color-border-light);">
                        <div>
                            <label class="text-xs form-label">Sale Price (GHS) *</label>
                            <input type="number" step="0.01" min="0.01" name="price_{{ product.id }}" id="price_{{ product.id }}" class="form-input text-sm sale-price-input" value="{% if product.sale_item %}{{ product.sale_item.price }}{% else %}{{ product.base_price }}{% endif %}">
                        </div>
                        <div>
                            <label class="text-xs form-label">Discount (% OFF)</label>
                            <input type="number" step="0.1" min="0" max="99" name="discount_{{ product.id }}" id="discount_{{ product.id }}" class="form-input text-sm sale-discount-input" value="{% if product.sale_item %}{{ product.sale_item.discount_percent|default:'' }}{% endif %}">
                        </div>
                        <div>
                            <label class="text-xs form-label">Sale Stock Pool *</label>
                            <input type="number" min="1" name="stock_{{ product.id }}" class="form-input text-sm" value="{% if product.sale_item %}{{ product.sale_item.stock_total }}{% else %}10{% endif %}">
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
            {% endif %}
        </div>
    </div>

    <div class="flex justify-end gap-3 mb-8">
        <a href="{% url 'dashboard:sale_manage' sale.id %}" class="btn btn--secondary">Cancel</a>
        <button type="submit" class="btn btn--primary btn--lg">Save Changes</button>
    </div>
</form>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.product-select-row').forEach(row => {
        const basePrice = parseFloat(row.getAttribute('data-base-price')) || 0;
        const priceInput = row.querySelector('.sale-price-input');
        const discountInput = row.querySelector('.sale-discount-input');

        if (!priceInput || !discountInput || basePrice <= 0) return;

        let isUpdating = false;

        // Auto-calculate Discount % when Sale Price changes
        priceInput.addEventListener('input', function() {
            if (isUpdating) return;
            isUpdating = true;
            const salePrice = parseFloat(this.value);
            if (!isNaN(salePrice) && salePrice > 0 && salePrice < basePrice) {
                const discountPct = ((basePrice - salePrice) / basePrice) * 100;
                discountInput.value = discountPct.toFixed(1).replace(/\.0$/, '');
            } else {
                discountInput.value = '';
            }
            isUpdating = false;
        });

        // Auto-calculate Sale Price when Discount % changes
        discountInput.addEventListener('input', function() {
            if (isUpdating) return;
            isUpdating = true;
            const discountPct = parseFloat(this.value);
            if (!isNaN(discountPct) && discountPct >= 0 && discountPct < 100) {
                const calculatedSalePrice = basePrice * (1 - (discountPct / 100));
                priceInput.value = calculatedSalePrice.toFixed(2);
            } else if (this.value === '' || discountPct === 0) {
                priceInput.value = basePrice.toFixed(2);
            }
            isUpdating = false;
        });
    });
});
</script>
{% endblock %}
