@extends('layouts.app')

@section('title', __('purchaseRequisition::lang.purchase_orders'))

@section('content')

<!-- Content Header -->
<section class="content-header">
    <h1>@lang('purchaseRequisition::lang.purchase_orders')</h1>
</section>

<!-- Main content -->
<section class="content">
    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary'])

                <div class="table-responsive">
                    <table class="table table-bordered table-striped" id="purchases_table">
                        <thead>
                            <tr>
                                <th>@lang('purchaseRequisition::lang.reference_no')</th>
                                <th>@lang('purchaseRequisition::lang.date')</th>
                                <th>@lang('purchase.supplier')</th>
                                <th>@lang('purchaseRequisition::lang.pr_refs')</th>
                                <th>@lang('sale.status')</th>
                                <th>@lang('purchaseRequisition::lang.total')</th>
                                <th>@lang('purchaseRequisition::lang.additional_expenses')</th>
                                <th>@lang('purchaseRequisition::lang.share_link')</th>
                                <th>@lang('purchaseRequisition::lang.actions')</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($shares as $share)
                            @php
                                $tx = $share->transaction;
                                $statusLabels = [
                                    'ordered'    => 'info',
                                    'pending'    => 'warning',
                                    'received'   => 'success',
                                    'draft'      => 'default',
                                    'in_transit' => 'primary',
                                    'completed'  => 'primary',
                                ];
                                $statusLabel = $statusLabels[$tx->status] ?? 'default';
                                $refs = collect($share->pr_request_ids)->map(fn($id) => $prRefMap[$id] ?? '#' . $id)->implode(', ');
                                $shareUrl = route('pr.purchase.show', $share->share_token);
                                $hasPending = ($pendingCounts[$share->id] ?? 0) > 0;
                                $pendingCount = $pendingCounts[$share->id] ?? 0;
                                $orderCurrency = $orderCurrencies[$share->id] ?? ['id' => null, 'symbol' => 'EGP'];
                                $paidEgp       = $paymentTotals[$share->id]->total_egp ?? 0;
                                $paidOrder     = $paymentTotals[$share->id]->total_order_currency ?? 0;
                                $hasPayments   = $paidEgp > 0;
                                $expenseTotal  = (\Module::has('LandedCost') && \Schema::hasTable('lc_expenses'))
                                    ? \Modules\LandedCost\Entities\LcExpense::forParent('pr_share', $share->id)->sum('base_amount') : 0;
                            @endphp
                            <tr @if($hasPending) style="background-color: #f2dede;" @endif>
                                <td>
                                    <a href="{{ url('/purchases/' . $tx->id . '/edit') }}" target="_blank">
                                        {{ $tx->ref_no }}
                                    </a>
                                </td>
                                <td>{{ \Carbon\Carbon::parse($tx->transaction_date)->format('Y-m-d') }}</td>
                                <td>{{ optional($tx->contact)->name ?: optional($tx->contact)->supplier_business_name ?: '-' }}</td>
                                <td><small>{{ $refs }}</small></td>
                                <td>
                                    <span class="label label-{{ $statusLabel }}">
                                        {{ ucfirst(str_replace('_', ' ', $tx->status)) }}
                                    </span>
                                    @if($hasPending)
                                        <br><span class="label label-danger" style="margin-top:2px; display:inline-block;">
                                            {{ $pendingCount }} @lang('purchaseRequisition::lang.pending_changes')
                                        </span>
                                    @endif
                                </td>
                                <td>
                                    EGP {{ number_format($tx->final_total, 2) }}
                                    @if($hasPayments)
                                        <br><small class="text-success"><i class="fa fa-check-circle"></i>
                                            EGP {{ number_format($paidEgp, 2) }} @lang('purchaseRequisition::lang.paid_label')
                                        </small>
                                    @endif
                                </td>
                                <td>
                                    @if($expenseTotal > 0)
                                        <span class="text-warning"><i class="fa fa-plus-circle"></i>
                                            EGP {{ number_format($expenseTotal, 2) }}
                                        </span>
                                    @else
                                        <span class="text-muted">—</span>
                                    @endif
                                </td>
                                <td>
                                    <div class="input-group input-group-sm" style="width: 260px;">
                                        <input type="text" class="form-control share-url-input"
                                               value="{{ $shareUrl }}" readonly>
                                        <span class="input-group-btn">
                                            <button class="btn btn-default copy-share-btn"
                                                    data-url="{{ $shareUrl }}"
                                                    title="@lang('purchaseRequisition::lang.link_copied')">
                                                <i class="fa fa-copy"></i>
                                            </button>
                                        </span>
                                    </div>
                                </td>
                                <td style="white-space:nowrap;">
                                    <!-- View -->
                                    <a href="{{ $shareUrl }}" target="_blank" class="btn btn-info btn-xs" title="@lang('messages.view')">
                                        <i class="fa fa-eye"></i>
                                    </a>
                                    <!-- Expenses / Landed Cost (handled by the LandedCost module) -->
                                    @if(\Module::has('LandedCost') && \Module::find('LandedCost')->isEnabled())
                                    <button type="button"
                                            class="btn btn-xs lc-expenses-btn"
                                            style="background:#5b7f3f; color:#fff;"
                                            data-lc-base-url="{{ url('landed-cost/pr_share/'.$share->share_token) }}"
                                            title="@lang('purchaseRequisition::lang.additional_expenses')">
                                        <i class="fa fa-truck"></i> @lang('purchaseRequisition::lang.expenses')
                                    </button>
                                    @endif
                                    <!-- Payment -->
                                    <button type="button"
                                            class="btn btn-primary btn-xs btn-payment"
                                            data-token="{{ $share->share_token }}"
                                            data-payments-url="{{ route('pr.purchases.getPayments', $share->share_token) }}"
                                            data-store-url="{{ route('pr.purchases.storePayment', $share->share_token) }}"
                                            data-order-currency-id="{{ $orderCurrency['id'] ?? '' }}"
                                            data-order-currency-symbol="{{ $orderCurrency['symbol'] }}"
                                            data-total-egp="{{ number_format($tx->final_total, 2) }}"
                                            title="@lang('purchaseRequisition::lang.payment')">
                                        <i class="fa fa-money"></i> @lang('purchaseRequisition::lang.payment')
                                    </button>
                                    <!-- Review Changes (only if pending) -->
                                    @if($hasPending)
                                    <button type="button"
                                            class="btn btn-danger btn-xs btn-review-changes"
                                            data-token="{{ $share->share_token }}"
                                            data-changes-url="{{ route('pr.purchases.changes', $share->share_token) }}"
                                            title="@lang('purchaseRequisition::lang.review_changes')">
                                        <i class="fa fa-exclamation-circle"></i> @lang('purchaseRequisition::lang.review_changes')
                                        <span class="badge">{{ $pendingCount }}</span>
                                    </button>
                                    @endif
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                <div style="margin-top: 15px;">
                    <a href="{{ action([\Modules\PurchaseRequisition\Http\Controllers\PrIndexController::class, 'index']) }}"
                       class="btn btn-default">
                        &laquo; @lang('purchaseRequisition::lang.back')
                    </a>
                </div>

            @endcomponent
        </div>
    </div>
</section>

{{-- Expense / Landed Cost modal (provided by the LandedCost module) --}}
@includeIf('landedcost::modal')

<!-- Payment Modal -->
<div class="modal fade" id="payment_modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background:#337ab7; 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-money"></i> @lang('purchaseRequisition::lang.record_payment')</h4>
            </div>
            <div class="modal-body">
                <!-- Order info -->
                <div class="alert alert-info" style="padding:6px 10px; margin-bottom:10px;">
                    <strong>@lang('purchaseRequisition::lang.order_total'):</strong>
                    <span id="pm_total_egp_label"></span>
                </div>

                <!-- Payment form -->
                <form id="payment_form">
                    <div class="row">
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label>@lang('purchaseRequisition::lang.paid_amount') <span class="text-danger">*</span></label>
                                <input type="number" id="pm_paid_amount" class="form-control" step="0.0001" min="0.0001" required>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label>@lang('purchaseRequisition::lang.paid_currency') <span class="text-danger">*</span></label>
                                <select id="pm_paid_currency" class="form-control" required>
                                    <option value="" disabled selected>— @lang('purchaseRequisition::lang.select') —</option>
                                    <option value="egp" data-symbol="EGP">Egyptian Pound (EGP)</option>
                                    @foreach($currencies as $cur)
                                        <option value="{{ $cur->id }}" data-symbol="{{ $cur->symbol }}">{{ $cur->name }} ({{ $cur->symbol }})</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-sm-4" id="pm_rate_egp_row" style="display:none;">
                            <div class="form-group">
                                <label>@lang('purchaseRequisition::lang.rate_to_egp') <span class="text-danger">*</span></label>
                                <input type="number" id="pm_rate_to_egp" class="form-control" step="0.000001" min="0.000001" value="1">
                                <small class="text-muted">1 <span class="pm-paid-sym">?</span> = <span id="pm_rate_egp_val">1</span> EGP</small>
                            </div>
                        </div>
                    </div>
                    <div class="row" id="pm_rate_order_row" style="display:none;">
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label>@lang('purchaseRequisition::lang.rate_to_order_currency') <span class="text-danger">*</span></label>
                                <input type="number" id="pm_rate_to_order" class="form-control" step="0.000001" min="0.000001" value="1">
                                <small class="text-muted">1 <span class="pm-paid-sym">?</span> = <span id="pm_rate_order_val">1</span> <span class="pm-order-sym"></span></small>
                            </div>
                        </div>
                    </div>

                    <!-- Live totals preview -->
                    <div id="pm_totals_preview" class="well well-sm" style="display:none; margin-bottom:10px;">
                        <strong>@lang('purchaseRequisition::lang.payment_totals_preview'):</strong>
                        &nbsp; EGP <strong id="pm_preview_egp">0.00</strong>
                        &nbsp;|&nbsp; <span class="pm-order-sym"></span> <strong id="pm_preview_order">0.00</strong>
                    </div>

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

                    <div class="form-group">
                        <label>@lang('purchaseRequisition::lang.document')</label>
                        <input type="file" id="pm_document" accept="image/*" style="padding:4px 0;">
                        <p class="help-block" style="margin:2px 0 0; font-size:11px;">@lang('purchaseRequisition::lang.image_only') (jpg, png, gif, webp — max 5 MB)</p>
                    </div>

                    <button type="submit" class="btn btn-primary" id="pm_submit_btn">
                        <i class="fa fa-save"></i> @lang('purchaseRequisition::lang.save')
                    </button>
                    <button type="button" class="btn btn-default" id="pm_cancel_edit" style="display:none; margin-left:6px;">
                        <i class="fas fa-times" style="font-size:inherit;"></i> @lang('purchaseRequisition::lang.cancel')
                    </button>
                </form>

                <hr>

                <!-- Payment history -->
                <h5><strong>@lang('purchaseRequisition::lang.payment_history')</strong></h5>
                <div id="pm_history_body">
                    <p class="text-center"><i class="fa fa-spinner fa-spin"></i></p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">@lang('purchaseRequisition::lang.close')</button>
            </div>
        </div>
    </div>
</div>

<!-- Review Changes Modal -->
<div class="modal fade" id="changes_review_modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background:#d9534f; 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">@lang('purchaseRequisition::lang.review_changes')</h4>
            </div>
            <div class="modal-body" id="changes_review_body">
                <p class="text-center"><i class="fa fa-spinner fa-spin fa-2x"></i></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">@lang('purchaseRequisition::lang.close')</button>
            </div>
        </div>
    </div>
</div>

@endsection

@section('javascript')
<script>
$(document).ready(function() {
    $('#purchases_table').DataTable({
        order: [[1, 'desc']],
        pageLength: 25,
        columnDefs: [{ orderable: false, targets: [6, 7] }]
    });

    // Copy share link to clipboard
    $(document).on('click', '.copy-share-btn', function() {
        var url = $(this).data('url');
        if (navigator.clipboard) {
            navigator.clipboard.writeText(url).then(function() {
                toastr.success('@lang("purchaseRequisition::lang.link_copied")');
            });
        } else {
            var $input = $(this).closest('.input-group').find('.share-url-input');
            $input.select();
            document.execCommand('copy');
            toastr.success('@lang("purchaseRequisition::lang.link_copied")');
        }
    });

    // Review Changes button
    $(document).on('click', '.btn-review-changes', function() {
        var changesUrl = $(this).data('changes-url');
        var token = $(this).data('token');
        $('#changes_review_body').html('<p class="text-center"><i class="fa fa-spinner fa-spin fa-2x"></i></p>');
        $('#changes_review_modal').modal('show');

        $.ajax({
            url: changesUrl,
            method: 'GET',
            success: function(res) {
                renderChangesModal(res.changes, token);
            },
            error: function() {
                $('#changes_review_body').html('<p class="text-danger">Error loading changes.</p>');
            }
        });
    });

    function renderChangesModal(changes, token) {
        if (!changes || changes.length === 0) {
            $('#changes_review_body').html('<p class="text-muted">@lang("purchaseRequisition::lang.no_pending_changes")</p>');
            return;
        }

        var html = '';

        changes.forEach(function(c) {
            var isPending = c.status === 'pending';
            var statusBadge = isPending
                ? '<span class="label label-warning">@lang("purchaseRequisition::lang.pending")</span>'
                : (c.status === 'approved'
                    ? '<span class="label label-success">@lang("purchaseRequisition::lang.approved")</span>'
                    : '<span class="label label-danger">@lang("purchaseRequisition::lang.rejected")</span>');

            var sym = c.currency_symbol || 'EGP';

            // Diff table rows
            var diffRows =
                '<tr>' +
                    '<td><strong>@lang("purchaseRequisition::lang.order_qty")</strong></td>' +
                    '<td style="background:#fff8f8;">' + parseFloat(c.original_qty).toFixed(2) + '</td>' +
                    '<td style="background:#f8fff8;"><strong>' + parseFloat(c.requested_qty).toFixed(2) + '</strong></td>' +
                '</tr>' +
                '<tr>' +
                    '<td><strong>@lang("purchaseRequisition::lang.supplier_price") (' + sym + ')</strong></td>' +
                    '<td style="background:#fff8f8;">' + sym + ' ' + parseFloat(c.original_supplier_price).toFixed(4) + '</td>' +
                    '<td style="background:#f8fff8;"><strong>' + sym + ' ' + parseFloat(c.requested_supplier_price).toFixed(4) + '</strong></td>' +
                '</tr>' +
                '<tr>' +
                    '<td><strong>@lang("purchaseRequisition::lang.converted_price_egp")</strong></td>' +
                    '<td style="background:#fff8f8;">EGP ' + parseFloat(c.original_egp_price).toFixed(4) + '</td>' +
                    '<td style="background:#f8fff8;"><strong>EGP ' + parseFloat(c.requested_egp_price).toFixed(4) + '</strong></td>' +
                '</tr>';

            // Admin override inputs (only for pending)
            var adminSection = '';
            if (isPending) {
                adminSection =
                    '<div class="row" style="margin-top:8px;">' +
                        '<div class="col-xs-4">' +
                            '<label class="control-label" style="font-size:11px;">@lang("purchaseRequisition::lang.admin_qty")</label>' +
                            '<input type="number" class="form-control input-sm admin-qty-input" step="0.01" value="' + parseFloat(c.requested_qty).toFixed(2) + '">' +
                        '</div>' +
                        '<div class="col-xs-4">' +
                            '<label class="control-label" style="font-size:11px;">@lang("purchaseRequisition::lang.admin_price") (' + sym + ')</label>' +
                            '<input type="number" class="form-control input-sm admin-price-input" step="0.0001" value="' + parseFloat(c.requested_supplier_price).toFixed(4) + '">' +
                        '</div>' +
                        '<div class="col-xs-4">' +
                            '<label class="control-label" style="font-size:11px;">@lang("purchaseRequisition::lang.admin_note_label")</label>' +
                            '<textarea class="form-control input-sm admin-note-input" rows="2" placeholder="@lang("purchaseRequisition::lang.admin_note_label")"></textarea>' +
                        '</div>' +
                    '</div>' +
                    '<div style="margin-top:8px;">' +
                        '<button class="btn btn-success btn-xs btn-approve-change" ' +
                            'data-id="' + c.id + '" data-approve-url="' + c.approve_url + '" data-reject-url="' + c.reject_url + '" data-delete-url="' + c.delete_url + '">' +
                            '<i class="fa fa-check"></i> @lang("purchaseRequisition::lang.approve")</button> ' +
                        '<button class="btn btn-warning btn-xs btn-reject-change" ' +
                            'data-id="' + c.id + '" data-reject-url="' + c.reject_url + '">' +
                            '<i class="fa fa-times" style="font-size:inherit;"></i> @lang("purchaseRequisition::lang.reject")</button> ' +
                        '<button class="btn btn-danger btn-xs btn-delete-line" ' +
                            'data-id="' + c.id + '" data-delete-url="' + c.delete_url + '">' +
                            '<i class="fa fa-trash"></i> @lang("purchaseRequisition::lang.delete_line")</button>' +
                    '</div>';
            }

            html +=
                '<div id="change-row-' + c.id + '" class="panel ' + (isPending ? 'panel-warning' : (c.status === 'approved' ? 'panel-success' : 'panel-danger')) + '" style="margin-bottom:10px;">' +
                    '<div class="panel-heading" style="padding:6px 10px;">' +
                        '<strong>' + c.product_name + '</strong>' +
                        ' <small class="text-muted">' + c.sku + '</small>' +
                        ' &nbsp; ' + statusBadge +
                        (c.supplier_note ? ' &nbsp; <em class="text-muted" style="font-size:12px;"><i class="fa fa-comment-o"></i> ' + c.supplier_note + '</em>' : '') +
                    '</div>' +
                    '<div class="panel-body" style="padding:8px 10px;">' +
                        '<table class="table table-bordered table-condensed" style="margin-bottom:' + (isPending ? '0' : '0') + ';">' +
                            '<thead>' +
                                '<tr>' +
                                    '<th style="width:35%;">@lang("purchaseRequisition::lang.field")</th>' +
                                    '<th style="width:32.5%; background:#fff8f8;">@lang("purchaseRequisition::lang.before")</th>' +
                                    '<th style="width:32.5%; background:#f8fff8;">@lang("purchaseRequisition::lang.after")</th>' +
                                '</tr>' +
                            '</thead>' +
                            '<tbody>' + diffRows + '</tbody>' +
                        '</table>' +
                        adminSection +
                    '</div>' +
                '</div>';
        });

        $('#changes_review_body').html(html);
    }

    // Approve
    $(document).on('click', '.btn-approve-change', function() {
        var $btn = $(this);
        var changeId = $btn.data('id');
        var url = $btn.data('approve-url');
        var $row = $('#change-row-' + changeId);
        var adminQty = $row.find('.admin-qty-input').val();
        var adminPrice = $row.find('.admin-price-input').val();
        var adminNote = $row.find('.admin-note-input').val();

        if (!confirm('@lang("purchaseRequisition::lang.approve_selected_products")')) return;

        $.ajax({
            url: url,
            method: 'POST',
            data: { admin_qty: adminQty, admin_price: adminPrice, admin_note: adminNote,
                    _token: $('meta[name="csrf-token"]').attr('content') },
            success: function(res) {
                if (res.success) {
                    toastr.success(res.message);
                    $row.removeClass('panel-warning').addClass('panel-success');
                    $row.find('.panel-heading .label').replaceWith('<span class="label label-success">@lang("purchaseRequisition::lang.approved")</span>');
                    $row.find('.btn-approve-change, .btn-reject-change, .btn-delete-line').closest('div').remove();
                    $row.find('.admin-qty-input, .admin-price-input, .admin-note-input').prop('disabled', true);
                }
            },
            error: function() { toastr.error('Error'); }
        });
    });

    // Reject
    $(document).on('click', '.btn-reject-change', function() {
        var $btn = $(this);
        var changeId = $btn.data('id');
        var url = $btn.data('reject-url');
        var $row = $('#change-row-' + changeId);
        var adminNote = $row.find('.admin-note-input').val();

        if (!confirm('@lang("purchaseRequisition::lang.are_you_sure")')) return;

        $.ajax({
            url: url,
            method: 'POST',
            data: { admin_note: adminNote, _token: $('meta[name="csrf-token"]').attr('content') },
            success: function(res) {
                if (res.success) {
                    toastr.warning(res.message);
                    $row.removeClass('panel-warning').addClass('panel-danger');
                    $row.find('.panel-heading .label').replaceWith('<span class="label label-danger">@lang("purchaseRequisition::lang.rejected")</span>');
                    $row.find('.btn-approve-change, .btn-reject-change, .btn-delete-line').closest('div').remove();
                    $row.find('.admin-qty-input, .admin-price-input, .admin-note-input').prop('disabled', true);
                }
            },
            error: function() { toastr.error('Error'); }
        });
    });

    // Delete line
    $(document).on('click', '.btn-delete-line', function() {
        var $btn = $(this);
        var changeId = $btn.data('id');
        var url = $btn.data('delete-url');
        var $row = $('#change-row-' + changeId);

        if (!confirm('@lang("purchaseRequisition::lang.are_you_sure")')) return;

        $.ajax({
            url: url,
            method: 'DELETE',
            data: { _token: $('meta[name="csrf-token"]').attr('content') },
            success: function(res) {
                if (res.success) {
                    toastr.success(res.message);
                    $row.remove();
                }
            },
            error: function() { toastr.error('Error'); }
        });
    });

    // ─── Payment Modal ─────────────────────────────────────────────────────

    var pmStoreUrl = '';
    var pmOrderCurrencyId = '';
    var pmOrderCurrencySymbol = 'EGP';

    function pmUpdatePreview() {
        var amount      = parseFloat($('#pm_paid_amount').val()) || 0;
        var selectedId  = $('#pm_paid_currency').val();
        var rateEgpVisible   = $('#pm_rate_egp_row').is(':visible');
        var rateOrderVisible = $('#pm_rate_order_row').is(':visible');
        var rateEgp = rateEgpVisible ? (parseFloat($('#pm_rate_to_egp').val()) || 1) : 1;
        var rateOrd = rateOrderVisible ? (parseFloat($('#pm_rate_to_order').val()) || 1) : 1;

        $('#pm_preview_egp').text((amount * rateEgp).toFixed(2));
        $('#pm_preview_order').text((amount * rateOrd).toFixed(2));
        // Show totals preview only when at least one rate conversion is active and amount is entered
        var showPreview = amount > 0 && (rateEgpVisible || rateOrderVisible);
        $('#pm_totals_preview').toggle(showPreview);
        $('#pm_rate_egp_val').text(rateEgp);
        $('#pm_rate_order_val').text(rateOrd);
    }

    function pmRenderHistory(payments) {
        if (!payments || payments.length === 0) {
            $('#pm_history_body').html('<p class="text-muted">@lang("purchaseRequisition::lang.no_payments")</p>');
            return;
        }
        var html = '<table class="table table-bordered table-condensed" style="font-size:12px;">' +
            '<thead><tr>' +
            '<th>@lang("purchaseRequisition::lang.date")</th>' +
            '<th>@lang("purchaseRequisition::lang.paid_by")</th>' +
            '<th>@lang("purchaseRequisition::lang.paid_amount")</th>' +
            '<th>EGP</th>' +
            '<th>@lang("purchaseRequisition::lang.order_total")</th>' +
            '<th>@lang("purchaseRequisition::lang.notes")</th>' +
            '<th>@lang("purchaseRequisition::lang.document")</th>' +
            '<th>@lang("purchaseRequisition::lang.received")</th>' +
            '<th></th>' +
            '</tr></thead><tbody>';
        payments.forEach(function(p) {
            var receivedBadge = p.received
                ? '<span class="label label-success">@lang("purchaseRequisition::lang.received")</span>'
                : '<span class="label label-default">-</span>';
            var docHtml = p.document_url
                ? '<a href="' + p.document_url + '" target="_blank"><i class="fa fa-file-image-o"></i></a>'
                : '-';
            var editBtn = '<button type="button" class="btn btn-xs btn-default btn-pm-edit" ' +
                'data-id="' + p.id + '" ' +
                'data-paid-amount="' + p.paid_amount + '" ' +
                'data-paid-currency-id="' + (p.paid_currency_id || 'egp') + '" ' +
                'data-rate-to-egp="' + p.rate_to_egp + '" ' +
                'data-rate-to-order="' + p.rate_to_order_currency + '" ' +
                'data-notes="' + (p.notes || '').replace(/"/g, '&quot;') + '" ' +
                'title="@lang("purchaseRequisition::lang.edit_payment")">' +
                '<i class="fas fa-pencil-alt"></i></button>';
            html += '<tr data-payment-id="' + p.id + '">' +
                '<td>' + p.created_at + '</td>' +
                '<td>' + p.created_by + '</td>' +
                '<td>' + p.paid_currency_symbol + ' ' + parseFloat(p.paid_amount).toFixed(2) + '</td>' +
                '<td>EGP ' + parseFloat(p.egp_amount).toFixed(2) + '</td>' +
                '<td>' + p.order_currency_symbol + ' ' + parseFloat(p.order_currency_amount).toFixed(2) + '</td>' +
                '<td>' + (p.notes || '-') + '</td>' +
                '<td>' + docHtml + '</td>' +
                '<td>' + receivedBadge + '</td>' +
                '<td>' + editBtn + '</td>' +
                '</tr>';
        });
        html += '</tbody></table>';
        $('#pm_history_body').html(html);
    }

    function pmLoadHistory(paymentsUrl) {
        $('#pm_history_body').html('<p class="text-center"><i class="fa fa-spinner fa-spin"></i></p>');
        $.ajax({
            url: paymentsUrl,
            method: 'GET',
            success: function(res) { pmRenderHistory(res.payments); },
            error: function() { $('#pm_history_body').html('<p class="text-danger">Error loading history.</p>'); }
        });
    }

    var pmEditingId = null; // null = add mode, number = edit mode

    function pmResetForm() {
        pmEditingId = null;
        $('#payment_form')[0].reset();
        $('#pm_rate_egp_row, #pm_rate_order_row, #pm_totals_preview').hide();
        $('#pm_rate_to_egp').val(1);
        $('#pm_rate_to_order').val(1);
        $('#pm_submit_btn').prop('disabled', false).html('<i class="fa fa-save"></i> @lang("purchaseRequisition::lang.save")');
        $('#pm_cancel_edit').hide();
        $('.modal-title').html('<i class="fa fa-money"></i> @lang("purchaseRequisition::lang.record_payment")');
    }

    $(document).on('click', '.btn-payment', function() {
        var $btn = $(this);
        pmStoreUrl         = $btn.data('store-url');
        pmOrderCurrencyId  = String($btn.data('order-currency-id') || '');
        pmOrderCurrencySymbol = $btn.data('order-currency-symbol') || 'EGP';

        pmResetForm();
        $('.pm-order-sym').text(pmOrderCurrencySymbol);
        $('#pm_total_egp_label').text('EGP ' + $btn.data('total-egp'));

        pmLoadHistory($btn.data('payments-url'));
        $('#payment_modal').modal('show');
    });

    // Edit payment: populate form with existing values
    $(document).on('click', '.btn-pm-edit', function() {
        var $btn        = $(this);
        var id          = $btn.data('id');
        var paidAmount  = $btn.data('paid-amount');
        var currId      = String($btn.data('paid-currency-id'));
        var rateEgp     = $btn.data('rate-to-egp');
        var rateOrd     = $btn.data('rate-to-order');
        var notes       = $btn.data('notes');

        pmEditingId = id;

        // Populate form fields
        $('#pm_paid_amount').val(paidAmount);
        $('#pm_paid_currency').val(currId).trigger('change');
        if ($('#pm_rate_egp_row').is(':visible')) { $('#pm_rate_to_egp').val(rateEgp); }
        if ($('#pm_rate_order_row').is(':visible')) { $('#pm_rate_to_order').val(rateOrd); }
        $('#pm_notes').val(notes);

        // Update modal heading and show cancel button
        $('.modal-title').html('<i class="fas fa-pencil-alt"></i> @lang("purchaseRequisition::lang.edit_payment") #' + id);
        $('#pm_cancel_edit').show();
        $('#pm_submit_btn').prop('disabled', false).html('<i class="fa fa-save"></i> @lang("purchaseRequisition::lang.save")');

        pmUpdatePreview();
        // Scroll to form top
        $('#payment_modal .modal-body').animate({ scrollTop: 0 }, 200);
    });

    $(document).on('click', '#pm_cancel_edit', function() {
        pmResetForm();
        $('#pm_paid_currency').val('').trigger('change');
    });

    $('#pm_paid_currency').on('change', function() {
        var selectedId  = $(this).val();
        var selectedSym = $(this).find(':selected').data('symbol') || 'EGP';
        $('.pm-paid-sym').text(selectedSym);

        // Rate to EGP: show if paid ≠ EGP
        var showEgpRate = selectedId !== 'egp';
        $('#pm_rate_egp_row').toggle(showEgpRate);
        $('#pm_rate_to_egp').prop('required', showEgpRate);

        // Rate to order currency: show if paid ≠ order currency AND order currency exists (not EGP)
        var showOrderRate = (pmOrderCurrencyId !== '' && pmOrderCurrencyId !== 'egp') &&
                            (selectedId !== String(pmOrderCurrencyId));
        $('#pm_rate_order_row').toggle(showOrderRate);
        $('#pm_rate_to_order').prop('required', showOrderRate);

        pmUpdatePreview();
    });

    $('#pm_paid_amount, #pm_rate_to_egp, #pm_rate_to_order').on('input', pmUpdatePreview);

    $('#payment_form').on('submit', function(e) {
        e.preventDefault();
        var $btn = $('#pm_submit_btn');

        var paidCurrId = $('#pm_paid_currency').val();
        if (!paidCurrId) {
            toastr.warning('@lang("purchaseRequisition::lang.select_currency")');
            return;
        }

        var rateToEgp = $('#pm_rate_egp_row').is(':visible') ? (parseFloat($('#pm_rate_to_egp').val()) || 1) : 1;
        var rateToOrd = $('#pm_rate_order_row').is(':visible') ? (parseFloat($('#pm_rate_to_order').val()) || 1) : 1;

        var isEdit = pmEditingId !== null;
        var url    = isEdit ? (pmStoreUrl + '/' + pmEditingId) : pmStoreUrl;

        var fd = new FormData();
        fd.append('_token',                 $('meta[name="csrf-token"]').attr('content'));
        fd.append('paid_amount',            $('#pm_paid_amount').val());
        fd.append('paid_currency_id',       paidCurrId);
        fd.append('rate_to_egp',            rateToEgp);
        fd.append('order_currency_id',      pmOrderCurrencyId || '');
        fd.append('rate_to_order_currency', rateToOrd);
        fd.append('notes',                  $('#pm_notes').val());
        var docFile = $('#pm_document')[0].files[0];
        if (docFile) { fd.append('document', docFile); }

        $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');

        $.ajax({
            url:         url,
            method:      'POST',
            data:        fd,
            processData: false,
            contentType: false,
            success: function(res) {
                if (res.success) {
                    toastr.success(res.message);
                    var p       = res.payment;
                    var docHtml = p.document_url
                        ? '<a href="' + p.document_url + '" target="_blank"><i class="fa fa-file-image-o"></i></a>'
                        : '-';
                    var receivedBadge = p.received
                        ? '<span class="label label-success">@lang("purchaseRequisition::lang.received")</span>'
                        : '<span class="label label-default">-</span>';
                    var editBtn = '<button type="button" class="btn btn-xs btn-default btn-pm-edit" ' +
                        'data-id="' + p.id + '" ' +
                        'data-paid-amount="' + p.paid_amount + '" ' +
                        'data-paid-currency-id="' + (p.paid_currency_id || 'egp') + '" ' +
                        'data-rate-to-egp="' + p.rate_to_egp + '" ' +
                        'data-rate-to-order="' + p.rate_to_order_currency + '" ' +
                        'data-notes="' + (p.notes || '').replace(/"/g, '&quot;') + '" ' +
                        'title="@lang("purchaseRequisition::lang.edit_payment")">' +
                        '<i class="fas fa-pencil-alt"></i></button>';
                    var newRow = '<tr data-payment-id="' + p.id + '">' +
                        '<td>' + p.created_at + '</td>' +
                        '<td>' + p.created_by + '</td>' +
                        '<td>' + p.paid_currency_symbol + ' ' + parseFloat(p.paid_amount).toFixed(2) + '</td>' +
                        '<td>EGP ' + parseFloat(p.egp_amount).toFixed(2) + '</td>' +
                        '<td>' + p.order_currency_symbol + ' ' + parseFloat(p.order_currency_amount).toFixed(2) + '</td>' +
                        '<td>' + (p.notes || '-') + '</td>' +
                        '<td>' + docHtml + '</td>' +
                        '<td>' + receivedBadge + '</td>' +
                        '<td>' + editBtn + '</td>' +
                        '</tr>';

                    if (isEdit) {
                        // Replace the existing row
                        $('#pm_history_body table tbody tr[data-payment-id="' + p.id + '"]').replaceWith(newRow);
                    } else {
                        var $tbody = $('#pm_history_body table tbody');
                        if ($tbody.length) { $tbody.prepend(newRow); }
                        else              { pmRenderHistory([p]); }
                    }

                    pmResetForm();
                    $('#pm_paid_currency').val('');
                }
                $btn.prop('disabled', false).html('<i class="fa fa-save"></i> @lang("purchaseRequisition::lang.save")');
            },
            error: function(xhr) {
                var msg = 'Error saving payment.';
                if (xhr.responseJSON && xhr.responseJSON.message) { msg = xhr.responseJSON.message; }
                toastr.error(msg);
                $btn.prop('disabled', false).html('<i class="fa fa-save"></i> @lang("purchaseRequisition::lang.save")');
            }
        });
    });

});

</script>
@endsection
