{% extends "base.html" %}
{% from "components/ui.html" import page_header %}

{% block content %}
{% set breadcrumbs = [
    {'text': 'Inventory', 'url': url_for('inventory.list_stock_items')},
    {'text': 'Purchase Orders', 'url': url_for('inventory.list_purchase_orders')},
    {'text': 'New Purchase Order'}
] %}

{{ page_header(
    icon_class='fas fa-shopping-cart',
    title_text='New Purchase Order',
    subtitle_text='Create a new purchase order to a supplier',
    breadcrumbs=breadcrumbs
) }}

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm max-w-6xl mx-auto">
    <form method="POST" action="{{ url_for('inventory.new_purchase_order') }}">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        
        <!-- Basic Information -->
        <div class="mb-6">
            <h3 class="text-lg font-semibold mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
                <i class="fas fa-info-circle mr-2"></i>{{ _('Basic Information') }}
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="supplier_id" class="form-label">{{ _('Supplier') }} *</label>
                    <select name="supplier_id" id="supplier_id" class="form-input" required>
                        <option value="">{{ _('Select Supplier') }}</option>
                        {% for supplier in suppliers %}
                        <option value="{{ supplier.id }}">{{ supplier.code }} - {{ supplier.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div>
                    <label for="order_date" class="form-label">{{ _('Order Date') }} *</label>
                    <input type="date" name="order_date" id="order_date" value="{{ request.form.get('order_date', '') }}" class="form-input" required>
                </div>
                <div>
                    <label for="expected_delivery_date" class="form-label">{{ _('Expected Delivery Date') }}</label>
                    <input type="date" name="expected_delivery_date" id="expected_delivery_date" value="{{ request.form.get('expected_delivery_date', '') }}" class="form-input">
                </div>
                <div>
                    <label for="currency_code" class="form-label">{{ _('Currency') }}</label>
                    <select name="currency_code" id="currency_code" class="form-input">
                        <option value="EUR" selected>EUR</option>
                        <option value="USD">USD</option>
                        <option value="GBP">GBP</option>
                        <option value="CHF">CHF</option>
                    </select>
                </div>
                <div class="md:col-span-2">
                    <label for="notes" class="form-label">{{ _('Notes') }}</label>
                    <textarea name="notes" id="notes" rows="2" class="form-input" placeholder="{{ _('Notes visible to supplier') }}">{{ request.form.get('notes', '') }}</textarea>
                </div>
                <div class="md:col-span-2">
                    <label for="internal_notes" class="form-label">{{ _('Internal Notes') }}</label>
                    <textarea name="internal_notes" id="internal_notes" rows="2" class="form-input" placeholder="{{ _('Internal notes (not visible to supplier)') }}">{{ request.form.get('internal_notes', '') }}</textarea>
                </div>
            </div>
        </div>

        <!-- Purchase Order Items -->
        <div class="mb-6">
            <div class="flex items-center justify-between mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold">
                    <i class="fas fa-list mr-2"></i>{{ _('Items') }}
                </h3>
                <button type="button" id="add-item" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors">
                    <i class="fas fa-plus mr-2"></i>{{ _('Add Item') }}
                </button>
            </div>
            
            <div class="hidden md:grid md:grid-cols-12 gap-3 mb-2 px-3 text-xs font-semibold text-gray-500 uppercase">
                <div class="md:col-span-3">{{ _('Stock Item') }}</div>
                <div class="md:col-span-2">{{ _('Description') }}</div>
                <div class="md:col-span-1">{{ _('Qty') }}</div>
                <div class="md:col-span-1">{{ _('Unit Cost') }}</div>
                <div class="md:col-span-1">{{ _('Total') }}</div>
                <div class="md:col-span-2">{{ _('Warehouse') }}</div>
                <div class="md:col-span-1">{{ _('Supplier SKU') }}</div>
                <div class="md:col-span-1 text-center">{{ _('Action') }}</div>
            </div>
            
            <div id="po-items" class="space-y-2">
                <!-- Items will be added here dynamically -->
            </div>
            
            <div class="mt-4 p-3 bg-primary/5 rounded-lg border border-primary/20">
                <div class="flex justify-between items-center">
                    <span class="text-sm font-medium">{{ _('Subtotal') }}:</span>
                    <span class="text-lg font-bold text-primary" id="po-subtotal">0.00</span>
                </div>
            </div>
        </div>

        <div class="mt-6 flex flex-col sm:flex-row justify-end gap-3">
            <a href="{{ url_for('inventory.list_purchase_orders') }}" class="px-4 py-2 bg-gray-200 dark:bg-gray-700 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors text-center">
                {{ _('Cancel') }}
            </a>
            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                {{ _('Create Purchase Order') }}
            </button>
        </div>
    </form>
</div>

{% block scripts_extra %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const itemsContainer = document.getElementById('po-items');
    const addItemBtn = document.getElementById('add-item');
    const supplierSelect = document.getElementById('supplier_id');
    
    const stockItems = {{ stock_items | tojson if stock_items else '[]' }};
    const warehouses = {{ warehouses | tojson if warehouses else '[]' }};
    
    // Build stock items dropdown HTML
    function buildStockItemsHtml(selectedSupplierId = null) {
        let html = '<option value="">{{ _("Select Item") }}</option>';
        stockItems.forEach(item => {
            html += '<option value="' + item.id + '" data-name="' + (item.name || '').replace(/"/g, '&quot;') + '" data-unit="' + (item.unit || '') + '">' + item.sku + ' - ' + item.name + '</option>';
        });
        return html;
    }
    
    // Build warehouses dropdown HTML
    function buildWarehousesHtml() {
        let html = '<option value="">{{ _("Select Warehouse") }}</option>';
        warehouses.forEach(wh => {
            html += '<option value="' + wh.id + '">' + wh.code + ' - ' + wh.name + '</option>';
        });
        return html;
    }
    
    // Add item row
    function addItemRow(item = null) {
        const row = document.createElement('div');
        row.className = 'grid grid-cols-1 md:grid-cols-12 gap-3 p-3 rounded-lg bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 po-item-row';
        
        row.innerHTML = 
            '<input type="hidden" name="item_stock_item_id[]" value="' + (item && item.stock_item_id ? item.stock_item_id : '') + '">' +
            '<input type="hidden" name="item_supplier_stock_item_id[]" value="' + (item && item.supplier_stock_item_id ? item.supplier_stock_item_id : '') + '">' +
            '<select name="item_stock_item_id[]" class="md:col-span-3 form-input text-sm item-stock-select">' + buildStockItemsHtml() + '</select>' +
            '<input type="text" name="item_description[]" placeholder="{{ _("Description") }}" value="' + (item ? (item.description || '').replace(/"/g, '&quot;') : '') + '" class="md:col-span-2 form-input text-sm item-description" required>' +
            '<input type="number" name="item_quantity[]" placeholder="{{ _("Qty") }}" value="' + (item ? item.quantity_ordered : '1') + '" step="0.01" min="0" class="md:col-span-1 form-input text-sm item-quantity" required data-calc-trigger>' +
            '<input type="number" name="item_unit_cost[]" placeholder="{{ _("Cost") }}" value="' + (item ? item.unit_cost : '') + '" step="0.01" min="0" class="md:col-span-1 form-input text-sm item-cost" required data-calc-trigger>' +
            '<div class="md:col-span-1 flex items-center font-medium item-total">0.00</div>' +
            '<select name="item_warehouse_id[]" class="md:col-span-2 form-input text-sm">' + buildWarehousesHtml() + '</select>' +
            '<input type="text" name="item_supplier_sku[]" placeholder="{{ _("Supplier SKU") }}" value="' + (item ? (item.supplier_sku || '') : '') + '" class="md:col-span-1 form-input text-sm">' +
            '<button type="button" class="remove-item md:col-span-1 bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300 px-3 py-2 rounded hover:bg-rose-200 dark:hover:bg-rose-900/50 transition text-sm" title="{{ _("Remove") }}">' +
                '<i class="fas fa-trash"></i>' +
            '</button>';
        
        itemsContainer.appendChild(row);
        
        // Setup stock item select handler
        const stockSelect = row.querySelector('.item-stock-select');
        stockSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const descInput = row.querySelector('.item-description');
            if (selectedOption && selectedOption.dataset.name && !descInput.value) {
                descInput.value = selectedOption.dataset.name;
            }
        });
        
        // Setup calculation triggers
        row.querySelectorAll('[data-calc-trigger]').forEach(input => {
            input.addEventListener('input', calculateTotals);
        });
        
        // Setup remove button
        row.querySelector('.remove-item').addEventListener('click', function() {
            row.remove();
            calculateTotals();
        });
        
        calculateTotals();
    }
    
    // Calculate totals
    function calculateTotals() {
        let subtotal = 0;
        
        document.querySelectorAll('.po-item-row').forEach(row => {
            const qty = parseFloat(row.querySelector('.item-quantity')?.value || 0);
            const cost = parseFloat(row.querySelector('.item-cost')?.value || 0);
            const total = qty * cost;
            
            const totalEl = row.querySelector('.item-total');
            if (totalEl) {
                totalEl.textContent = total.toFixed(2);
            }
            
            subtotal += total;
        });
        
        document.getElementById('po-subtotal').textContent = subtotal.toFixed(2);
    }
    
    // Add item button
    addItemBtn.addEventListener('click', function() {
        addItemRow();
    });
    
    // Add initial row
    addItemRow();
});
</script>
{% endblock %}
{% endblock %}

