@extends('layouts.admin.app')

@section('title', translate('Add Purchase Entry'))

@php
    $oldPurchaseItems = old('items');
    if (! is_array($oldPurchaseItems) || count($oldPurchaseItems) === 0) {
        $oldPurchaseItems = [[
            'item_id' => old('item_id'),
            'variation_type' => old('variation_type'),
            'quantity' => old('quantity', 1),
            'purchase_price' => old('purchase_price'),
        ]];
    }
@endphp

@section('content')
    <div class="content container-fluid">
        <div class="page-header">
            <h1 class="page-header-title">
                <span class="page-header-icon">
                    <i class="tio-add-circle"></i>
                </span>
                <span>{{ translate('Add Purchase Entry') }}</span>
            </h1>
            <div class="page-header-right">
                <a href="{{ route('admin.purchase.index') }}" class="btn btn--light">{{ translate('Back to Purchase History') }}</a>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                @if($errors->any())
                    <div class="alert alert-danger">
                        <ul class="mb-0 pl-3">
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <form action="{{ route('admin.purchase.store') }}" method="post">
                    @csrf

                    <div class="row g-3">
                        <div class="col-sm-6 col-md-4">
                            <label class="input-label">{{ translate('Purchase Date') }}</label>
                            <input type="date" name="purchase_date" value="{{ old('purchase_date', now()->toDateString()) }}" class="form-control" required>
                        </div>
                        <div class="col-sm-6 col-md-4">
                            <label class="input-label">{{ translate('Supplier / Source') }}</label>
                            <input type="text" name="supplier_name" value="{{ old('supplier_name') }}" class="form-control">
                        </div>
                        <div class="col-sm-12 col-md-4">
                            <label class="input-label">{{ translate('Invoice Number') }}</label>
                            <input type="text" name="invoice_number" value="{{ old('invoice_number') }}" class="form-control">
                        </div>
                    </div>

                    <div class="d-flex flex-wrap justify-content-between align-items-center mt-4 mb-3 gap-2">
                        <div>
                            <h4 class="mb-1">{{ translate('Purchase Items') }}</h4>
                            <p class="mb-0 text-muted">
                                {{ translate('Add multiple products in one purchase entry and submit all quantities and prices together.') }}
                            </p>
                        </div>
                        <button type="button" class="btn btn--primary" id="add-purchase-row">
                            <i class="tio-add"></i> {{ translate('Add Another Product') }}
                        </button>
                    </div>

                    <div class="table-responsive border rounded">
                        <table class="table table-borderless table-align-middle mb-0" id="purchase-items-table">
                            <thead class="thead-light">
                            <tr>
                                <th style="min-width: 250px;">{{ translate('Product') }}</th>
                                <th style="min-width: 180px;">{{ translate('Variation') }}</th>
                                <th style="min-width: 150px;">{{ translate('Current Stock') }}</th>
                                <th style="min-width: 130px;">{{ translate('Quantity') }}</th>
                                <th style="min-width: 170px;">{{ translate('Purchase Price (Per Piece)') }}</th>
                                <th style="min-width: 150px;">{{ translate('Line Total') }}</th>
                                <th class="text-center" style="width: 72px;">{{ translate('Action') }}</th>
                            </tr>
                            </thead>
                            <tbody id="purchase-items-body"></tbody>
                        </table>
                    </div>

                    <div class="row g-3 mt-2">
                        <div class="col-md-6">
                            <label class="input-label">{{ translate('Note') }}</label>
                            <textarea name="note" rows="4" class="form-control">{{ old('note') }}</textarea>
                        </div>
                        <div class="col-md-6">
                            <div class="card h-100 bg-light border-0">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between mb-2">
                                        <span class="text-muted">{{ translate('Total Products') }}</span>
                                        <strong id="purchase-total-products">0</strong>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span class="text-muted">{{ translate('Total Quantity') }}</span>
                                        <strong id="purchase-total-quantity">0</strong>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <span class="text-muted">{{ translate('Grand Total Amount') }}</span>
                                        <strong id="purchase-grand-total">0.00</strong>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="d-flex justify-content-end gap-3 mt-4">
                        <a href="{{ route('admin.purchase.index') }}" class="btn btn--reset">{{ translate('Cancel') }}</a>
                        <button type="submit" class="btn btn--primary">{{ translate('Save Purchase Entry') }}</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('script_2')
    <script>
        "use strict";

        const purchaseInitialRows = @json(array_values($oldPurchaseItems));
        const purchaseSearchUrl = @json(route('admin.purchase.search-items'));
        const purchaseMetaUrl = @json(route('admin.purchase.item-meta'));
        const purchaseItemsBody = $('#purchase-items-body');
        const purchaseAddRowButton = $('#add-purchase-row');
        const purchaseTotalProducts = $('#purchase-total-products');
        const purchaseTotalQuantity = $('#purchase-total-quantity');
        const purchaseGrandTotal = $('#purchase-grand-total');
        let purchaseRowIndex = 0;

        function purchaseLineTotal(quantity, price) {
            return (parseFloat(quantity || 0) * parseFloat(price || 0)).toFixed(2);
        }

        function updatePurchaseSummary() {
            let totalProducts = 0;
            let totalQuantity = 0;
            let grandTotal = 0;

            purchaseItemsBody.find('.purchase-item-row').each(function () {
                totalProducts += 1;
                const quantity = parseFloat($(this).find('.purchase-quantity').val() || 0);
                const price = parseFloat($(this).find('.purchase-price').val() || 0);
                totalQuantity += quantity;
                grandTotal += quantity * price;
            });

            purchaseTotalProducts.text(totalProducts);
            purchaseTotalQuantity.text(totalQuantity);
            purchaseGrandTotal.text(grandTotal.toFixed(2));

            const rows = purchaseItemsBody.find('.purchase-item-row');
            rows.find('.remove-purchase-row').prop('disabled', rows.length <= 1);
        }

        function updateRowTotal($row) {
            const quantity = $row.find('.purchase-quantity').val();
            const price = $row.find('.purchase-price').val();
            $row.find('.purchase-line-total').val(purchaseLineTotal(quantity, price));
            updatePurchaseSummary();
        }

        function resetRowMeta($row) {
            $row.find('.purchase-stock-label').text('{{ translate('Select a product') }}');
            $row.find('.purchase-store-label').text('');
            const $variationWrapper = $row.find('.variation-field-wrapper');
            const $variationSelect = $row.find('.variation-type-select');
            $variationSelect.html('<option value="">{{ translate('Select variation') }}</option>').val('');
            $variationWrapper.addClass('d-none');
        }

        function initializePurchaseItemSelect($row) {
            const $itemSelect = $row.find('.purchase-item-select');
            const preselectedId = $itemSelect.data('selectedId');

            $itemSelect.select2({
                placeholder: '{{ translate('Search product from existing list') }}',
                ajax: {
                    url: purchaseSearchUrl,
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return { q: params.term };
                    },
                    processResults: function (data) {
                        return { results: data };
                    }
                }
            });

            $itemSelect.on('change', function () {
                loadPurchaseItemMeta($(this).val(), $row);
            });

            if (preselectedId) {
                loadPurchaseItemMeta(preselectedId, $row, $row.find('.variation-type-select').data('selectedValue'));
            } else {
                resetRowMeta($row);
            }
        }

        function loadPurchaseItemMeta(itemId, $row, selectedVariation = null) {
            const $itemSelect = $row.find('.purchase-item-select');
            const $variationWrapper = $row.find('.variation-field-wrapper');
            const $variationSelect = $row.find('.variation-type-select');
            const $stockLabel = $row.find('.purchase-stock-label');
            const $storeLabel = $row.find('.purchase-store-label');

            if (!itemId) {
                resetRowMeta($row);
                return;
            }

            $.get({
                url: purchaseMetaUrl,
                data: { item_id: itemId },
                success: function (response) {
                    const optionText = response.name + (response.store_name ? ' (' + response.store_name + ')' : '');
                    if (!$itemSelect.find("option[value='" + response.id + "']").length) {
                        const option = new Option(optionText, response.id, true, true);
                        $itemSelect.append(option);
                    } else {
                        $itemSelect.find("option:selected").text(optionText);
                    }
                    $itemSelect.trigger('change.select2');

                    $stockLabel.text(response.current_stock);
                    $storeLabel.text(response.store_name ? '{{ translate('Store') }}: ' + response.store_name : '');

                    if (response.has_variations) {
                        let options = '<option value="">{{ translate('Select variation') }}</option>';
                        response.variations.forEach(function (variation) {
                            const selected = selectedVariation && selectedVariation === variation.type ? 'selected' : '';
                            options += '<option value=\"' + variation.type + '\" ' + selected + '>' + variation.type + ' ({{ translate('Stock') }}: ' + variation.stock + ')</option>';
                        });
                        $variationSelect.html(options);
                        $variationWrapper.removeClass('d-none');
                    } else {
                        $variationSelect.html('<option value="">{{ translate('Select variation') }}</option>').val('');
                        $variationWrapper.addClass('d-none');
                    }
                }
            });
        }

        function createPurchaseRow(values = {}) {
            const rowIndex = purchaseRowIndex++;
            const itemId = values.item_id || '';
            const variationType = values.variation_type || '';
            const quantity = values.quantity || 1;
            const purchasePrice = values.purchase_price || '';
            const rowHtml = `
                <tr class="purchase-item-row" data-index="${rowIndex}">
                    <td>
                        <select
                            name="items[${rowIndex}][item_id]"
                            class="form-control purchase-item-select"
                            data-selected-id="${itemId}"
                        ></select>
                    </td>
                    <td>
                        <div class="variation-field-wrapper d-none">
                            <select
                                name="items[${rowIndex}][variation_type]"
                                class="form-control variation-type-select"
                                data-selected-value="${variationType}"
                            >
                                <option value="">{{ translate('Select variation') }}</option>
                            </select>
                        </div>
                    </td>
                    <td>
                        <div class="purchase-stock-label font-weight-semibold">{{ translate('Loading...') }}</div>
                        <small class="text-muted purchase-store-label"></small>
                    </td>
                    <td>
                        <input
                            type="number"
                            min="1"
                            step="1"
                            name="items[${rowIndex}][quantity]"
                            value="${quantity}"
                            class="form-control purchase-quantity"
                            required
                        >
                    </td>
                    <td>
                        <input
                            type="number"
                            min="0"
                            step="0.01"
                            name="items[${rowIndex}][purchase_price]"
                            value="${purchasePrice}"
                            class="form-control purchase-price"
                            required
                        >
                    </td>
                    <td>
                        <input
                            type="text"
                            class="form-control purchase-line-total"
                            value="${purchaseLineTotal(quantity, purchasePrice)}"
                            readonly
                        >
                    </td>
                    <td class="text-center">
                        <button type="button" class="btn btn--danger btn-sm remove-purchase-row">
                            <i class="tio-delete"></i>
                        </button>
                    </td>
                </tr>
            `;

            purchaseItemsBody.append(rowHtml);

            const $row = purchaseItemsBody.find('.purchase-item-row').last();
            initializePurchaseItemSelect($row);
            $row.on('input', '.purchase-quantity, .purchase-price', function () {
                updateRowTotal($row);
            });
            $row.find('.remove-purchase-row').on('click', function () {
                if (purchaseItemsBody.find('.purchase-item-row').length <= 1) {
                    return;
                }
                $row.remove();
                updatePurchaseSummary();
            });

            updateRowTotal($row);
        }

        $(document).ready(function () {
            purchaseItemsBody.empty();

            if (purchaseInitialRows.length > 0) {
                purchaseInitialRows.forEach(function (item) {
                    createPurchaseRow(item || {});
                });
            } else {
                createPurchaseRow();
            }

            purchaseAddRowButton.on('click', function () {
                createPurchaseRow();
            });
        });
    </script>
@endpush
