<!DOCTYPE html>
<html lang="{{ request('lang', 'en') }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>@lang('purchaseRequisition::lang.purchase_order') - {{ $transaction->ref_no }}</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <style>
        body { padding: 20px; background: #f4f4f4; }
        .product-image { max-width: 80px; cursor: pointer; }
        .fullscreen-modal { display: none; position: fixed; z-index: 9999; padding-top: 50px; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.9); }
        .fullscreen-modal img { margin: auto; display: block; max-width: 90%; max-height: 90%; }
        .close-fullscreen { position: absolute; top: 15px; right: 35px; color: #f1f1f1; font-size: 40px; font-weight: bold; cursor: pointer; }
        .extra-part-cell { max-width: 120px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .extra-part-trigger { cursor: pointer; }
        .extra-part-trigger:hover { text-decoration: underline; }
        tfoot td { font-weight: bold; background-color: #f5f5f5; }
        .landed-cost-cell { background-color: #f0fff0; }
        .expenses-section { margin-top: 20px; background: #fff; padding: 15px; border: 1px solid #5b7f3f; border-radius: 4px; }
        .expenses-section h5 { color: #5b7f3f; }
        .lang-switcher { float: right; margin-top: -2px; }
        .lang-switcher a { color: #fff; opacity: 0.75; font-size: 12px; margin-left: 6px; border: 1px solid rgba(255,255,255,0.5); border-radius: 3px; padding: 2px 7px; text-decoration: none; }
        .lang-switcher a.active, .lang-switcher a:hover { opacity: 1; background: rgba(255,255,255,0.2); }
        .row-change-form { display: none; background: #fff9e6; border: 1px solid #f0ad4e; border-radius: 4px; padding: 10px; margin-top: 6px; }
        .row-change-form input[type=number]::-webkit-inner-spin-button,
        .row-change-form input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
        .row-change-form input[type=number] { -moz-appearance: textfield; }
        .row-note-cell textarea { width: 100%; min-height: 40px; resize: vertical; font-size: 12px; }
        .btn-history { background: none; border: none; padding: 2px 5px; cursor: not-allowed; color: #ccc; }
        .btn-history.has-changes { cursor: pointer; color: #337ab7; }
        .btn-history.has-pending { color: #d9534f; }
        .change-status-pending { background-color: #f2dede !important; }
        .order-notes-section { margin-top: 20px; background: #fff; padding: 15px; border: 1px solid #ddd; border-radius: 4px; }
        .attached-images img { max-height: 80px; margin: 4px; cursor: pointer; border: 1px solid #ddd; border-radius: 3px; }
    </style>
</head>
<body>
@php
    $currentLang = request('lang', 'en');
    app()->setLocale($currentLang);
    $langQuery = '?lang=' . $currentLang;
    $saveNotesUrl = route('pr.purchase.saveNotes', $share->share_token);
    $requestChangeUrl = route('pr.purchase.requestChange', $share->share_token);

    // Load expenses and landed costs for this share (from the LandedCost module)
    $shareExpenses   = (\Module::has('LandedCost') && \Schema::hasTable('lc_expenses'))
        ? \Modules\LandedCost\Entities\LcExpense::forParent('pr_share', $share->id)->orderBy('created_at')->get()
        : collect();
    $totalExpenseEgp = $shareExpenses->sum('base_amount');

    // Load landed unit costs indexed by purchase_line_id
    $supplierId       = $transaction->contact_id;
    $prProductIdsShow = $transaction->purchase_lines->pluck('purchase_requisition_line_id')->filter()->unique();
    $landedCostMap    = \Schema::hasTable('pr_supplier_products') ? \Modules\PurchaseRequisition\Entities\PrSupplierProduct::whereIn('pr_product_id', $prProductIdsShow)
        ->where('approved', true)
        ->whereHas('supplierResponse', function ($q) use ($supplierId) {
            $q->where('supplier_id', $supplierId)->where('status', 'approved');
        })
        ->get()
        ->keyBy('pr_product_id') : collect();
@endphp

    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-primary">
                    <div class="panel-heading">
                        <h3 class="panel-title">
                            @lang('purchaseRequisition::lang.purchase_order') &mdash; {{ $transaction->ref_no }}
                            <span class="lang-switcher">
                                <a href="?lang=en" class="{{ $currentLang === 'en' ? 'active' : '' }}">EN</a>
                                <a href="?lang=zh" class="{{ $currentLang === 'zh' ? 'active' : '' }}">中文</a>
                            </span>
                        </h3>
                    </div>
                    <div class="panel-body">

                        <!-- Header info -->
                        <div class="row" style="margin-bottom: 15px;">
                            <div class="col-md-6">
                                <p><strong>@lang('purchaseRequisition::lang.reference_no'):</strong> {{ $transaction->ref_no }}</p>
                                <p><strong>@lang('purchaseRequisition::lang.date'):</strong> {{ \Carbon\Carbon::parse($transaction->transaction_date)->format('Y-m-d') }}</p>
                                <p><strong>@lang('purchase.supplier'):</strong>
                                    {{ optional($transaction->contact)->name ?: optional($transaction->contact)->supplier_business_name ?: '-' }}
                                </p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>@lang('purchaseRequisition::lang.status'):</strong>
                                    @php
                                        $statusLabelMap = ['ordered'=>'info','pending'=>'warning','received'=>'success','draft'=>'default','in_transit'=>'primary','completed'=>'primary'];
                                        $statusLabel = $statusLabelMap[$transaction->status] ?? 'default';
                                    @endphp
                                    <span class="label label-{{ $statusLabel }}">
                                        {{ ucfirst(str_replace('_', ' ', $transaction->status)) }}
                                    </span>
                                </p>
                                <p><strong>@lang('purchaseRequisition::lang.pr_refs'):</strong>
                                    {{ implode(', ', $prRefNos) }}
                                </p>
                            </div>
                        </div>

                        <!-- Products table -->
                        <h4>@lang('purchaseRequisition::lang.products')</h4>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>@lang('purchaseRequisition::lang.product')</th>
                                        <th>@lang('purchaseRequisition::lang.sku')</th>
                                        <th style="max-width:120px;">@lang('purchaseRequisition::lang.extra_part_number')</th>
                                        <th>@lang('purchaseRequisition::lang.image')</th>
                                        <th>@lang('purchaseRequisition::lang.notes')</th>
                                        <th>@lang('purchaseRequisition::lang.order_qty')</th>
                                        <th>@lang('purchaseRequisition::lang.supplier_price')</th>
                                        <th>@lang('purchaseRequisition::lang.total')</th>
                                        @if($totalExpenseEgp > 0)
                                        <th class="landed-cost-cell" title="@lang('purchaseRequisition::lang.landed_cost_hint')">
                                            @lang('purchaseRequisition::lang.landed_unit_cost')
                                            <i class="fa fa-info-circle text-muted"></i>
                                        </th>
                                        @endif
                                        <th>@lang('purchaseRequisition::lang.supplier_notes')</th>
                                        <th style="white-space:nowrap;">@lang('purchaseRequisition::lang.row_note') / @lang('purchaseRequisition::lang.actions')</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @php $grandTotal = 0; $rowNo = 0; $lastSymbol = 'EGP'; @endphp
                                    @foreach($items as $item)
                                    @php
                                        $rowNo++;
                                        $line       = $item['line'];
                                        $prProduct  = $item['pr_product'];
                                        $sp         = $item['supplier_product'];

                                        $product    = $prProduct ? $prProduct->product  : $line->product;
                                        $variation  = $prProduct ? $prProduct->variation : $line->variations;

                                        $varName = ($product && $product->type == 'variable' && $variation
                                                    && !in_array(strtoupper(trim($variation->name ?? '')), ['DUMMY', '']))
                                                   ? ' ' . $variation->name : '';
                                        $productName = $product ? $product->name . $varName : '-';
                                        $sku         = $variation ? ($variation->sub_sku ?: ($product->sku ?? '-')) : ($product->sku ?? '-');
                                        $extraPart   = $product ? ($product->product_custom_field4 ?? '-') : '-';
                                        $extraPartClass = ($extraPart !== '-' && strlen($extraPart) > 15) ? 'extra-part-trigger' : '';

                                        $orderQty     = $line->quantity;
                                        $currency     = $sp ? optional($sp->supplierResponse)->currency : null;
                                        $symbol       = $currency ? $currency->symbol : 'EGP';
                                        $supplierPrice = $sp ? $sp->supplier_price : $line->purchase_price;
                                        $lineTotal     = $orderQty * $supplierPrice;
                                        $grandTotal   += $lineTotal;
                                        $lastSymbol    = $symbol;
                                        $supplierNotes = $sp ? ($sp->supplier_notes ?? '-') : '-';
                                        $rowNote       = ($share->row_notes[$line->id] ?? ($share->row_notes[(string)$line->id] ?? ''));

                                        // Landed cost for this line
                                        $prProductIdForLine = $line->purchase_requisition_line_id;
                                        $lcSp = $prProductIdForLine ? ($landedCostMap[$prProductIdForLine] ?? null) : null;
                                        $landedCost    = $lcSp ? (float) $lcSp->landed_unit_cost     : 0;
                                        $landedCostEgp = $lcSp ? (float) $lcSp->landed_unit_cost_egp : 0;
                                        $hasLanded = $totalExpenseEgp > 0;

                                        $lineChanges      = $changes[$line->id] ?? ($changes[(string)$line->id] ?? collect());
                                        $hasPendingChange = $lineChanges->where('status', 'pending')->isNotEmpty();
                                        $hasAnyChange     = $lineChanges->isNotEmpty();

                                        // If an approved change exists, override displayed price
                                        $approvedChange = $lineChanges->sortByDesc('id')->firstWhere('status', 'approved');
                                        if ($approvedChange) {
                                            $grandTotal   -= $lineTotal; // remove original contribution
                                            $supplierPrice = (float) $approvedChange->requested_price;
                                            $lineTotal     = $line->quantity * $supplierPrice;
                                            $grandTotal   += $lineTotal;
                                        }

                                        // Enrich changes for JS with currency symbol and original supplier price
                                        $conversionRate  = $currency ? (float)$currency->conversion_rate_to_egp : 1;
                                        $origSpPrice     = $sp ? (float)$sp->supplier_price : 0;
                                        $changesForJs    = $lineChanges->values()->map(function($c) use ($symbol, $origSpPrice) {
                                            $arr = $c->toArray();
                                            $arr['original_supplier_price'] = $origSpPrice;
                                            $arr['currency_symbol']         = $symbol;
                                            $arr['created_at']              = $c->created_at ? $c->created_at->format('Y-m-d H:i') : null;
                                            return $arr;
                                        })->toArray();
                                    @endphp
                                    <tr class="{{ $hasPendingChange ? 'change-status-pending' : '' }}" data-line-id="{{ $line->id }}">
                                        <td>{{ $rowNo }}</td>
                                        <td>{{ $productName }}</td>
                                        <td>{{ $sku }}</td>
                                        <td class="extra-part-cell {{ $extraPartClass }}"
                                            title="{{ $extraPart }}"
                                            data-full-text="{{ $extraPart }}">{{ $extraPart }}</td>
                                        <td>
                                            @if($product && !empty($product->image))
                                                <img src="{{ $product->image_url }}" class="product-image" alt="Product">
                                            @else
                                                -
                                            @endif
                                        </td>
                                        <td>{{ $prProduct ? ($prProduct->notes ?? '-') : '-' }}</td>
                                        <td>
                                            <strong>{{ number_format($orderQty, 2) }}</strong>
                                            @if($hasPendingChange)
                                                @php $pendingChange = $lineChanges->firstWhere('status','pending'); @endphp
                                                <br><small class="text-danger">→ {{ number_format($pendingChange->requested_qty, 2) }}</small>
                                            @endif
                                        </td>
                                        <td>
                                            {{ $symbol }} {{ number_format($supplierPrice, 4) }}
                                            @if($hasPendingChange)
                                                <br><small class="text-danger">→ {{ $symbol }} {{ number_format($pendingChange->requested_price, 4) }}</small>
                                            @endif
                                        </td>
                                        <td>{{ $symbol }} {{ number_format($lineTotal, 2) }}</td>
                                        @if($hasLanded)
                                        <td class="landed-cost-cell">
                                            @if($landedCost > 0)
                                                <strong>{{ $symbol }} {{ number_format($landedCost, 4) }}</strong>
                                                <br><small class="text-muted">EGP {{ number_format($landedCostEgp, 4) }}</small>
                                            @else
                                                <span class="text-muted">—</span>
                                            @endif
                                        </td>
                                        @endif
                                        <td>{{ $supplierNotes }}</td>
                                        <td>
                                            <!-- Row note textarea -->
                                            <textarea class="row-note-input form-control input-sm"
                                                      data-line-id="{{ $line->id }}"
                                                      placeholder="@lang('purchaseRequisition::lang.row_note')"
                                                      rows="2">{{ $rowNote }}</textarea>

                                            <!-- Action buttons -->
                                            <div style="margin-top:5px; white-space:nowrap;">
                                                <!-- Request Change button -->
                                                <button type="button"
                                                        class="btn btn-warning btn-xs btn-request-change"
                                                        data-line-id="{{ $line->id }}"
                                                        data-qty="{{ $orderQty }}"
                                                        data-price="{{ $supplierPrice }}">
                                                    <i class="fa fa-edit"></i> @lang('purchaseRequisition::lang.request_change')
                                                </button>
                                                <!-- History icon -->
                                                <button type="button"
                                                        class="btn-history {{ $hasAnyChange ? 'has-changes' : '' }} {{ $hasPendingChange ? 'has-pending' : '' }}"
                                                        {{ $hasAnyChange ? '' : 'disabled' }}
                                                        data-line-id="{{ $line->id }}"
                                                        data-changes='@json($changesForJs)'
                                                        title="@lang('purchaseRequisition::lang.change_history')">
                                                    <i class="fa fa-history fa-lg"></i>
                                                </button>
                                            </div>

                                            <!-- Inline change request form -->
                                            <div class="row-change-form" id="change-form-{{ $line->id }}">
                                                <div class="alert alert-warning alert-sm" style="padding:6px; margin-bottom:8px; font-size:12px;">
                                                    <i class="fa fa-exclamation-triangle"></i>
                                                    @lang('purchaseRequisition::lang.change_request_warning')
                                                </div>
                                                <div class="form-group" style="margin-bottom:6px;">
                                                    <label style="font-size:12px;">@lang('purchaseRequisition::lang.new_qty')</label>
                                                    <input type="number" class="form-control input-sm change-qty" min="0" step="0.01"
                                                           value="{{ $orderQty }}">
                                                </div>
                                                <div class="form-group" style="margin-bottom:6px;">
                                                    <label style="font-size:12px;">@lang('purchaseRequisition::lang.new_price')</label>
                                                    <input type="number" class="form-control input-sm change-price" min="0" step="0.0001"
                                                           value="{{ $supplierPrice }}">
                                                </div>
                                                <div class="form-group" style="margin-bottom:6px;">
                                                    <label style="font-size:12px;">@lang('purchaseRequisition::lang.supplier_notes')</label>
                                                    <textarea class="form-control input-sm change-note" rows="2"></textarea>
                                                </div>
                                                <button type="button" class="btn btn-danger btn-xs btn-submit-change" data-line-id="{{ $line->id }}">
                                                    @lang('purchaseRequisition::lang.submit_change')
                                                </button>
                                                <button type="button" class="btn btn-default btn-xs btn-cancel-change" data-line-id="{{ $line->id }}">
                                                    @lang('purchaseRequisition::lang.cancel')
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="8" class="text-right">@lang('purchaseRequisition::lang.products_total'):</td>
                                        <td><strong>{{ $lastSymbol }} {{ number_format($grandTotal, 2) }}</strong></td>
                                        @if($totalExpenseEgp > 0)
                                        <td class="landed-cost-cell text-right">
                                            <small>@lang('purchaseRequisition::lang.total_expenses'):<br>
                                            <strong>EGP {{ number_format($totalExpenseEgp, 2) }}</strong></small>
                                        </td>
                                        @endif
                                        <td colspan="2"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        <!-- Additional Expenses Summary (read-only on public view) -->
                        @if($shareExpenses->isNotEmpty())
                        <div class="expenses-section">
                            <h5><strong><i class="fa fa-truck"></i> @lang('purchaseRequisition::lang.additional_expenses')</strong></h5>
                            <table class="table table-bordered table-condensed" style="font-size:12px;">
                                <thead>
                                    <tr>
                                        <th>@lang('purchaseRequisition::lang.expense_name')</th>
                                        <th>@lang('purchaseRequisition::lang.expense_type')</th>
                                        <th>@lang('purchaseRequisition::lang.amount')</th>
                                        <th>@lang('purchaseRequisition::lang.egp_equivalent')</th>
                                        <th>@lang('purchaseRequisition::lang.distribution_method')</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($shareExpenses as $exp)
                                    @php
                                        $expTypes   = \Modules\LandedCost\Entities\LcExpense::TYPES;
                                        $expMethods = \Modules\LandedCost\Entities\LcExpense::METHODS;
                                        $expCur     = $exp->currency_id ? \Modules\PurchaseRequisition\Entities\PrCurrency::find($exp->currency_id) : null;
                                        $expSym     = $expCur ? $expCur->symbol : 'EGP';
                                    @endphp
                                    <tr>
                                        <td>
                                            <strong>{{ $exp->name }}</strong>
                                            @if($exp->notes)<br><small class="text-muted">{{ $exp->notes }}</small>@endif
                                        </td>
                                        <td><span class="label label-default">{{ $expTypes[$exp->expense_type] ?? $exp->expense_type }}</span></td>
                                        <td>{{ $expSym }} {{ number_format($exp->amount, 2) }}</td>
                                        <td>EGP {{ number_format($exp->base_amount, 2) }}</td>
                                        <td><small>{{ $expMethods[$exp->distribution_method] ?? $exp->distribution_method }}</small></td>
                                    </tr>
                                    @endforeach
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="3" class="text-right">@lang('purchaseRequisition::lang.total_expenses'):</td>
                                        <td><strong>EGP {{ number_format($totalExpenseEgp, 2) }}</strong></td>
                                        <td></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                        @endif

                        <!-- Order-level notes + images -->
                        <div class="order-notes-section">
                            <h5><strong>@lang('purchaseRequisition::lang.order_note')</strong></h5>
                            <textarea id="order_note_input" class="form-control" rows="3"
                                      placeholder="@lang('purchaseRequisition::lang.order_note')">{{ $share->supplier_order_note }}</textarea>

                            <h5 style="margin-top:12px;"><strong>@lang('purchaseRequisition::lang.upload_images')</strong></h5>
                            <input type="file" id="image_upload_input" multiple accept="image/*" class="form-control">

                            @if(!empty($share->images))
                            <div class="attached-images" style="margin-top:10px;">
                                <p><strong>@lang('purchaseRequisition::lang.attached_images'):</strong></p>
                                @foreach($share->images as $imgPath)
                                <img src="{{ Storage::disk('public')->url($imgPath) }}" class="product-image" alt="Uploaded image">
                                @endforeach
                            </div>
                            @endif

                            <div style="margin-top:10px;">
                                <button type="button" id="save_notes_btn" class="btn btn-primary">
                                    <i class="fa fa-save"></i> @lang('purchaseRequisition::lang.save_notes')
                                </button>
                            </div>
                        </div>

                        @if($payments->isNotEmpty())
                        <div style="margin-top:20px; background:#fff; padding:15px; border:1px solid #ddd; border-radius:4px;">
                            <h5><strong>@lang('purchaseRequisition::lang.payments')</strong></h5>
                            @foreach($payments as $payment)
                            @php
                                $markReceivedUrl = route('pr.purchase.markReceived', [$share->share_token, $payment->id]);
                                $pmOrderSym = $payment->orderCurrency ? $payment->orderCurrency->symbol : 'EGP';
                            @endphp
                            <div class="payment-entry" style="margin-bottom:10px; padding:10px; border:1px solid #eee; border-radius:4px;" data-id="{{ $payment->id }}">
                                <div style="display:flex; justify-content:space-between; align-items:flex-start; flex-wrap:wrap; gap:8px;">
                                    <div>
                                        <strong style="font-size:15px;">{{ $pmOrderSym }} {{ number_format($payment->order_currency_amount, 2) }}</strong>
                                        @if($payment->notes)
                                            <br><small class="text-muted">{{ $payment->notes }}</small>
                                        @endif
                                    </div>
                                    <label style="margin:0; font-weight:normal; cursor:pointer; white-space:nowrap;">
                                        <input type="checkbox" class="payment-received-cb"
                                               data-id="{{ $payment->id }}"
                                               data-url="{{ $markReceivedUrl }}"
                                               {{ $payment->received ? 'checked' : '' }}>
                                        @lang('purchaseRequisition::lang.received')
                                    </label>
                                </div>
                                <div class="received-note-section" style="{{ $payment->received ? '' : 'display:none;' }} margin-top:8px;">
                                    <textarea class="form-control input-sm received-note-input" rows="2"
                                        placeholder="@lang('purchaseRequisition::lang.received_note')">{{ $payment->received_note }}</textarea>
                                    <button type="button" class="btn btn-xs btn-default btn-save-received" style="margin-top:4px;"
                                            data-url="{{ $markReceivedUrl }}">
                                        <i class="fa fa-save"></i> @lang('purchaseRequisition::lang.save')
                                    </button>
                                </div>
                            </div>
                            @endforeach
                        </div>
                        @endif

                        <div class="text-center" style="margin-top: 25px;">
                            <p class="text-muted">
                                <small><i class="glyphicon glyphicon-lock"></i> @lang('purchaseRequisition::lang.purchase_read_only_notice')</small>
                            </p>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Fullscreen Image Modal -->
    <div id="fullscreen_modal" class="fullscreen-modal">
        <span class="close-fullscreen">&times;</span>
        <img id="fullscreen_image" src="">
    </div>

    <!-- Extra Part Number Modal -->
    <div class="modal fade" id="extra_part_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                    <h4 class="modal-title">@lang('purchaseRequisition::lang.extra_part_number')</h4>
                </div>
                <div class="modal-body">
                    <p id="extra_part_content" style="word-wrap: break-word;"></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>

    <!-- Change History Modal -->
    <div class="modal fade" id="change_history_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                    <h4 class="modal-title">@lang('purchaseRequisition::lang.change_history')</h4>
                </div>
                <div class="modal-body" id="change_history_body">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">@lang('purchaseRequisition::lang.close')</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <script>
    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });

    $(document).ready(function() {

        // Image fullscreen
        $(document).on('click', '.product-image', function() {
            $('#fullscreen_image').attr('src', $(this).attr('src'));
            $('#fullscreen_modal').show();
        });
        $('.close-fullscreen').click(function() { $('#fullscreen_modal').hide(); });

        // Extra part modal
        $(document).on('click', '.extra-part-trigger', function() {
            var fullText = $(this).data('full-text');
            if (fullText && fullText !== '-') {
                $('#extra_part_content').text(fullText);
                $('#extra_part_modal').modal('show');
            }
        });

        // Request Change button — show inline form
        $(document).on('click', '.btn-request-change', function() {
            var lineId = $(this).data('line-id');
            $('#change-form-' + lineId).slideToggle(150);
        });

        // Cancel change form
        $(document).on('click', '.btn-cancel-change', function() {
            var lineId = $(this).data('line-id');
            $('#change-form-' + lineId).slideUp(150);
        });

        // Submit change request
        $(document).on('click', '.btn-submit-change', function() {
            var lineId = $(this).data('line-id');
            var $form  = $('#change-form-' + lineId);
            var qty    = $form.find('.change-qty').val();
            var price  = $form.find('.change-price').val();
            var note   = $form.find('.change-note').val();
            var $btn   = $(this);

            $btn.prop('disabled', true).text('@lang("purchaseRequisition::lang.submitting")');

            $.ajax({
                url: '{{ $requestChangeUrl }}',
                method: 'POST',
                data: {
                    purchase_line_id: lineId,
                    requested_qty: qty,
                    requested_price: price,
                    supplier_note: note
                },
                success: function(res) {
                    if (res.success) {
                        // Turn row red
                        $('[data-line-id="' + lineId + '"]').addClass('change-status-pending');
                        // Update history button with returned change data so it becomes clickable
                        var $historyBtn = $('[data-line-id="' + lineId + '"].btn-history, [data-line-id="' + lineId + '"] .btn-history').last();
                        var existing = $historyBtn.data('changes') || [];
                        // replace existing pending entry or append
                        var found = false;
                        existing = existing.map(function(c) { if (c.status === 'pending') { found = true; return res.change; } return c; });
                        if (!found && res.change) existing.push(res.change);
                        $historyBtn.data('changes', existing).removeAttr('disabled').removeClass('has-changes has-pending').addClass('has-changes has-pending');
                        $form.slideUp(150);
                        alert(res.message);
                    }
                    $btn.prop('disabled', false).text('@lang("purchaseRequisition::lang.submit_change")');
                },
                error: function(xhr) {
                    var msg = (xhr.responseJSON && xhr.responseJSON.message) ? xhr.responseJSON.message : 'Error';
                    alert(msg);
                    $btn.prop('disabled', false).text('@lang("purchaseRequisition::lang.submit_change")');
                }
            });
        });

        // History icon click — show all change entries
        $(document).on('click', '.btn-history.has-changes', function() {
            var allChanges = $(this).data('changes');
            if (!allChanges || allChanges.length === 0) { return; }

            var html = '';
            allChanges.forEach(function(c) {
                var statusBadge = c.status === 'pending'
                    ? '<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 || '';
                var origPrice  = parseFloat(c.original_supplier_price  || c.original_price  || 0).toFixed(4);
                var reqPrice   = parseFloat(c.requested_supplier_price || c.requested_price || 0).toFixed(4);

                html += '<div style="border:1px solid #ddd; border-radius:4px; margin-bottom:10px;">' +
                    '<div style="background:#f5f5f5; padding:6px 12px; border-bottom:1px solid #ddd;">' +
                        statusBadge +
                        (c.created_at ? ' <small class="text-muted" style="margin-left:8px;">' + c.created_at + '</small>' : '') +
                    '</div>' +
                    '<div style="padding:10px;">' +
                    '<table class="table table-bordered table-condensed" style="margin-bottom:4px;">' +
                    '<thead><tr>' +
                        '<th style="width:22%;">@lang("purchaseRequisition::lang.field")</th>' +
                        '<th style="width:39%; background:#fff8f8;">@lang("purchaseRequisition::lang.before")</th>' +
                        '<th style="width:39%; background:#f8fff8;">@lang("purchaseRequisition::lang.after")</th>' +
                    '</tr></thead><tbody>' +
                    '<tr><td>@lang("purchaseRequisition::lang.order_qty")</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>@lang("purchaseRequisition::lang.supplier_price")</td>' +
                        '<td style="background:#fff8f8;">' + sym + ' ' + origPrice + '</td>' +
                        '<td style="background:#f8fff8;"><strong>' + sym + ' ' + reqPrice + '</strong></td></tr>' +
                    '</tbody></table>' +
                    (c.supplier_note ? '<p style="margin:0; font-size:12px;"><strong>@lang("purchaseRequisition::lang.supplier_notes"):</strong> ' + c.supplier_note + '</p>' : '') +
                    (c.admin_note ? '<p style="margin:4px 0 0; font-size:12px;"><strong>@lang("purchaseRequisition::lang.admin_note_label"):</strong> ' + c.admin_note + '</p>' : '') +
                    '</div></div>';
            });

            $('#change_history_body').html(html);
            $('#change_history_modal').modal('show');
        });

        // Save Notes
        $('#save_notes_btn').click(function() {
            var $btn = $(this);
            $btn.prop('disabled', true);

            var formData = new FormData();
            formData.append('order_note', $('#order_note_input').val());

            // Collect row notes
            $('.row-note-input').each(function() {
                var lineId = $(this).data('line-id');
                formData.append('row_notes[' + lineId + ']', $(this).val());
            });

            // Images
            var files = $('#image_upload_input')[0].files;
            for (var i = 0; i < files.length; i++) {
                formData.append('images[]', files[i]);
            }

            $.ajax({
                url: '{{ $saveNotesUrl }}',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                success: function(res) {
                    if (res.success) {
                        alert(res.message);
                        // Clear file input
                        $('#image_upload_input').val('');
                    }
                    $btn.prop('disabled', false);
                },
                error: function(xhr) {
                    var errors = xhr.responseJSON && xhr.responseJSON.errors
                        ? Object.values(xhr.responseJSON.errors).flat().join('\n')
                        : 'Error saving notes';
                    alert(errors);
                    $btn.prop('disabled', false);
                }
            });
        });

    });

    // ─── Payments panel ───────────────────────────────────────────────────

    $(document).on('change', '.payment-received-cb', function() {
        var $cb      = $(this);
        var url      = $cb.data('url');
        var received = $cb.is(':checked') ? 1 : 0;
        $cb.closest('.payment-entry').find('.received-note-section').toggle($cb.is(':checked'));
        $.ajax({
            url: url, method: 'POST',
            data: { received: received, _token: $('meta[name="csrf-token"]').attr('content') }
        });
    });

    $(document).on('click', '.btn-save-received', function() {
        var $btn = $(this);
        var url  = $btn.data('url');
        var note = $btn.closest('.received-note-section').find('.received-note-input').val();
        $btn.prop('disabled', true);
        $.ajax({
            url: url, method: 'POST',
            data: { received: 1, received_note: note, _token: $('meta[name="csrf-token"]').attr('content') },
            success: function(res) {
                if (res.success) { alert(res.message); }
                $btn.prop('disabled', false);
            },
            error: function() { $btn.prop('disabled', false); }
        });
    });

    </script>
</body>
</html>
