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

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">

    <style>
        body { padding: 20px; background: #f4f4f4; }
        .product-image { max-width: 100px; 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; }
        /* Remove number input arrows */
        input[type=number]::-webkit-inner-spin-button,
        input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
        input[type=number] { -moz-appearance: textfield; }
        /* Language switcher */
        .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); }
        /* Sortable column headers */
        .sortable-th { cursor: pointer; user-select: none; white-space: nowrap; }
        .sortable-th .sort-icon { margin-left: 4px; color: #aaa; font-size: 11px; }
        .sortable-th.asc  .sort-icon { color: #333; }
        .sortable-th.desc .sort-icon { color: #333; }
    </style>
</head>
<body>
    @php $currentLang = request('lang', 'en'); @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_requisition_response')
                            <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">
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>@lang('purchaseRequisition::lang.reference_no'):</strong> {{ $response->ref_no ?? $response->prRequest->ref_no }}</p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>@lang('purchaseRequisition::lang.date'):</strong> {{ \Carbon\Carbon::parse($response->prRequest->transaction_date)->format('Y-m-d') }}</p>
                                <p><strong>@lang('purchaseRequisition::lang.status'):</strong>
                                    <span class="label label-info">{{ ucfirst($response->status) }}</span>
                                </p>
                            </div>
                        </div>

                        <div class="alert alert-info">
                            <i class="glyphicon glyphicon-info-sign"></i>
                            @lang('purchaseRequisition::lang.zero_qty_auto_removed_notice')
                        </div>

                        @if(session('success'))
                        <div class="alert alert-success">{{ session('success') }}</div>
                        @endif

                        @if(session('error'))
                        <div class="alert alert-danger">{{ session('error') }}</div>
                        @endif

                        {!! Form::open(['url' => route('pr.supplier.save', $response->share_token), 'method' => 'post', 'id' => 'supplier_form']) !!}

                        {{-- Pass current language with the form so it survives save/submit redirects --}}
                        <input type="hidden" name="lang" value="{{ $currentLang }}">

                        <div class="form-group">
                            <label>@lang('purchaseRequisition::lang.currency'):*</label>
                            <select name="currency_id" class="form-control" required id="currency_id">
                                @foreach($currencies as $currency)
                                    <option value="{{ $currency->id }}" {{ $response->currency_id == $currency->id ? 'selected' : '' }}>
                                        {{ $currency->name }} ({{ $currency->symbol }})
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        <h4>@lang('purchaseRequisition::lang.products')</h4>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th class="sortable-th" data-col="0">@lang('purchaseRequisition::lang.product') <span class="sort-icon">↕</span></th>
                                        <th class="sortable-th" data-col="1">@lang('purchaseRequisition::lang.sku') <span class="sort-icon">↕</span></th>
                                        <th class="sortable-th" data-col="2" style="max-width: 120px;">@lang('purchaseRequisition::lang.extra_part_number') <i class="glyphicon glyphicon-info-sign" title="@lang('purchaseRequisition::lang.click_to_view_full_content')"></i> <span class="sort-icon">↕</span></th>
                                        <th>@lang('purchaseRequisition::lang.image')</th>
                                        <th class="sortable-th" data-col="4">@lang('purchaseRequisition::lang.notes') <span class="sort-icon">↕</span></th>
                                        <th class="sortable-th" data-col="5">@lang('purchaseRequisition::lang.required_qty') <span class="sort-icon">↕</span></th>
                                        <th class="sortable-th" data-col="6">@lang('purchaseRequisition::lang.available_qty') <span class="sort-icon">↕</span></th>
                                        <th class="sortable-th" data-col="7">@lang('purchaseRequisition::lang.price') <span class="sort-icon">↕</span></th>
                                        <th>@lang('purchaseRequisition::lang.supplier_notes')</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($supplierProducts as $item)
                                    @php
                                        $extraPart = $item['pr_product']->product->product_custom_field4 ?? '-';
                                        $extraPartClass = ($extraPart && $extraPart !== '-' && strlen($extraPart) > 15) ? 'extra-part-trigger' : '';
                                    @endphp
                                    <tr>
                                        <td>{{ $item['pr_product']->product->name }}@if($item['pr_product']->product->type == 'variable' && $item['pr_product']->variation && !in_array(strtoupper(trim($item['pr_product']->variation->name)), ['DUMMY', ''])) {{ $item['pr_product']->variation->name }}@endif</td>
                                        <td>{{ $item['pr_product']->variation->sub_sku ?? $item['pr_product']->product->sku ?? '-' }}</td>
                                        <td class="extra-part-cell {{ $extraPartClass }}" title="{{ $extraPart }}" data-full-text="{{ $extraPart }}">{{ $extraPart }}</td>
                                        <td>
                                            @if(!empty($item['pr_product']->product->image))
                                            <img src="{{ $item['pr_product']->product->image_url }}" class="product-image" alt="Product">
                                            @else
                                            -
                                            @endif
                                        </td>
                                        <td>{{ $item['pr_product']->notes ?? '-' }}</td>
                                        <td>{{ intval(ceil($item['pr_product']->required_quantity)) }}</td>
                                        <td>
                                            @php
                                                $availableQty = floatval($item['supplier_product']->available_qty);
                                                $requiredQtyDefault = intval(ceil($item['pr_product']->required_quantity));
                                                $defaultAvailableQty = $availableQty > 0 ? $availableQty : $requiredQtyDefault;
                                            @endphp
                                            <input type="number" name="products[{{ $item['id'] }}][available_qty]"
                                                   class="form-control available-qty-input"
                                                   data-required-qty="{{ intval(ceil($item['pr_product']->required_quantity)) }}"
                                                   value="{{ $defaultAvailableQty }}"
                                                   min="0" step="any">
                                        </td>
                                        <td>
                                            <input type="number" name="products[{{ $item['id'] }}][supplier_price]"
                                                   class="form-control"
                                                   value="{{ floatval($item['supplier_product']->supplier_price) ?: 0 }}"
                                                   min="0" step="any">
                                        </td>
                                        <td style="min-width: 250px;">
                                            <textarea name="products[{{ $item['id'] }}][supplier_notes]"
                                                      class="form-control"
                                                      rows="2">{{ $item['supplier_product']->supplier_notes }}</textarea>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>

                        <div class="row">
                            <div class="col-md-12 text-center">
                                <button type="submit" class="btn btn-success btn-lg">
                                    <i class="glyphicon glyphicon-floppy-disk"></i> @lang('purchaseRequisition::lang.save')
                                </button>
                                <button type="button" class="btn btn-primary btn-lg" id="submit_btn">
                                    <i class="glyphicon glyphicon-ok"></i> @lang('purchaseRequisition::lang.submit')
                                </button>
                            </div>
                        </div>

                        {!! Form::close() !!}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Currency & Language Selection Modal (shown on page load) -->
    <div class="modal fade" id="currency_modal" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">@lang('purchaseRequisition::lang.select_currency')</h4>
                </div>
                <div class="modal-body">
                    {{-- Language Selector --}}
                    <div class="form-group">
                        <label><strong>@lang('purchaseRequisition::lang.select_language') / Language / 语言:</strong></label>
                        <div class="btn-group" style="display:block;">
                            <button type="button" class="btn btn-sm {{ $currentLang === 'en' ? 'btn-primary' : 'btn-default' }}" id="modal_lang_en">English</button>
                            <button type="button" class="btn btn-sm {{ $currentLang === 'zh' ? 'btn-primary' : 'btn-default' }}" id="modal_lang_zh">中文</button>
                        </div>
                    </div>
                    <hr style="margin: 10px 0;">
                    {{-- Currency Selector --}}
                    <p class="text-muted">@lang('purchaseRequisition::lang.please_select_currency')</p>
                    <div class="form-group">
                        <label>@lang('purchaseRequisition::lang.currency'):</label>
                        <select id="modal_currency_id" class="form-control">
                            @foreach($currencies as $currency)
                                <option value="{{ $currency->id }}" {{ $response->currency_id == $currency->id ? 'selected' : '' }}>{{ $currency->name }} ({{ $currency->symbol }})</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary btn-block" id="confirm_currency_btn">
                        @lang('purchaseRequisition::lang.confirm') &#10003;
                    </button>
                </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>

    <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 src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

    <script>
    $(document).ready(function() {
        var currentLang = '{{ $currentLang }}';
        var selectedModalLang = currentLang;

        // Show currency/language modal on page load
        $('#currency_modal').modal('show');

        // Language buttons in modal
        $('#modal_lang_en').click(function() {
            selectedModalLang = 'en';
            $('#modal_lang_en').removeClass('btn-default').addClass('btn-primary');
            $('#modal_lang_zh').removeClass('btn-primary').addClass('btn-default');
        });
        $('#modal_lang_zh').click(function() {
            selectedModalLang = 'zh';
            $('#modal_lang_zh').removeClass('btn-default').addClass('btn-primary');
            $('#modal_lang_en').removeClass('btn-primary').addClass('btn-default');
        });

        // Confirm button: apply currency then check if language changed
        $('#confirm_currency_btn').click(function() {
            var selectedCurrency = $('#modal_currency_id').val();
            $('#currency_id').val(selectedCurrency);

            if (selectedModalLang !== currentLang) {
                // Reload page with new language (modal will reappear with same currency pre-selected)
                window.location.href = window.location.pathname + '?lang=' + selectedModalLang;
            } else {
                $('#currency_modal').modal('hide');
            }
        });

        // When page currency changes, sync to modal
        $('#currency_id').on('change', function() {
            $('#modal_currency_id').val($(this).val());
        });

        // Validate available qty
        $(document).on('change', '.available-qty-input', function() {
            var requiredQty = parseFloat($(this).data('required-qty'));
            var availableQty = parseFloat($(this).val());

            if (availableQty > requiredQty) {
                alert('@lang("purchaseRequisition::lang.available_qty_cannot_exceed_required")');
                $(this).val(requiredQty);
            }
        });

        // Fullscreen image
        $('.product-image').click(function() {
            $('#fullscreen_image').attr('src', $(this).attr('src'));
            $('#fullscreen_modal').show();
        });

        $('.close-fullscreen').click(function() {
            $('#fullscreen_modal').hide();
        });

        // Submit button with confirmation
        $('#submit_btn').click(function() {
            // Check for products with price = 0
            var zeroPriceInputs = [];
            $('input[name*="[supplier_price]"]').each(function() {
                if (parseFloat($(this).val()) === 0 || $(this).val() === '' || $(this).val() === '0') {
                    zeroPriceInputs.push($(this));
                }
            });

            function doSubmit() {
                swal({
                    title: '@lang("purchaseRequisition::lang.are_you_sure")',
                    text: '@lang("purchaseRequisition::lang.once_submitted_cannot_edit")',
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                }).then((willSubmit) => {
                    if (willSubmit) {
                        $('#supplier_form').attr('action', '{{ route("pr.supplier.submit", $response->share_token) }}');
                        $('#supplier_form').submit();
                    }
                });
            }

            if (zeroPriceInputs.length > 0) {
                swal({
                    title: '@lang("purchaseRequisition::lang.zero_price_products_found")',
                    text: zeroPriceInputs.length + ' @lang("purchaseRequisition::lang.price") = 0. @lang("purchaseRequisition::lang.zero_price_leave_them") / @lang("purchaseRequisition::lang.zero_price_remove_them")?',
                    icon: "warning",
                    buttons: {
                        leave: {
                            text: '@lang("purchaseRequisition::lang.zero_price_leave_them")',
                            value: 'leave',
                            className: 'btn-primary'
                        },
                        remove: {
                            text: '@lang("purchaseRequisition::lang.zero_price_remove_them")',
                            value: 'remove',
                            className: 'btn-warning'
                        }
                    }
                }).then((value) => {
                    if (value === 'remove') {
                        zeroPriceInputs.forEach(function(priceInput) {
                            // Zero out the available_qty for this row so it's excluded in approval
                            priceInput.closest('tr').find('input[name*="[available_qty]"]').val(0);
                        });
                    }
                    if (value) {
                        doSubmit();
                    }
                });
            } else {
                doSubmit();
            }
        });

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

        // ── Table sort ──────────────────────────────────────────────────
        function getCellSortValue(row, colIndex) {
            var $cell = $(row).find('td').eq(colIndex);
            var $input = $cell.find('input[type="number"]');
            if ($input.length) return parseFloat($input.val()) || 0;
            return $cell.text().trim().toLowerCase();
        }

        $('.sortable-th').on('click', function() {
            var $th = $(this);
            var colIndex = parseInt($th.data('col'));
            var asc = !$th.hasClass('asc'); // toggle direction

            // Reset all sortable headers
            $('.sortable-th').removeClass('asc desc').find('.sort-icon').text('↕');

            // Apply direction to clicked header
            $th.addClass(asc ? 'asc' : 'desc')
               .find('.sort-icon').text(asc ? '↑' : '↓');

            // Sort rows
            var $tbody = $('table.table tbody');
            var rows = $tbody.find('tr').toArray();

            rows.sort(function(a, b) {
                var aVal = getCellSortValue(a, colIndex);
                var bVal = getCellSortValue(b, colIndex);
                var aNum = parseFloat(aVal);
                var bNum = parseFloat(bVal);
                if (!isNaN(aNum) && !isNaN(bNum)) {
                    return asc ? aNum - bNum : bNum - aNum;
                }
                if (aVal < bVal) return asc ? -1 : 1;
                if (aVal > bVal) return asc ? 1 : -1;
                return 0;
            });

            $.each(rows, function(i, row) { $tbody.append(row); });
        });
    });
    </script>
</body>
</html>
