{{--
    Landed Cost / Purchase Expenses — self-contained modal + JS.

    Include ONCE on a persistent page (e.g. a purchase / purchase-order / PR-purchases
    index). Trigger it from any element with class "lc-expenses-btn" carrying a
    data-lc-base-url attribute, e.g.:

        <a href="#" class="lc-expenses-btn" data-lc-base-url="{{ url('landed-cost/purchase/'.$id) }}">…</a>

    The base URL is the route prefix (landed-cost/{parentType}/{parentRef}); the modal
    derives /expenses, /expenses/preview, /expenses/{id} from it. Currency options and
    the base-currency symbol are loaded dynamically from the server response, so the same
    markup serves PR shares (EGP / pr_currencies) and core purchases (business currency).
--}}

{{-- Add / Edit Expense Modal --}}
<div class="modal fade" id="lc_expense_modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background:#5b7f3f; color:#fff; border-radius:4px 4px 0 0;">
                <button type="button" class="close" data-dismiss="modal" style="color:#fff; opacity:1;"><span>&times;</span></button>
                <h4 class="modal-title" id="lc_expense_modal_title">
                    <i class="fa fa-truck"></i> @lang('landedcost::lang.add_expense')
                </h4>
            </div>
            <div class="modal-body">
                <form id="lc_expense_form">
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>@lang('landedcost::lang.expense_name') <span class="text-danger">*</span></label>
                                <input type="text" id="lc_exp_name" class="form-control" maxlength="100" required
                                       placeholder="@lang('landedcost::lang.eg_sea_freight')">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>@lang('landedcost::lang.expense_type') <span class="text-danger">*</span></label>
                                <select id="lc_exp_type" class="form-control" required>
                                    <option value="shipping">@lang('landedcost::lang.type_shipping')</option>
                                    <option value="customs">@lang('landedcost::lang.type_customs')</option>
                                    <option value="insurance">@lang('landedcost::lang.type_insurance')</option>
                                    <option value="handling">@lang('landedcost::lang.type_handling')</option>
                                    <option value="freight">@lang('landedcost::lang.type_freight')</option>
                                    <option value="other">@lang('landedcost::lang.type_other')</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label>@lang('landedcost::lang.amount') <span class="text-danger">*</span></label>
                                <input type="number" id="lc_exp_amount" class="form-control" step="0.0001" min="0.0001" required>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label>@lang('landedcost::lang.currency')</label>
                                <select id="lc_exp_currency" class="form-control"></select>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label>@lang('landedcost::lang.rate_to_base') <span class="text-danger">*</span></label>
                                <input type="number" id="lc_exp_rate" class="form-control" step="0.000001" min="0.000001" value="1">
                                <small class="text-muted">
                                    @lang('landedcost::lang.equivalent'):
                                    <span class="lc-base-symbol"></span> <strong id="lc_exp_base_preview">0.00</strong>
                                </small>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>@lang('landedcost::lang.distribution_method') <span class="text-danger">*</span></label>
                        <div>
                            <label class="radio-inline">
                                <input type="radio" name="lc_exp_method" value="equal_value" checked>
                                <strong>@lang('landedcost::lang.method_equal_value')</strong>
                                <small class="text-muted">— @lang('landedcost::lang.method_equal_value_hint')</small>
                            </label>
                        </div>
                        <div>
                            <label class="radio-inline">
                                <input type="radio" name="lc_exp_method" value="equal_qty">
                                <strong>@lang('landedcost::lang.method_equal_qty')</strong>
                                <small class="text-muted">— @lang('landedcost::lang.method_equal_qty_hint')</small>
                            </label>
                        </div>
                        <div>
                            <label class="radio-inline">
                                <input type="radio" name="lc_exp_method" value="equal_lines">
                                <strong>@lang('landedcost::lang.method_equal_lines')</strong>
                                <small class="text-muted">— @lang('landedcost::lang.method_equal_lines_hint')</small>
                            </label>
                        </div>
                        <div>
                            <label class="radio-inline">
                                <input type="radio" name="lc_exp_method" value="custom">
                                <strong>@lang('landedcost::lang.method_custom')</strong>
                                <small class="text-muted">— @lang('landedcost::lang.method_custom_hint')</small>
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>@lang('landedcost::lang.notes')</label>
                        <textarea id="lc_exp_notes" class="form-control" rows="2" maxlength="2000"></textarea>
                    </div>

                    {{-- Distribution Preview / Custom Ratios --}}
                    <div id="lc_exp_preview_section" style="display:none; margin-top:10px;">
                        <hr style="margin:8px 0;">
                        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
                            <strong>@lang('landedcost::lang.distribution_preview')</strong>
                            <button type="button" id="lc_exp_refresh_preview" class="btn btn-xs btn-default">
                                <i class="fa fa-refresh"></i> @lang('landedcost::lang.refresh_preview')
                            </button>
                        </div>
                        <div id="lc_exp_ratio_alert" class="alert alert-danger" style="display:none; padding:6px 10px; font-size:12px;">
                            <i class="fa fa-exclamation-triangle"></i>
                            @lang('landedcost::lang.ratios_must_sum_100')
                            <strong>(<span id="lc_exp_ratio_sum">0</span>%)</strong>
                        </div>
                        <div id="lc_exp_preview_body">
                            <p class="text-center text-muted"><i class="fa fa-spinner fa-spin"></i></p>
                        </div>
                    </div>

                    <div style="margin-top:14px;">
                        <button type="submit" class="btn btn-success" id="lc_exp_submit_btn">
                            <i class="fa fa-save"></i> @lang('landedcost::lang.save')
                        </button>
                        <button type="button" class="btn btn-default" data-dismiss="modal" style="margin-left:6px;">
                            @lang('landedcost::lang.cancel')
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

{{-- Expenses List Modal --}}
<div class="modal fade" id="lc_expenses_list_modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background:#5b7f3f; color:#fff; border-radius:4px 4px 0 0;">
                <button type="button" class="close" data-dismiss="modal" style="color:#fff; opacity:1;"><span>&times;</span></button>
                <h4 class="modal-title">
                    <i class="fa fa-truck"></i> @lang('landedcost::lang.additional_expenses')
                </h4>
            </div>
            <div class="modal-body">
                <div class="alert alert-info" style="padding:6px 10px; font-size:12px; margin-bottom:10px;">
                    <strong>@lang('landedcost::lang.total_expenses'):</strong>
                    <span class="lc-base-symbol"></span> <strong id="lc_exp_total_base_label">0.00</strong>
                </div>
                <div id="lc_exp_list_body">
                    <p class="text-center"><i class="fa fa-spinner fa-spin fa-2x"></i></p>
                </div>
                <div style="margin-top:12px;">
                    <button type="button" id="lc_btn_add_new_expense" class="btn btn-success btn-sm">
                        <i class="fa fa-plus"></i> @lang('landedcost::lang.add_expense')
                    </button>
                </div>

                {{-- Apply landed cost to the real purchase cost / roll it back --}}
                <div id="lc_apply_area" style="margin-top:12px; border-top:1px solid #eee; padding-top:10px; display:none;">
                    <span id="lc_applied_badge" class="label label-success" style="display:none; font-size:12px;">
                        <i class="fa fa-check"></i> @lang('landedcost::lang.applied')
                    </span>
                    <button type="button" id="lc_btn_apply" class="btn btn-primary btn-sm" style="display:none;">
                        <i class="fa fa-check-circle"></i> @lang('landedcost::lang.apply_to_cost')
                    </button>
                    <button type="button" id="lc_btn_rollback" class="btn btn-warning btn-sm" style="display:none; margin-left:6px;">
                        <i class="fa fa-undo"></i> @lang('landedcost::lang.roll_back')
                    </button>
                    <p class="text-muted" style="font-size:11px; margin-top:6px; margin-bottom:0;">
                        <i class="fa fa-info-circle"></i> @lang('landedcost::lang.apply_hint')
                    </p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">@lang('landedcost::lang.close')</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
(function () {
    // This partial renders in the page body, before jQuery loads in the footer.
    // Wait for jQuery to be available before binding any handlers.
    function lcBoot() {
        if (typeof window.jQuery === 'undefined') { return setTimeout(lcBoot, 50); }
        if (window.__lcInit) { return; }   // guard against double include
        window.__lcInit = true;

        var $ = window.jQuery;
    var lcBaseUrl       = '';
    var lcEditingId     = null;       // null = add, number = edit
    var lcBaseSymbol    = '';
    var lcCurrencies    = [];
    var lcAppliedWarning = false;

    function lcToken()   { return $('meta[name="csrf-token"]').attr('content'); }
    function lcListUrl() { return lcBaseUrl + '/expenses'; }
    function lcStoreUrl(){ return lcBaseUrl + '/expenses'; }
    function lcPrevUrl() { return lcBaseUrl + '/expenses/preview'; }

    var L = {
        error_loading:     @json(__('landedcost::lang.error_loading')),
        no_expenses_yet:   @json(__('landedcost::lang.no_expenses_yet')),
        no_lines_found:    @json(__('landedcost::lang.no_lines_found')),
        ratios_must_100:   @json(__('landedcost::lang.ratios_must_sum_100')),
        confirm_delete:    @json(__('landedcost::lang.confirm_delete_expense')),
        select_method:     @json(__('landedcost::lang.select_distribution_method')),
        save:              @json(__('landedcost::lang.save')),
        edit_expense:      @json(__('landedcost::lang.edit_expense')),
        add_expense:       @json(__('landedcost::lang.add_expense')),
        col_name:          @json(__('landedcost::lang.expense_name')),
        col_type:          @json(__('landedcost::lang.expense_type')),
        col_amount:        @json(__('landedcost::lang.amount')),
        col_equivalent:    @json(__('landedcost::lang.equivalent')),
        col_method:        @json(__('landedcost::lang.distribution_method')),
        col_product:       @json(__('landedcost::lang.product')),
        col_order_qty:     @json(__('landedcost::lang.order_qty')),
        col_ratio:         @json(__('landedcost::lang.distribution_ratio')),
        col_allocated:     @json(__('landedcost::lang.allocated')),
        col_base_price:    @json(__('landedcost::lang.base_price')),
        col_landed:        @json(__('landedcost::lang.landed_cost')),
        col_total:         @json(__('landedcost::lang.total')),
        apply_confirm:      @json(__('landedcost::lang.apply_confirm')),
        apply_confirm_sold: @json(__('landedcost::lang.apply_confirm_sold')),
        rollback_confirm:   @json(__('landedcost::lang.rollback_confirm'))
    };

    // Open the expenses list modal
    $(document).on('click', '.lc-expenses-btn', function (e) {
        e.preventDefault();
        lcBaseUrl = $(this).data('lc-base-url');
        lcLoadList();
        $('#lc_expenses_list_modal').modal('show');
    });

    function lcApplyBaseSymbol() {
        $('.lc-base-symbol').text(lcBaseSymbol);
    }

    function lcPopulateCurrencies(selectedId) {
        var $sel = $('#lc_exp_currency');
        var html = '<option value="" data-rate="1" data-symbol="' + lcBaseSymbol + '">' + lcBaseSymbol + ' (base)</option>';
        lcCurrencies.forEach(function (c) {
            html += '<option value="' + c.id + '" data-rate="' + c.rate + '" data-symbol="' + c.symbol + '">' + c.name + '</option>';
        });
        $sel.html(html).val(selectedId || '');
    }

    function lcLoadList() {
        $('#lc_exp_list_body').html('<p class="text-center"><i class="fa fa-spinner fa-spin fa-2x"></i></p>');
        $.ajax({
            url: lcListUrl(), method: 'GET',
            success: function (res) {
                lcBaseSymbol = res.base_symbol || '';
                lcCurrencies = res.currencies || [];
                lcAppliedWarning = !!res.applied_warning;
                lcApplyBaseSymbol();
                $('#lc_exp_total_base_label').text(parseFloat(res.total_base || 0).toFixed(2));
                lcRenderList(res.expenses || []);
                lcRenderApplyState(!!res.applied, !!res.can_apply, (res.expenses || []).length);
            },
            error: function () {
                $('#lc_exp_list_body').html('<p class="text-danger">' + L.error_loading + '</p>');
            }
        });
    }

    // Toggle the Apply / Roll back controls based on server state.
    function lcRenderApplyState(applied, canApply, expenseCount) {
        if (!canApply) { $('#lc_apply_area').hide(); return; }
        $('#lc_apply_area').show();
        $('#lc_applied_badge').toggle(applied);
        $('#lc_btn_rollback').toggle(applied);
        $('#lc_btn_apply').toggle(!applied && expenseCount > 0);
    }

    $(document).on('click', '#lc_btn_apply', function () {
        if (!confirm(lcAppliedWarning ? L.apply_confirm_sold : L.apply_confirm)) return;
        var $b = $(this).prop('disabled', true);
        $.ajax({
            url: lcBaseUrl + '/apply', method: 'POST', data: { _token: lcToken() },
            success: function (res) {
                if (res.success) { toastr.success(res.message); lcLoadList(); }
                $b.prop('disabled', false);
            },
            error: function (xhr) {
                toastr.error((xhr.responseJSON && xhr.responseJSON.message) || L.error_loading);
                $b.prop('disabled', false);
            }
        });
    });

    $(document).on('click', '#lc_btn_rollback', function () {
        if (!confirm(L.rollback_confirm)) return;
        var $b = $(this).prop('disabled', true);
        $.ajax({
            url: lcBaseUrl + '/rollback', method: 'POST', data: { _token: lcToken() },
            success: function (res) {
                if (res.success) { toastr.success(res.message); lcLoadList(); }
                $b.prop('disabled', false);
            },
            error: function (xhr) {
                toastr.error((xhr.responseJSON && xhr.responseJSON.message) || L.error_loading);
                $b.prop('disabled', false);
            }
        });
    });

    function lcRenderList(expenses) {
        if (!expenses.length) {
            $('#lc_exp_list_body').html('<p class="text-muted">' + L.no_expenses_yet + '</p>');
            return;
        }
        var html = '<table class="table table-bordered table-condensed" style="font-size:12px;">' +
            '<thead><tr>' +
            '<th>' + L.col_name + '</th>' +
            '<th>' + L.col_type + '</th>' +
            '<th>' + L.col_amount + '</th>' +
            '<th>' + lcBaseSymbol + ' ' + L.col_equivalent + '</th>' +
            '<th>' + L.col_method + '</th>' +
            '<th></th>' +
            '</tr></thead><tbody>';
        expenses.forEach(function (e) {
            html += '<tr>' +
                '<td><strong>' + e.name + '</strong>' + (e.notes ? '<br><small class="text-muted">' + e.notes + '</small>' : '') + '</td>' +
                '<td><span class="label label-default">' + e.expense_type_label + '</span></td>' +
                '<td>' + e.currency_symbol + ' ' + parseFloat(e.amount).toFixed(2) + '</td>' +
                '<td>' + lcBaseSymbol + ' ' + parseFloat(e.base_amount).toFixed(2) + '</td>' +
                '<td><small>' + e.distribution_label + '</small></td>' +
                '<td style="white-space:nowrap;">' +
                    '<button type="button" class="btn btn-xs btn-default lc-exp-edit" data-id="' + e.id + '"><i class="fa fa-pencil"></i></button> ' +
                    '<button type="button" class="btn btn-xs btn-danger lc-exp-delete" data-id="' + e.id + '" data-name="' + e.name + '"><i class="fa fa-trash"></i></button>' +
                '</td>' +
            '</tr>';
        });
        html += '</tbody></table>';
        $('#lc_exp_list_body').html(html);
    }

    // Open Add form
    $(document).on('click', '#lc_btn_add_new_expense', function () {
        lcEditingId = null;
        lcResetForm();
        lcPopulateCurrencies('');
        $('#lc_expense_modal_title').html('<i class="fa fa-truck"></i> ' + L.add_expense);
        $('#lc_expenses_list_modal').modal('hide');
        setTimeout(function () { $('#lc_expense_modal').modal('show'); }, 300);
    });

    // Open Edit form
    $(document).on('click', '.lc-exp-edit', function () {
        var id = $(this).data('id');
        lcEditingId = id;
        $.ajax({
            url: lcListUrl(), method: 'GET',
            success: function (res) {
                var e = (res.expenses || []).find(function (x) { return x.id == id; });
                if (!e) return;
                lcPopulateForm(e);
                $('#lc_expense_modal_title').html('<i class="fa fa-pencil"></i> ' + L.edit_expense + ' #' + id);
                $('#lc_expenses_list_modal').modal('hide');
                setTimeout(function () { $('#lc_expense_modal').modal('show'); }, 300);
            }
        });
    });

    function lcPopulateForm(e) {
        $('#lc_exp_name').val(e.name);
        $('#lc_exp_type').val(e.expense_type);
        $('#lc_exp_amount').val(e.amount);
        lcPopulateCurrencies(e.currency_id || '');
        $('#lc_exp_rate').val(e.rate_to_base);
        $('input[name="lc_exp_method"][value="' + e.distribution_method + '"]').prop('checked', true).trigger('change');
        $('#lc_exp_notes').val(e.notes || '');
        lcUpdateBasePreview();
    }

    // Delete expense
    $(document).on('click', '.lc-exp-delete', function () {
        var id   = $(this).data('id');
        var name = $(this).data('name');
        if (!confirm(L.confirm_delete + ' "' + name + '"?')) return;

        $.ajax({
            url: lcStoreUrl() + '/' + id, method: 'POST',
            data: { _method: 'DELETE', _token: lcToken() },
            success: function (res) {
                if (res.success) {
                    toastr.success(res.message);
                    lcLoadList();
                }
            },
            error: function () { toastr.error(L.error_loading); }
        });
    });

    // Currency change → auto-fill rate
    $(document).on('change', '#lc_exp_currency', function () {
        var rate = parseFloat($(this).find(':selected').data('rate') || 1);
        $('#lc_exp_rate').val(rate);
        lcUpdateBasePreview();
    });

    $(document).on('input', '#lc_exp_amount, #lc_exp_rate', function () {
        lcUpdateBasePreview();
        if ($('#lc_exp_preview_section').is(':visible') && $(this).val()) lcFetchPreview();
    });

    function lcUpdateBasePreview() {
        var amt  = parseFloat($('#lc_exp_amount').val()) || 0;
        var rate = parseFloat($('#lc_exp_rate').val()) || 1;
        $('#lc_exp_base_preview').text((amt * rate).toFixed(2));
    }

    // Method change → show/hide preview section
    $(document).on('change', 'input[name="lc_exp_method"]', function () {
        $('#lc_exp_preview_section').show();
        if ($('#lc_exp_amount').val()) lcFetchPreview();
    });

    $(document).on('click', '#lc_exp_refresh_preview', lcFetchPreview);

    function lcFetchPreview() {
        var method = $('input[name="lc_exp_method"]:checked').val();
        var amount = $('#lc_exp_amount').val();
        var rate   = $('#lc_exp_rate').val();
        if (!amount || !rate || !method) return;

        var postData = {
            _token: lcToken(),
            amount: amount,
            rate_to_base: rate,
            distribution_method: method
        };

        if (method === 'custom') {
            var $inputs = $('#lc_exp_preview_body .lc-custom-ratio-input');
            if ($inputs.length > 0) {
                var sum = 0;
                $inputs.each(function () {
                    postData['ratios[' + $(this).data('line-id') + ']'] = parseFloat($(this).val()) || 0;
                    sum += parseFloat($(this).val()) || 0;
                });
                if (Math.abs(sum - 100) > 0.01) {
                    $('#lc_exp_ratio_alert').show();
                    $('#lc_exp_ratio_sum').text(sum.toFixed(2));
                    return;
                }
                $('#lc_exp_ratio_alert').hide();
            }
        }

        $('#lc_exp_preview_body').html('<p class="text-center"><i class="fa fa-spinner fa-spin"></i></p>');
        $.ajax({
            url: lcPrevUrl(), method: 'POST', data: postData,
            success: function (res) {
                var renderMethod = (res.is_custom_seed || method === 'custom') ? 'custom' : method;
                lcRenderPreview(res.rows || [], renderMethod);
            },
            error: function () {
                $('#lc_exp_preview_body').html('<p class="text-danger">' + L.error_loading + '</p>');
            }
        });
    }

    function lcRenderPreview(rows, method) {
        if (!rows.length) {
            $('#lc_exp_preview_body').html('<p class="text-muted">' + L.no_lines_found + '</p>');
            return;
        }
        var isCustom = method === 'custom';
        var html = '<table class="table table-bordered table-condensed" style="font-size:11px;">' +
            '<thead><tr>' +
            '<th>' + L.col_product + '</th>' +
            '<th>' + L.col_order_qty + '</th>' +
            (isCustom ? '<th>% <span class="text-danger">*</span></th>' : '<th>' + L.col_ratio + ' %</th>') +
            '<th>' + lcBaseSymbol + ' ' + L.col_allocated + '</th>' +
            '<th>' + L.col_base_price + '</th>' +
            '<th>' + L.col_landed + '</th>' +
            '</tr></thead><tbody>';

        rows.forEach(function (r) {
            var sym = r.currency_symbol || lcBaseSymbol;
            var ratioCell = isCustom
                ? '<input type="number" class="form-control input-sm lc-custom-ratio-input" style="width:70px;" min="0" max="100" step="0.01" data-line-id="' + r.purchase_line_id + '" value="' + r.distribution_ratio + '">'
                : parseFloat(r.distribution_ratio).toFixed(2) + '%';
            html += '<tr>' +
                '<td>' + r.product_name + '</td>' +
                '<td>' + parseFloat(r.order_qty).toFixed(2) + '</td>' +
                '<td>' + ratioCell + '</td>' +
                '<td>' + lcBaseSymbol + ' ' + parseFloat(r.allocated_base).toFixed(2) + '</td>' +
                '<td>' + sym + ' ' + parseFloat(r.base_price).toFixed(4) + '</td>' +
                '<td style="background:#f0fff0;"><strong>' + sym + ' ' + parseFloat(r.landed_cost).toFixed(4) + '</strong>' +
                    '<br><small class="text-muted">' + lcBaseSymbol + ' ' + parseFloat(r.landed_cost_base).toFixed(4) + '</small>' +
                '</td>' +
            '</tr>';
        });
        html += '</tbody></table>';
        if (isCustom) {
            html += '<div style="font-size:12px; margin-top:4px;">' + L.col_total + ' %: <strong id="lc_exp_ratio_sum_display">0</strong></div>';
        }
        $('#lc_exp_preview_body').html(html);
        if (isCustom) { lcUpdateRatioSum(); }
    }

    $(document).on('input', '.lc-custom-ratio-input', lcUpdateRatioSum);

    function lcUpdateRatioSum() {
        var sum = 0;
        $('.lc-custom-ratio-input').each(function () { sum += parseFloat($(this).val()) || 0; });
        var diff = Math.abs(sum - 100);
        $('#lc_exp_ratio_sum_display').text(sum.toFixed(2)).css('color', diff > 0.01 ? 'red' : 'green');
        $('#lc_exp_ratio_alert').toggle(diff > 0.01);
        $('#lc_exp_ratio_sum').text(sum.toFixed(2));
    }

    function lcResetForm() {
        document.getElementById('lc_expense_form').reset();
        $('#lc_exp_preview_section').hide();
        $('#lc_exp_preview_body').html('');
        $('#lc_exp_ratio_alert').hide();
        $('input[name="lc_exp_method"][value="equal_value"]').prop('checked', true);
        lcUpdateBasePreview();
    }

    // Submit (add or edit)
    $(document).on('submit', '#lc_expense_form', function (e) {
        e.preventDefault();
        var method = $('input[name="lc_exp_method"]:checked').val();
        if (!method) { toastr.warning(L.select_method); return; }

        if (method === 'custom') {
            var sum = 0;
            $('.lc-custom-ratio-input').each(function () { sum += parseFloat($(this).val()) || 0; });
            if (Math.abs(sum - 100) > 0.01) { toastr.warning(L.ratios_must_100); return; }
        }

        var isEdit = lcEditingId !== null;
        var url    = isEdit ? (lcStoreUrl() + '/' + lcEditingId) : lcStoreUrl();
        var $btn   = $('#lc_exp_submit_btn');
        $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');

        var postData = {
            _token:              lcToken(),
            name:                $('#lc_exp_name').val(),
            expense_type:        $('#lc_exp_type').val(),
            amount:              $('#lc_exp_amount').val(),
            currency_id:         $('#lc_exp_currency').val() || '',
            rate_to_base:        $('#lc_exp_rate').val(),
            distribution_method: method,
            notes:               $('#lc_exp_notes').val()
        };
        if (isEdit) { postData['_method'] = 'POST'; }
        if (method === 'custom') {
            $('.lc-custom-ratio-input').each(function () {
                postData['ratios[' + $(this).data('line-id') + ']'] = $(this).val();
            });
        }

        $.ajax({
            url: url, method: 'POST', data: postData,
            success: function (res) {
                if (res.success) {
                    toastr.success(res.message);
                    $('#lc_expense_modal').modal('hide');
                    setTimeout(function () {
                        lcLoadList();
                        $('#lc_expenses_list_modal').modal('show');
                    }, 300);
                }
                $btn.prop('disabled', false).html('<i class="fa fa-save"></i> ' + L.save);
            },
            error: function (xhr) {
                var msg = (xhr.responseJSON && xhr.responseJSON.message) ? xhr.responseJSON.message : L.error_loading;
                toastr.error(msg);
                $btn.prop('disabled', false).html('<i class="fa fa-save"></i> ' + L.save);
            }
        });
    });

    $(document).on('shown.bs.modal', '#lc_expense_modal', function () {
        if ($('#lc_exp_amount').val()) lcFetchPreview();
        else $('#lc_exp_preview_section').show();
    });
    }   // end lcBoot

    lcBoot();
})();
</script>
