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

{% block content %}
{% set breadcrumbs = [
    {'text': 'Inventory', 'url': url_for('inventory.list_stock_items')},
    {'text': 'Stock Movements', 'url': url_for('inventory.list_movements')},
    {'text': 'Record Movement'}
] %}

{{ page_header(
    icon_class='fas fa-exchange-alt',
    title_text='Record Stock Movement',
    subtitle_text='Record inventory adjustment or movement',
    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-2xl mx-auto">
    <form method="POST" action="{{ url_for('inventory.new_movement') }}" id="movement_form"
          data-hint-return="{{ _('Use a positive quantity (items coming back)') }}"
          data-hint-waste="{{ _('Use a negative quantity (items written off)') }}"
          data-hint-devaluation="{{ _('Quantity to revalue (positive)') }}"
          data-hint-default="{{ _('Use positive values for additions, negative for removals') }}"
          data-msg-return-positive="{{ _('Return requires a positive quantity.') }}"
          data-msg-waste-negative="{{ _('Waste requires a negative quantity.') }}"
          data-msg-devaluation-unsupported="{{ _('Devaluation requires a trackable item with a default cost.') }}">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <div class="space-y-6">
            <div>
                <label for="movement_type" class="form-label">{{ _('Movement Type') }} *</label>
                <select name="movement_type" id="movement_type" class="form-input" required>
                    <option value="adjustment">{{ _('Adjustment') }}</option>
                    <option value="transfer">{{ _('Transfer') }}</option>
                    <option value="sale">{{ _('Sale') }}</option>
                    <option value="rent">{{ _('Rent') }}</option>
                    <option value="purchase">{{ _('Purchase') }}</option>
                    <option value="return">{{ _('Return') }}</option>
                    <option value="waste">{{ _('Waste') }}</option>
                    <option value="devaluation">{{ _('Devaluation') }}</option>
                </select>
                <p class="mt-1 text-sm text-gray-500 dark:text-gray-400 hidden" id="devaluation_discovery_hint">{{ _('You can apply devaluation below to record returned or wasted items at a reduced cost.') }}</p>
            </div>
            <div>
                <label for="stock_item_id" class="form-label">{{ _('Stock Item') }} *</label>
                <select name="stock_item_id" id="stock_item_id" class="form-input" required>
                    <option value="">{{ _('Select Item') }}</option>
                    {% for item in stock_items %}
                    <option value="{{ item.id }}" data-devaluation-supported="{{ 'true' if (item.is_trackable and item.default_cost is not none and (item.default_cost|float) > 0) else 'false' }}">{{ item.sku }} - {{ item.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label for="warehouse_id" class="form-label">{{ _('Warehouse') }} *</label>
                <select name="warehouse_id" id="warehouse_id" class="form-input" required>
                    <option value="">{{ _('Select Warehouse') }}</option>
                    {% for warehouse in warehouses %}
                    <option value="{{ warehouse.id }}">{{ warehouse.code }} - {{ warehouse.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label for="quantity" class="form-label">{{ _('Quantity') }} *</label>
                <input type="number" name="quantity" id="quantity" step="0.01" class="form-input" required>
                <p class="mt-1 text-sm text-gray-500" id="quantity_hint">{{ _('Use positive values for additions, negative for removals') }}</p>
                <p class="mt-1 text-sm text-red-600 dark:text-red-400 hidden" id="quantity_error" role="alert"></p>
            </div>

            <!-- Devaluation options (Return / Waste / Devaluation) -->
            <div id="devaluation_section" class="hidden border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <p class="text-sm text-amber-600 dark:text-amber-400 hidden mt-0 mb-2" id="devaluation_unsupported_msg" role="alert"></p>
                <div class="flex items-center justify-between">
                    <div>
                        <h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">{{ _('Devaluation') }}</h3>
                        <p class="text-sm text-gray-500">{{ _('Devalue items without creating a new stock item') }}</p>
                    </div>
                    <label class="inline-flex items-center gap-2">
                        <input type="checkbox" name="devalue_enabled" id="devalue_enabled" class="rounded border-gray-300 dark:border-gray-600">
                        <span class="text-sm text-gray-700 dark:text-gray-300">{{ _('Apply devaluation') }}</span>
                    </label>
                </div>

                <div id="devaluation_fields" class="mt-4 space-y-4 hidden">
                    <div>
                        <label for="devalue_method" class="form-label">{{ _('Method') }}</label>
                        <select name="devalue_method" id="devalue_method" class="form-input">
                            <option value="percent">{{ _('Percent off default cost') }}</option>
                            <option value="fixed">{{ _('Fixed new unit cost') }}</option>
                        </select>
                    </div>

                    <div id="devalue_percent_row">
                        <label for="devalue_percent" class="form-label">{{ _('Percent') }}</label>
                        <input type="number" name="devalue_percent" id="devalue_percent" step="0.01" min="0" max="100" class="form-input" placeholder="e.g. 30">
                        <p class="mt-1 text-sm text-gray-500">{{ _('Example: 30 = reduce cost by 30%') }}</p>
                    </div>

                    <div id="devalue_fixed_row" class="hidden">
                        <label for="devalue_unit_cost" class="form-label">{{ _('New Unit Cost') }}</label>
                        <input type="number" name="devalue_unit_cost" id="devalue_unit_cost" step="0.01" min="0" class="form-input" placeholder="e.g. 2.50">
                    </div>
                </div>
            </div>
            <div>
                <label for="reason" class="form-label">{{ _('Reason') }}</label>
                <input type="text" name="reason" id="reason" class="form-input" placeholder="{{ _('e.g., Physical count correction') }}">
            </div>
            <div>
                <label for="notes" class="form-label">{{ _('Notes') }}</label>
                <textarea name="notes" id="notes" rows="3" class="form-input"></textarea>
            </div>
        </div>
        <div class="mt-6 flex flex-col sm:flex-row justify-end gap-3">
            <a href="{{ url_for('inventory.list_movements') }}" 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">
                {{ _('Record Movement') }}
            </button>
        </div>
    </form>
</div>

<script>
    (function () {
        const form = document.getElementById('movement_form');
        const movementType = document.getElementById('movement_type');
        const section = document.getElementById('devaluation_section');
        const enabled = document.getElementById('devalue_enabled');
        const fields = document.getElementById('devaluation_fields');
        const method = document.getElementById('devalue_method');
        const percentRow = document.getElementById('devalue_percent_row');
        const fixedRow = document.getElementById('devalue_fixed_row');
        const quantityHint = document.getElementById('quantity_hint');
        const quantityError = document.getElementById('quantity_error');
        const devaluePercent = document.getElementById('devalue_percent');
        const devalueUnitCost = document.getElementById('devalue_unit_cost');
        const discoveryHint = document.getElementById('devaluation_discovery_hint');
        const unsupportedMsg = document.getElementById('devaluation_unsupported_msg');

        function selectedItemSupportsDevaluation() {
            const sel = document.getElementById('stock_item_id');
            const opt = sel.options[sel.selectedIndex];
            if (!opt || !opt.value) return true;
            return opt.getAttribute('data-devaluation-supported') === 'true';
        }

        function refreshVisibility() {
            const type = (movementType.value || '').toLowerCase();
            const showSection = (type === 'return' || type === 'waste' || type === 'devaluation');
            section.classList.toggle('hidden', !showSection);

            const showDiscoveryHint = (type === 'return' || type === 'waste');
            if (discoveryHint) discoveryHint.classList.toggle('hidden', !showDiscoveryHint);

            const canDevalue = selectedItemSupportsDevaluation();
            const isReturnOrWaste = (type === 'return' || type === 'waste');

            if (type === 'devaluation') {
                enabled.checked = true;
                enabled.disabled = true;
                if (unsupportedMsg) {
                    if (!canDevalue) {
                        unsupportedMsg.textContent = form.dataset.msgDevaluationUnsupported || 'Devaluation requires a trackable item with a default cost.';
                        unsupportedMsg.classList.remove('hidden');
                    } else {
                        unsupportedMsg.classList.add('hidden');
                        unsupportedMsg.textContent = '';
                    }
                }
            } else if (isReturnOrWaste && !canDevalue) {
                enabled.checked = false;
                enabled.disabled = true;
                if (unsupportedMsg) {
                    unsupportedMsg.textContent = form.dataset.msgDevaluationUnsupported || 'Devaluation requires a trackable item with a default cost.';
                    unsupportedMsg.classList.remove('hidden');
                }
            } else {
                enabled.disabled = false;
                if (unsupportedMsg) { unsupportedMsg.classList.add('hidden'); unsupportedMsg.textContent = ''; }
            }

            const showFields = showSection && enabled.checked && !enabled.disabled;
            fields.classList.toggle('hidden', !showFields);

            const m = (method.value || 'percent');
            percentRow.classList.toggle('hidden', m !== 'percent');
            fixedRow.classList.toggle('hidden', m !== 'fixed');

            // Dynamic quantity hint
            var hintKey = type === 'return' ? 'hintReturn' : type === 'waste' ? 'hintWaste' : type === 'devaluation' ? 'hintDevaluation' : 'hintDefault';
            quantityHint.textContent = (form.dataset[hintKey] || form.dataset.hintDefault) || '';

            // Required on devaluation inputs when section is shown and method matches
            devaluePercent.required = showFields && (m === 'percent');
            devalueUnitCost.required = showFields && (m === 'fixed');
        }

        form.addEventListener('submit', function (e) {
            quantityError.classList.add('hidden');
            quantityError.textContent = '';
            var type = (movementType.value || '').toLowerCase();
            var qty = parseFloat(form.querySelector('#quantity').value, 10);
            if (type === 'return' && qty <= 0) {
                e.preventDefault();
                quantityError.textContent = form.dataset.msgReturnPositive || 'Return requires a positive quantity.';
                quantityError.classList.remove('hidden');
                return;
            }
            if (type === 'waste' && qty >= 0) {
                e.preventDefault();
                quantityError.textContent = form.dataset.msgWasteNegative || 'Waste requires a negative quantity.';
                quantityError.classList.remove('hidden');
                return;
            }
        });

        movementType.addEventListener('change', refreshVisibility);
        document.getElementById('stock_item_id').addEventListener('change', refreshVisibility);
        enabled.addEventListener('change', refreshVisibility);
        method.addEventListener('change', refreshVisibility);
        refreshVisibility();
    })();
</script>
{% endblock %}

