@extends('layouts.app')

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

@section('content')

<style>
    .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;
    }
    .product-link {
        cursor: pointer;
        color: #3c8dbc;
    }
    .product-link: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; }
    /* Sticky header row - vertical (sticks to top when scrolling down) */
    .table-responsive { overflow-x: auto; }
    #approval_table thead th {
        position: sticky;
        top: 0;
        z-index: 4;
        background: white;
    }
    #approval_table tfoot th {
        position: sticky;
        bottom: 0;
        z-index: 4;
        background: #f5f5f5;
    }
    /* Sticky first 3 columns (checkbox, product name, SKU) - horizontal */
    #approval_table thead th:nth-child(1),
    #approval_table tbody td:nth-child(1),
    #approval_table tfoot th:nth-child(1),
    #approval_table thead th:nth-child(2),
    #approval_table tbody td:nth-child(2),
    #approval_table tfoot th:nth-child(2),
    #approval_table thead th:nth-child(3),
    #approval_table tbody td:nth-child(3),
    #approval_table tfoot th:nth-child(3) {
        position: sticky;
        z-index: 2;
        background: white;
    }
    /* thead first 3: both top AND left sticky (z-index must beat both groups) */
    #approval_table thead th:nth-child(1),
    #approval_table thead th:nth-child(2),
    #approval_table thead th:nth-child(3) { z-index: 5; }
    /* tfoot first 3: both bottom AND left sticky */
    #approval_table tfoot th:nth-child(1),
    #approval_table tfoot th:nth-child(2),
    #approval_table tfoot th:nth-child(3) { z-index: 5; background: #f5f5f5; }
    #approval_table thead th:nth-child(1),
    #approval_table tbody td:nth-child(1),
    #approval_table tfoot th:nth-child(1) { left: 0; }
    /* nth-child(2) and (3) left values are set by JS after draw */
    #approval_table thead th:nth-child(3),
    #approval_table tbody td:nth-child(3),
    #approval_table tfoot th:nth-child(3) { box-shadow: 2px 0 4px rgba(0,0,0,0.08); }
    .product-thumb { max-width: 60px; max-height: 60px; cursor: pointer; }
</style>

<!-- Content Header -->
<section class="content-header">
    <h1>@lang('purchaseRequisition::lang.approve_purchase_requisition') - {{ isset($supplierResponse) && $supplierResponse && $supplierResponse->ref_no ? $supplierResponse->ref_no : $prRequest->ref_no }}</h1>
</section>

<!-- Main content -->
<section class="content">
    {!! Form::open(['url' => action([\Modules\PurchaseRequisition\Http\Controllers\PrApprovalController::class, 'approve'], ['id' => $prRequest->id]), 'method' => 'post', 'id' => 'approval_form']) !!}

    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary'])
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>@lang('purchaseRequisition::lang.reference_no'):</strong> {{ isset($supplierResponse) && $supplierResponse && $supplierResponse->ref_no ? $supplierResponse->ref_no : $prRequest->ref_no }}</p>
                        <p><strong>@lang('purchaseRequisition::lang.date'):</strong> {{ \Carbon\Carbon::parse($prRequest->transaction_date)->format('Y-m-d') }}</p>
                        <p><strong>@lang('purchase.supplier'):</strong>
                            @if(isset($supplierResponse) && $supplierResponse)
                                <span class="label label-info">{{ $supplierResponse->supplier ? ($supplierResponse->supplier->name ?: $supplierResponse->supplier->supplier_business_name ?: 'Unknown') : 'Unknown' }}</span>
                            @else
                                @foreach($prRequest->supplierResponses as $response)
                                    @if(in_array($response->status, ['submitted', 'approved']))
                                        <span class="label label-{{ $response->status == 'approved' ? 'success' : 'info' }}">{{ $response->supplier ? ($response->supplier->name ?: $response->supplier->supplier_business_name ?: 'Unknown') : 'Unknown' }}</span>
                                    @endif
                                @endforeach
                            @endif
                        </p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>@lang('sale.status'):</strong>
                            <span class="label label-warning">{{ ucfirst(str_replace('_', ' ', $prRequest->status)) }}</span>
                        </p>
                        <p><strong>@lang('purchaseRequisition::lang.margin_threshold'):</strong> {{ $settings['margin_ratio'] }}%</p>
                        @if(isset($supplierResponse) && $supplierResponse && $supplierResponse->currency)
                        <p><strong>@lang('purchaseRequisition::lang.currency'):</strong> {{ $supplierResponse->currency->name }} ({{ $supplierResponse->currency->symbol }})
                            @if($supplierResponse->currency->code != 'EGP')
                            - <strong>@lang('purchaseRequisition::lang.conversion_rate'):</strong> {{ number_format($supplierResponse->currency->conversion_rate_to_egp, 4) }}
                            @endif
                        </p>
                        @endif
                    </div>
                </div>
            @endcomponent>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary', 'title' => __('purchaseRequisition::lang.supplier_responses')])
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    @lang('purchaseRequisition::lang.rows_highlighted_have_low_margin')
                </div>

                <div class="table-responsive">
                    <table class="table table-bordered table-striped" id="approval_table">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="select_all"></th>
                                <th>@lang('sale.product')</th>
                                <th>@lang('purchaseRequisition::lang.sku')</th>
                                <th>@lang('purchase.supplier')</th>
                                <th>@lang('purchaseRequisition::lang.extra_part_number') <i class="fa fa-info-circle" title="@lang('purchaseRequisition::lang.click_to_view_full_content')"></i></th>
                                <th>@lang('purchaseRequisition::lang.image')</th>
                                <th>@lang('purchaseRequisition::lang.notes')</th>
                                <th>@lang('purchaseRequisition::lang.current_stock')</th>
                                <th>@lang('purchaseRequisition::lang.required_qty')</th>
                                <th>@lang('purchaseRequisition::lang.avg_cost')</th>
                                <th>@lang('purchaseRequisition::lang.last_purchase_price')</th>
                                <th>@lang('purchaseRequisition::lang.last_purchased_qty')</th>
                                <th>@lang('purchaseRequisition::lang.last_purchased_adjusted_qty')</th>
                                <th>@lang('purchaseRequisition::lang.year_ago_sold_qty')</th>
                                <th>@lang('purchaseRequisition::lang.selling_unit_price')</th>
                                <th>@lang('purchaseRequisition::lang.available_qty')</th>
                                <th>@lang('purchaseRequisition::lang.order_qty')</th>
                                <th>@lang('purchaseRequisition::lang.supplier_price')</th>
                                <th>@lang('purchaseRequisition::lang.supplier_notes')</th>
                                <th>@lang('purchaseRequisition::lang.converted_price_egp')</th>
                                <th>@lang('purchaseRequisition::lang.margin')</th>
                            </tr>
                        </thead>
                        <tfoot>
                            <tr style="font-weight: bold;">
                                <th></th>
                                <th>@lang('purchaseRequisition::lang.total')</th>
                                <th></th><th></th>{{-- sku, supplier_name --}}
                                <th></th><th></th><th></th><th></th>{{-- extra_part, image, notes, current_stock --}}
                                <th id="tfoot_required_qty">-</th>
                                <th></th><th></th><th></th><th></th><th></th><th></th>{{-- avg_cost to selling_price --}}
                                <th id="tfoot_available_qty">-</th>
                                <th id="tfoot_order_qty">-</th>
                                <th id="tfoot_supplier_price">-</th>
                                <th></th>{{-- supplier_notes --}}
                                <th id="tfoot_converted_price">-</th>
                                <th></th>{{-- margin --}}
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <div class="row" style="margin-top: 20px;">
                    <div class="col-md-12">
                        <button type="button" class="btn btn-success btn-lg" id="approve_btn">
                            <i class="fa fa-check"></i> @lang('purchaseRequisition::lang.approve_selected')
                        </button>
                        <a href="{{ action([\Modules\PurchaseRequisition\Http\Controllers\PrIndexController::class, 'index']) }}" class="btn btn-default btn-lg">
                            @lang('purchaseRequisition::lang.back')
                        </a>
                    </div>
                </div>
            @endcomponent>
        </div>
    </div>

    {!! Form::close() !!}

    <!-- Product View Modal -->
    <div class="modal fade view_product_modal" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel"></div>

    <!-- Fullscreen Image Modal -->
    <div id="approval_fullscreen_modal" style="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);">
        <span id="close_fullscreen_approval" style="position:absolute; top:15px; right:35px; color:#f1f1f1; font-size:40px; font-weight:bold; cursor:pointer;">&times;</span>
        <img id="approval_fullscreen_image" src="" style="margin:auto; display:block; max-width:90%; max-height:90%;">
    </div>

    <!-- Extra Part Number Modal -->
    <div class="modal fade" id="extraPartModal" 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" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">@lang('purchaseRequisition::lang.extra_part_number')</h4>
                </div>
                <div class="modal-body">
                    <p id="extraPartContent"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">@lang('messages.close')</button>
                </div>
            </div>
        </div>
    </div>
</section>

@endsection

@section('javascript')
<script type="text/javascript">
$(document).ready(function() {
    var selectedProducts = [];
    var settings = {
        margin_ratio: {{ $settings['margin_ratio'] }},
        bg_color_low_margin: '{{ $settings["bg_color_low_margin"] }}'
    };

    // Approval DataTable
    var approval_table = $('#approval_table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '{{ action([\Modules\PurchaseRequisition\Http\Controllers\PrApprovalController::class, "getProducts"], ["id" => $prRequest->id]) }}',
            type: 'POST',
            data: function(d) {
                @if(isset($responseId) && $responseId)
                d.response_id = '{{ $responseId }}';
                @endif
            }
        },
        columns: [
            {
                data: 'approve_checkbox',
                name: 'approve_checkbox',
                orderable: false,
                searchable: false
            },
            { data: 'product_name', name: 'product_name' },
            { data: 'sku', name: 'sku' },
            { data: 'supplier_name', name: 'supplier_name', orderable: false, searchable: false },
            { data: 'product_custom_field4', name: 'product_custom_field4', defaultContent: '-' },
            { data: 'product_image', name: 'product_image', orderable: false, searchable: false },
            { data: 'pr_product_notes', name: 'pr_product_notes', defaultContent: '-', orderable: false },
            { data: 'current_stock', name: 'current_stock' },
            { data: 'required_quantity', name: 'required_quantity' },
            { data: 'avg_unit_cost', name: 'avg_unit_cost' },
            { data: 'last_purchase_price', name: 'last_purchase_price' },
            { data: 'last_purchased_qty', name: 'last_purchased_qty', defaultContent: '0.00' },
            { data: 'last_purchased_adjusted_qty', name: 'last_purchased_adjusted_qty', defaultContent: '0.00' },
            { data: 'year_ago_sold_qty', name: 'year_ago_sold_qty', defaultContent: '0.00' },
            { data: 'selling_price', name: 'selling_price' },
            { data: 'available_qty', name: 'available_qty' },
            { data: 'order_qty', name: 'order_qty', orderable: false, searchable: false },
            { data: 'supplier_price', name: 'supplier_price' },
            { data: 'supplier_notes', name: 'supplier_notes' },
            { data: 'converted_price_egp', name: 'converted_price_egp' },
            { data: 'margin', name: 'margin' }
        ],
        drawCallback: function() {
            // Restore checkbox states
            $('.approve-product').each(function() {
                var id = $(this).data('id');
                if (selectedProducts.indexOf(id) !== -1) {
                    $(this).prop('checked', true);
                }
            });
            updateTotals(this.api());
        },
        footerCallback: function() {
            updateTotals(this.api());
        }
    });

    function updateTotals(api) {
        // Column indices (0-based) after inserting supplier_name at col 3:
        // 8=required_qty, 15=available_qty, 16=order_qty, 17=supplier_price, 19=converted_price_egp
        var totalRequired = 0, totalAvailable = 0, totalOrder = 0, totalSupplierPrice = 0, totalConverted = 0;

        api.column(8, {page: 'current'}).data().each(function(val) {
            totalRequired += parseFloat(String(val).replace(/,/g, '')) || 0;
        });
        api.column(15, {page: 'current'}).data().each(function(val) {
            totalAvailable += parseFloat(String(val).replace(/,/g, '')) || 0;
        });
        api.column(16, {page: 'current'}).nodes().each(function(node) {
            totalOrder += parseFloat($(node).find('input').val()) || 0;
        });
        api.column(17, {page: 'current'}).data().each(function(val) {
            totalSupplierPrice += parseFloat(String(val).replace(/[^0-9.]/g, '')) || 0;
        });
        api.column(19, {page: 'current'}).nodes().each(function(node) {
            totalConverted += parseFloat($(node).text().replace(/[^0-9.]/g, '')) || 0;
        });

        $('#tfoot_required_qty').text(totalRequired.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
        $('#tfoot_available_qty').text(totalAvailable.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
        $('#tfoot_order_qty').text(totalOrder.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
        $('#tfoot_supplier_price').text(totalSupplierPrice.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
        $('#tfoot_converted_price').text('EGP ' + totalConverted.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
    }

    // Select all checkbox
    $('#select_all').click(function() {
        var isChecked = $(this).is(':checked');
        $('.approve-product').prop('checked', isChecked).trigger('change');
    });

    // Individual checkbox
    $(document).on('change', '.approve-product', function() {
        var id = $(this).data('id');
        var index = selectedProducts.indexOf(id);

        if ($(this).is(':checked')) {
            if (index === -1) {
                selectedProducts.push(id);
            }
        } else {
            if (index !== -1) {
                selectedProducts.splice(index, 1);
            }
        }

        // Update select all checkbox
        var totalCheckboxes = $('.approve-product').length;
        var checkedCheckboxes = $('.approve-product:checked').length;
        $('#select_all').prop('checked', totalCheckboxes === checkedCheckboxes);
    });

    // Validate order qty on change
    $(document).on('change', '.order-qty-input', function() {
        var max = parseFloat($(this).data('max'));
        var val = parseFloat($(this).val());
        if (val > max) {
            $(this).val(max.toFixed(2));
            toastr.error('@lang("purchaseRequisition::lang.order_qty_exceeds_available")');
        }
        if (val < 0) {
            $(this).val('0.00');
        }
        updateTotals(approval_table);
    });

    // Approve button
    $('#approve_btn').click(function() {
        if (selectedProducts.length === 0) {
            toastr.error('@lang("purchaseRequisition::lang.please_select_at_least_one_product")');
            return;
        }

        // Validate order quantities for selected products
        var valid = true;
        selectedProducts.forEach(function(id) {
            var input = $('.order-qty-input[data-id="' + id + '"]');
            if (input.length) {
                var val = parseFloat(input.val());
                var max = parseFloat(input.data('max'));
                if (isNaN(val) || val <= 0) {
                    toastr.error('@lang("purchaseRequisition::lang.order_qty_must_be_greater_than_zero")');
                    valid = false;
                    return false;
                }
                if (val > max) {
                    toastr.error('@lang("purchaseRequisition::lang.order_qty_exceeds_available")');
                    valid = false;
                    return false;
                }
            }
        });

        if (!valid) return;

        swal({
            title: '@lang("messages.sure")',
            text: '@lang("purchaseRequisition::lang.approve_selected_products")',
            icon: "warning",
            buttons: true,
        }).then((willApprove) => {
            if (willApprove) {
                // Add selected products and order quantities to form
                var form = $('#approval_form');
                form.find('input[name="approved_products[]"]').remove();
                form.find('input[name^="order_quantities"]').remove();

                selectedProducts.forEach(function(id) {
                    form.append('<input type="hidden" name="approved_products[]" value="' + id + '">');
                    var input = $('.order-qty-input[data-id="' + id + '"]');
                    if (input.length) {
                        form.append('<input type="hidden" name="order_quantities[' + id + ']" value="' + input.val() + '">');
                    }
                });

                form.submit();
            }
        });
    });

    // Product name click - open view modal
    $(document).on('click', '.product-link', function(e) {
        e.preventDefault();
        var productId = $(this).data('product-id');
        if (productId) {
            $.ajax({
                url: '/products/view/' + productId,
                dataType: 'html',
                success: function(result) {
                    $('.view_product_modal').html(result).modal('show');
                }
            });
        }
    });

    // Load stock details when product modal is shown
    $(document).on('shown.bs.modal', '.view_product_modal', function() {
        var div = $(this).find('#view_product_stock_details');
        if (div.length) {
            $.ajax({
                url: '/reports/stock-report?for=view_product&product_id=' + div.data('product_id'),
                dataType: 'html',
                success: function(result) {
                    div.html(result);
                    __currency_convert_recursively(div);
                },
                error: function(xhr) {
                    console.error('Error loading stock details:', xhr.responseText);
                    div.html('<p class="text-danger">Error loading stock details</p>');
                }
            });
        }
    });

    // Extra part number click - show in modal
    $(document).on('click', '.extra-part-trigger', function(e) {
        e.preventDefault();
        var fullText = $(this).attr('title');
        if (fullText && fullText !== '-') {
            $('#extraPartContent').text(fullText);
            $('#extraPartModal').modal('show');
        }
    });

    // Product thumbnail click - fullscreen
    $(document).on('click', '.product-thumb', function() {
        $('#approval_fullscreen_image').attr('src', $(this).attr('src'));
        $('#approval_fullscreen_modal').show();
    });

    $('#close_fullscreen_approval').click(function() {
        $('#approval_fullscreen_modal').hide();
    });

    // Fix sticky column positions and backgrounds after each draw
    approval_table.on('draw', function() {
        var col1W = $('#approval_table thead th:nth-child(1)').outerWidth() || 0;
        var col2W = $('#approval_table thead th:nth-child(2)').outerWidth() || 0;
        var leftCol2 = col1W + 'px';
        var leftCol3 = (col1W + col2W) + 'px';

        $('#approval_table thead th:nth-child(2), #approval_table tbody td:nth-child(2), #approval_table tfoot th:nth-child(2)').css('left', leftCol2);
        $('#approval_table thead th:nth-child(3), #approval_table tbody td:nth-child(3), #approval_table tfoot th:nth-child(3)').css('left', leftCol3);

        $('#approval_table tbody tr').each(function() {
            // Only use the row's bg if it has an explicit inline color (e.g. low-margin highlight).
            // Otherwise force white so the semi-transparent striped pattern doesn't bleed through.
            var inlineStyle = $(this).attr('style') || '';
            var rowBg = inlineStyle.indexOf('background-color') !== -1
                ? $(this).css('background-color')
                : 'white';
            $(this).find('td:nth-child(1), td:nth-child(2), td:nth-child(3)').css('background-color', rowBg);
        });
    });
});
</script>
@endsection
