@extends('layouts.app')

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

@section('content')

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

<!-- Main content -->
<section class="content">
    @if(isset($prRequest))
    {!! Form::open(['url' => url('/pr-module/generate/' . $prRequest->id . '/update'), 'method' => 'post', 'id' => 'pr_generate_form']) !!}
    @else
    {!! Form::open(['url' => action([\Modules\PurchaseRequisition\Http\Controllers\PrGenerateController::class, 'store']), 'method' => 'post', 'id' => 'pr_generate_form']) !!}
    @endif

    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary', 'title' => __('purchaseRequisition::lang.filters')])
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            {!! Form::label('brand_id', __('product.brand') . ':') !!}
                            <select name="brand_id[]" id="brand_id" class="form-control select2" multiple="multiple" style="width: 100%;">
                                @foreach($brands as $id => $name)
                                    <option value="{{ $id }}">{{ $name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            {!! Form::label('category_id', __('product.category') . ':') !!}
                            <select name="category_id[]" id="category_id" class="form-control select2" multiple="multiple" style="width: 100%;">
                                @foreach($categories as $id => $name)
                                    <option value="{{ $id }}">{{ $name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            {!! Form::label('subcategory_id', __('product.sub_category') . ':') !!}
                            <select name="subcategory_id[]" id="subcategory_id" class="form-control select2" multiple="multiple" style="width: 100%;" disabled>
                            </select>
                            <small class="text-muted" id="subcategory_hint">@lang('purchaseRequisition::lang.select_category_first')</small>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('selling_interval', __('purchaseRequisition::lang.selling_interval_days') . ':*') !!}
                            {!! Form::number('selling_interval', isset($prRequest) ? $prRequest->selling_interval : ($settings['selling_interval'] ?? 365), ['class' => 'form-control', 'required', 'min' => 1, 'id' => 'selling_interval']) !!}
                            <small class="text-muted">@lang('purchaseRequisition::lang.default_365_days')</small>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-group">
                            {!! Form::label('stock_cover_interval', __('purchaseRequisition::lang.stock_cover_interval_days') . ':*') !!}
                            {!! Form::number('stock_cover_interval', isset($prRequest) ? $prRequest->stock_cover_interval : ($settings['stock_cover_interval'] ?? 180), ['class' => 'form-control', 'required', 'min' => 1, 'id' => 'stock_cover_interval']) !!}
                            <small class="text-muted">@lang('purchaseRequisition::lang.default_180_days')</small>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <br>
                            <button type="button" class="btn btn-primary" id="auto_generate_btn">
                                <i class="fa fa-cogs"></i> @lang('purchaseRequisition::lang.auto_generate')
                            </button>
                            <button type="button" class="btn btn-success" id="add_products_btn">
                                <i class="fa fa-plus"></i> @lang('purchaseRequisition::lang.add_products')
                            </button>
                        </div>
                    </div>
                </div>
            @endcomponent
        </div>
    </div>

    <!-- Progress Bar (hidden by default) -->
    <div class="row" id="progress_container" style="display: none;">
        <div class="col-md-12">
            <div class="box box-primary">
                <div class="box-body">
                    <div class="progress progress-sm active">
                        <div class="progress-bar progress-bar-success progress-bar-striped" id="loading_progress" role="progressbar" style="width: 0%">
                            <span id="progress_text">0%</span>
                        </div>
                    </div>
                    <p class="text-center text-muted" id="progress_status">Loading products...</p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary', 'title' => __('purchaseRequisition::lang.products')])
                <div class="table-responsive">
                    <table class="table table-bordered table-striped" id="products_table" style="width: 100%;">
                        <thead>
                            <tr>
                                <th>@lang('sale.product')</th>
                                <th style="max-width: 120px;">@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.current_stock')</th>
                                <th>@lang('purchaseRequisition::lang.covered_qty')</th>
                                <th>@lang('purchaseRequisition::lang.pending_purchase_qty')</th>
                                <th>@lang('purchaseRequisition::lang.required_quantity')</th>
                                <th>@lang('purchaseRequisition::lang.avg_unit_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.actions')</th>
                            </tr>
                        </thead>
                    </table>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            {!! Form::label('general_notes', __('purchaseRequisition::lang.general_notes') . ':') !!}
                            {!! Form::textarea('general_notes', isset($prRequest) ? $prRequest->notes : null, ['class' => 'form-control', 'rows' => 3, 'id' => 'general_notes']) !!}
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <button type="button" class="btn btn-primary btn-lg" id="save_pr_btn" disabled>
                            <i class="fa fa-save"></i> @lang('messages.save')
                        </button>
                        <button type="button" class="btn btn-success btn-lg" id="submit_pr_btn" disabled>
                            <i class="fa fa-check"></i> @lang('purchaseRequisition::lang.submit')
                        </button>
                    </div>
                </div>
            @endcomponent
        </div>
    </div>

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

<!-- Add Products Modal -->
<div class="modal fade" id="add_products_modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document" style="width: 90%; max-width: 1200px;">
        <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.select_products')</h4>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped" id="select_products_table" style="width: 100%;">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="select_all_products"></th>
                                <th>@lang('sale.product')</th>
                                <th>@lang('product.sku')</th>
                                <th>@lang('product.brand')</th>
                                <th>@lang('product.category')</th>
                                <th>@lang('purchaseRequisition::lang.current_stock')</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">@lang('messages.close')</button>
                <button type="button" class="btn btn-primary" id="insert_selected_products">
                    <i class="fa fa-plus"></i> @lang('purchaseRequisition::lang.insert_selected')
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Notes Modal -->
<div class="modal fade" id="notes_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.product_notes')</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="notes_variation_id">
                <p id="notes_product_name" class="text-muted"></p>
                <div class="form-group">
                    {!! Form::label('product_notes', __('purchaseRequisition::lang.notes') . ':') !!}
                    {!! Form::textarea('product_notes', null, ['class' => 'form-control', 'rows' => 4, 'id' => 'product_notes']) !!}
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">@lang('messages.close')</button>
                <button type="button" class="btn btn-primary" id="save_notes_btn">@lang('messages.save')</button>
            </div>
        </div>
    </div>
</div>

<!-- Product View Modal -->
<div class="modal fade view_product_modal" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel"></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('messages.close')</button>
            </div>
        </div>
    </div>
</div>

@endsection

@section('css')
<style>
    /* 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; }
    .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;
    }
</style>
@endsection

@section('javascript')
<script type="text/javascript">
$(document).ready(function() {
    // Store products data for submission
    var productsData = {};

    // Settings for row styling
    var settings = {
        bg_color_no_purchase: '{{ $settings["bg_color_no_purchase"] ?? "#fff3cd" }}',
        bg_color_no_purchase_no_stock: '{{ $settings["bg_color_no_purchase_no_stock"] ?? "#ffddc1" }}',
        bg_color_zero_qty: '{{ $settings["bg_color_zero_qty"] ?? "#d4edda" }}'
    };

    // Initialize select2 without placeholder for multiple select
    $('#brand_id').select2({
        allowClear: true,
        width: '100%'
    });

    $('#category_id').select2({
        allowClear: true,
        width: '100%'
    });

    $('#subcategory_id').select2({
        allowClear: true,
        width: '100%'
    });

    // Category change - load subcategories grouped by category
    var categoryChangeTimeout = null;
    var lastCategoryValue = null;
    var isLoadingSubcategories = false;

    $('#category_id').on('change.select2', function() {
        var categories = $(this).val();
        var categoriesStr = categories ? categories.join(',') : '';

        // Prevent duplicate calls with same value
        if (categoriesStr === lastCategoryValue) {
            return;
        }
        lastCategoryValue = categoriesStr;

        // Clear any pending request
        if (categoryChangeTimeout) {
            clearTimeout(categoryChangeTimeout);
        }

        if (categories && categories.length > 0) {
            categoryChangeTimeout = setTimeout(function() {
                if (isLoadingSubcategories) {
                    return;
                }
                isLoadingSubcategories = true;

                $('#subcategory_id').prop('disabled', true);
                $('#subcategory_hint').text('Loading...');

                $.ajax({
                    url: '{{ url("/pr-module/generate/subcategories") }}',
                    type: 'POST',
                    data: {
                        cat_id: categories,
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(result) {
                        $('#subcategory_id').html(result).prop('disabled', false);
                        // Reinitialize select2 after changing options
                        $('#subcategory_id').select2('destroy').select2({
                            allowClear: true,
                            width: '100%'
                        });
                        $('#subcategory_hint').text('');
                        isLoadingSubcategories = false;
                    },
                    error: function(xhr) {
                        console.error('Subcategory load error:', xhr.responseText);
                        $('#subcategory_id').prop('disabled', false);
                        $('#subcategory_hint').text('Error loading subcategories');
                        isLoadingSubcategories = false;
                    }
                });
            }, 350); // Debounce 350ms
        } else {
            $('#subcategory_id').prop('disabled', true).html('');
            // Reinitialize select2 after clearing options
            $('#subcategory_id').select2('destroy').select2({
                allowClear: true,
                width: '100%'
            });
            $('#subcategory_hint').text('@lang("purchaseRequisition::lang.select_category_first")');
        }
    });

    // Validate filters before auto-generate
    function validateFilters() {
        var brands = $('#brand_id').val();
        var categories = $('#category_id').val();

        if ((!brands || brands.length === 0) && (!categories || categories.length === 0)) {
            toastr.error('@lang("purchaseRequisition::lang.please_select_brand_or_category")');
            return false;
        }
        return true;
    }

    // Progressive loading configuration
    var CHUNK_SIZE = 100; // Products per request
    var isLoadingProducts = false;

    // Initialize DataTable for products (following app default patterns)
    var productsTable = $('#products_table').DataTable({
        data: [],
        processing: true,
        autoWidth: false,
        columns: [
            { data: 'product_display', title: '@lang("sale.product")' },
            { data: 'extra_part_number', title: '@lang("purchaseRequisition::lang.extra_part_number")', defaultContent: '-', className: 'extra-part-cell' },
            { data: 'current_stock', title: '@lang("purchaseRequisition::lang.current_stock")', className: 'text-right' },
            { data: 'covered_qty', title: '@lang("purchaseRequisition::lang.covered_qty")', className: 'text-right' },
            { data: 'pending_purchase_qty', title: '@lang("purchaseRequisition::lang.pending_purchase_qty")', className: 'text-right' },
            { data: 'required_quantity_raw', title: '@lang("purchaseRequisition::lang.required_quantity")', className: 'text-center' },
            { data: 'avg_unit_cost', title: '@lang("purchaseRequisition::lang.avg_unit_cost")', className: 'text-right' },
            { data: 'last_purchase_price', title: '@lang("purchaseRequisition::lang.last_purchase_price")', className: 'text-right' },
            { data: 'last_purchased_qty', title: '@lang("purchaseRequisition::lang.last_purchased_qty")', className: 'text-right', defaultContent: '0.00' },
            { data: 'last_purchased_adjusted_qty', title: '@lang("purchaseRequisition::lang.last_purchased_adjusted_qty")', className: 'text-right', defaultContent: '0.00' },
            { data: 'year_ago_sold_qty', title: '@lang("purchaseRequisition::lang.year_ago_sold_qty")', className: 'text-right', defaultContent: '0.00' },
            { data: 'selling_price', title: '@lang("purchaseRequisition::lang.selling_unit_price")', className: 'text-right' },
            { data: 'actions', title: '@lang("purchaseRequisition::lang.actions")', orderable: false, searchable: false }
        ],
        columnDefs: [
            {
                "targets": [0], // Product display column - render for display, return searchable text for filter
                "render": function(data, type, row) {
                    if (type === 'filter' || type === 'sort') {
                        // Return plain text with SKU for searching
                        return row.product_name_plain + ' ' + (row.sku || '');
                    }
                    return data;
                }
            },
            {
                "targets": [5], // Required quantity column
                "render": function(data, type, row) {
                    if (type === 'display') {
                        return '<input type="number" class="form-control input-sm required-qty-input" data-variation-id="' + row.variation_id + '" value="' + data + '" min="0" step="1" style="width: 100px;">';
                    }
                    return data;
                }
            },
            {
                "targets": [12], // Actions column (now at index 12 after adding 3 columns)
                "orderable": false,
                "searchable": false
            }
        ],
        order: [[0, 'asc']],
        pageLength: parseInt(__default_datatable_page_entries) || 25,
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        language: {
            processing: '<i class="fa fa-spinner fa-spin fa-2x"></i>'
        },
        createdRow: function(row, data, dataIndex) {
            // Store variation_id on the row for easy access
            $(row).attr('data-variation-id', data.variation_id);

            // Apply row styling based on data
            if (!data.has_previous_purchase && !data.has_opening_stock) {
                $(row).css('background-color', settings.bg_color_no_purchase_no_stock);
            } else if (!data.has_previous_purchase) {
                $(row).css('background-color', settings.bg_color_no_purchase);
            } else if (parseFloat(data.required_quantity_raw || 0) <= 0) {
                $(row).css('background-color', settings.bg_color_zero_qty);
            }
        },
        fnDrawCallback: function(oSettings) {
            __currency_convert_recursively($('#products_table'));
        }
    });

    // Auto generate button click - Progressive Loading
    $('#auto_generate_btn').click(function() {
        if (!validateFilters()) {
            return;
        }

        if (isLoadingProducts) {
            toastr.warning('Loading in progress, please wait...');
            return;
        }

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

        // Clear existing products from DataTable
        productsTable.clear().draw();
        productsData = {};

        // Show progress bar
        $('#progress_container').show();
        updateProgress(0, 'Getting product count...');

        // Step 1: Get total count first
        $.ajax({
            url: '{{ url("/pr-module/generate/products") }}',
            type: 'POST',
            data: {
                _token: '{{ csrf_token() }}',
                brands: $('#brand_id').val() || [],
                categories: $('#category_id').val() || [],
                subcategories: $('#subcategory_id').val() || [],
                selling_interval: $('#selling_interval').val(),
                stock_cover_interval: $('#stock_cover_interval').val(),
                auto_generate: 1,
                count_only: 1
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    var totalProducts = response.total;

                    if (totalProducts === 0) {
                        btn.prop('disabled', false).html('<i class="fa fa-cogs"></i> @lang("purchaseRequisition::lang.auto_generate")');
                        $('#progress_container').hide();
                        isLoadingProducts = false;
                        toastr.warning('@lang("purchaseRequisition::lang.no_products_found")');
                        return;
                    }

                    updateProgress(5, 'Found ' + totalProducts + ' products. Loading...');

                    // Step 2: Load products in chunks
                    loadProductsInChunks(totalProducts, btn);
                } else {
                    handleLoadError(btn, 'Error getting product count');
                }
            },
            error: function(xhr, status, error) {
                handleLoadError(btn, 'Error: ' + error);
            }
        });
    });

    // Load products in chunks with progress updates
    function loadProductsInChunks(totalProducts, btn) {
        var totalChunks = Math.ceil(totalProducts / CHUNK_SIZE);
        var currentChunk = 0;
        var loadedCount = 0;

        function loadNextChunk() {
            if (currentChunk >= totalChunks) {
                // All chunks loaded
                finishLoading(btn, loadedCount);
                return;
            }

            var offset = currentChunk * CHUNK_SIZE;
            var progressPercent = Math.round(5 + (currentChunk / totalChunks * 90)); // 5-95%

            updateProgress(progressPercent, 'Loading chunk ' + (currentChunk + 1) + '/' + totalChunks + ' (' + loadedCount + '/' + totalProducts + ' products)');

            $.ajax({
                url: '{{ url("/pr-module/generate/products") }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    brands: $('#brand_id').val() || [],
                    categories: $('#category_id').val() || [],
                    subcategories: $('#subcategory_id').val() || [],
                    selling_interval: $('#selling_interval').val(),
                    stock_cover_interval: $('#stock_cover_interval').val(),
                    auto_generate: 1,
                    offset: offset,
                    limit: CHUNK_SIZE
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data) {
                        // Add products to DataTable
                        $.each(response.data, function(index, product) {
                            addProductToTable(product);
                        });

                        // Refresh DataTable to show new rows
                        refreshProductsTable();

                        loadedCount += response.data.length;
                        currentChunk++;

                        // Small delay to prevent overwhelming the server and allow UI to update
                        setTimeout(loadNextChunk, 50);
                    } else {
                        handleLoadError(btn, 'Error loading chunk ' + (currentChunk + 1));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Chunk error:', xhr.responseText);
                    // Try to continue with next chunk
                    currentChunk++;
                    setTimeout(loadNextChunk, 100);
                }
            });
        }

        // Start loading chunks
        loadNextChunk();
    }

    // Update progress bar
    function updateProgress(percent, statusText) {
        $('#loading_progress').css('width', percent + '%');
        $('#progress_text').text(percent + '%');
        $('#progress_status').text(statusText);
    }

    // Finish loading
    function finishLoading(btn, loadedCount) {
        updateProgress(100, 'Complete! Loaded ' + loadedCount + ' products');

        setTimeout(function() {
            $('#progress_container').hide();
            btn.prop('disabled', false).html('<i class="fa fa-cogs"></i> @lang("purchaseRequisition::lang.auto_generate")');
            isLoadingProducts = false;
            updateSaveButton();
            toastr.success(loadedCount + ' products loaded successfully');
        }, 500);
    }

    // Handle load error
    function handleLoadError(btn, message) {
        $('#progress_container').hide();
        btn.prop('disabled', false).html('<i class="fa fa-cogs"></i> @lang("purchaseRequisition::lang.auto_generate")');
        isLoadingProducts = false;
        console.error(message);
        toastr.error(message);
    }

    // Add product row to table using DataTables API
    function addProductToTable(product) {
        // Check for duplicate by variation_id
        if (productsData[product.variation_id]) {
            return; // Skip duplicate
        }

        // Store product data
        productsData[product.variation_id] = product;

        // Determine product display name
        var productName = product.product_name || '';
        if (product.product_type !== 'single' && product.variation_name && product.variation_name !== 'DUMMY' && product.variation_name !== '') {
            productName += ' - ' + product.variation_name;
        }

        var sku = product.sub_sku || product.sku || '';

        // Build display info parts - only show if value exists
        var infoParts = [];
        if (product.brand_name) infoParts.push('[' + product.brand_name + ']');
        if (product.category_name) infoParts.push('[' + product.category_name + ']');
        if (product.sub_category_name) infoParts.push('[' + product.sub_category_name + ']');
        if (sku) infoParts.push('(' + sku + ')');

        // Display product name on first line, info on second line
        var displayName = '<div><span class="product-link" data-product-id="' + product.product_id + '">' + productName + '</span></div>';
        if (infoParts.length > 0) {
            displayName += '<div><small class="text-muted">' + infoParts.join(' ') + '</small></div>';
        }

        var requiredQty = Math.max(0, Math.ceil(parseFloat(product.required_quantity || 0)));

        // Handle extra part number - truncate for display, store full value
        var extraPartNumber = product.product_custom_field4 || '-';
        var extraPartDisplay = extraPartNumber;
        if (extraPartNumber.length > 15) {
            extraPartDisplay = '<span class="extra-part-trigger" data-full-text="' + extraPartNumber.replace(/"/g, '&quot;') + '" title="' + extraPartNumber.replace(/"/g, '&quot;') + '">' + extraPartNumber.substring(0, 12) + '...</span>';
        }

        // Build row data for DataTables
        var rowData = {
            variation_id: product.variation_id,
            product_id: product.product_id,
            product_display: displayName,
            product_name_plain: productName,
            sku: sku, // For search functionality
            extra_part_number: extraPartDisplay,
            current_stock: parseFloat(product.current_stock || 0).toFixed(2),
            covered_qty: parseFloat(product.covered_qty || 0).toFixed(2),
            pending_purchase_qty: parseFloat(product.pending_purchase_qty || 0).toFixed(2),
            required_quantity_raw: requiredQty,
            avg_unit_cost: parseFloat(product.avg_unit_cost || 0).toFixed(2),
            last_purchase_price: parseFloat(product.last_purchase_price || 0).toFixed(2),
            last_purchased_qty: parseFloat(product.last_purchased_qty || 0).toFixed(2),
            last_purchased_adjusted_qty: parseFloat(product.last_purchased_adjusted_qty || 0).toFixed(2),
            year_ago_sold_qty: parseFloat(product.year_ago_sold_qty || 0).toFixed(2),
            selling_price: parseFloat(product.selling_price || 0).toFixed(2),
            has_previous_purchase: product.has_previous_purchase,
            actions: '<button type="button" class="btn btn-xs ' + (product.notes && product.notes.trim() !== '' ? 'btn-warning' : 'btn-info') + ' add-notes-btn" data-variation-id="' + product.variation_id + '" data-product-name="' + productName.replace(/"/g, '&quot;') + '"><i class="fa fa-sticky-note"></i></button> ' +
                     '<button type="button" class="btn btn-xs btn-danger delete-product-btn" data-variation-id="' + product.variation_id + '"><i class="fa fa-trash"></i></button>'
        };

        // Add row to DataTable
        productsTable.row.add(rowData);
    }

    // Refresh DataTable after adding all rows in a chunk
    function refreshProductsTable() {
        productsTable.draw(false);
    }

    // Update save/submit button state
    function updateSaveButton() {
        var hasProducts = Object.keys(productsData).length > 0;
        $('#save_pr_btn').prop('disabled', !hasProducts);
        $('#submit_pr_btn').prop('disabled', !hasProducts);
    }

    // Required quantity input change - update both productsData and DataTable row data
    $(document).on('change', '.required-qty-input', function() {
        var variationId = $(this).data('variation-id');
        var newQty = parseFloat($(this).val()) || 0;

        if (productsData[variationId]) {
            productsData[variationId].required_quantity = newQty;

            // Also update the DataTable row data for proper export
            var row = productsTable.row($(this).closest('tr'));
            var data = row.data();
            if (data) {
                data.required_quantity_raw = newQty;
                row.invalidate();
            }
        }
    });

    // Add Products Modal - Initialize DataTable
    var selectProductsTable = null;

    $('#add_products_btn').click(function() {
        if (!validateFilters()) {
            return;
        }

        // Destroy existing DataTable if exists
        if (selectProductsTable !== null) {
            selectProductsTable.destroy();
            $('#select_products_table tbody').empty();
        }

        selectProductsTable = $('#select_products_table').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: '{{ url("/pr-module/generate/products") }}',
                type: 'POST',
                data: function(d) {
                    d._token = '{{ csrf_token() }}';
                    d.brands = $('#brand_id').val() || [];
                    d.categories = $('#category_id').val() || [];
                    d.subcategories = $('#subcategory_id').val() || [];
                    d.selling_interval = $('#selling_interval').val();
                    d.stock_cover_interval = $('#stock_cover_interval').val();
                    d.for_selection = 1;
                },
                error: function(xhr, error, thrown) {
                    console.error('DataTable AJAX Error:', xhr.responseText);
                    toastr.error('Error loading products');
                }
            },
            columns: [
                {
                    data: null,
                    orderable: false,
                    searchable: false,
                    render: function(data, type, row) {
                        var checked = productsData[row.variation_id] ? 'checked' : '';
                        return '<input type="checkbox" class="select-product-checkbox" data-variation-id="' + row.variation_id + '" ' + checked + '>';
                    }
                },
                { data: 'product_display', name: 'products.name', defaultContent: '' },
                { data: 'sku', name: 'variations.sub_sku', defaultContent: '' },
                { data: 'brand_name', name: 'brands.name', defaultContent: 'N/A', searchable: false },
                { data: 'category_name', name: 'categories.name', defaultContent: 'N/A', searchable: false },
                { data: 'current_stock', name: 'current_stock', className: 'text-right', defaultContent: '0', orderable: false, searchable: false }
            ],
            order: [[1, 'asc']],
            language: {
                processing: '<i class="fa fa-spinner fa-spin fa-2x"></i>'
            }
        });

        $('#add_products_modal').modal('show');
    });

    // Clean up DataTable when modal is closed
    $('#add_products_modal').on('hidden.bs.modal', function () {
        if (selectProductsTable !== null) {
            selectProductsTable.destroy();
            selectProductsTable = null;
            $('#select_products_table tbody').empty();
        }
    });

    // Select all products checkbox
    $(document).on('change', '#select_all_products', function() {
        var isChecked = $(this).prop('checked');
        $('.select-product-checkbox').prop('checked', isChecked);
    });

    // Insert selected products - fetch full data for selected variations
    $('#insert_selected_products').click(function() {
        var selectedVariationIds = [];

        $('.select-product-checkbox:checked').each(function() {
            var variationId = $(this).data('variation-id');
            if (!productsData[variationId]) {
                selectedVariationIds.push(variationId);
            }
        });

        if (selectedVariationIds.length === 0) {
            toastr.warning('@lang("purchaseRequisition::lang.please_select_products")');
            return;
        }

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

        // Fetch full calculated data for selected products
        $.ajax({
            url: '{{ url("/pr-module/generate/products") }}',
            type: 'POST',
            data: {
                _token: '{{ csrf_token() }}',
                variation_ids: selectedVariationIds,
                selling_interval: $('#selling_interval').val(),
                stock_cover_interval: $('#stock_cover_interval').val(),
                auto_generate: 1
            },
            dataType: 'json',
            success: function(response) {
                btn.prop('disabled', false).html('<i class="fa fa-plus"></i> @lang("purchaseRequisition::lang.insert_selected")');

                if (response.success && response.data) {
                    var addedCount = 0;
                    $.each(response.data, function(index, product) {
                        if (!productsData[product.variation_id]) {
                            addProductToTable(product);
                            addedCount++;
                        }
                    });

                    // Refresh DataTable to show new rows
                    refreshProductsTable();

                    updateSaveButton();
                    $('#add_products_modal').modal('hide');
                    toastr.success(addedCount + ' @lang("purchaseRequisition::lang.products_added")');
                } else {
                    toastr.error('Error loading product data');
                }
            },
            error: function(xhr) {
                btn.prop('disabled', false).html('<i class="fa fa-plus"></i> @lang("purchaseRequisition::lang.insert_selected")');
                console.error('Error fetching product data:', xhr.responseText);
                toastr.error('Error loading product data');
            }
        });
    });

    // Delete product from table using DataTables API
    $(document).on('click', '.delete-product-btn', function() {
        var variationId = $(this).data('variation-id');
        var btn = $(this);

        // Remove from data
        delete productsData[variationId];

        // Remove row from DataTable
        var row = productsTable.row(btn.closest('tr'));
        row.remove().draw(false);

        updateSaveButton();
    });

    // Open notes modal
    $(document).on('click', '.add-notes-btn', function() {
        var variationId = $(this).data('variation-id');
        var productName = $(this).data('product-name');

        $('#notes_variation_id').val(variationId);
        $('#notes_product_name').text(productName);

        // Load existing notes if any
        var existingNotes = productsData[variationId] ? productsData[variationId].notes || '' : '';
        $('#product_notes').val(existingNotes);

        $('#notes_modal').modal('show');
    });

    // Save notes
    $('#save_notes_btn').click(function() {
        var variationId = $('#notes_variation_id').val();
        var notes = $('#product_notes').val();

        if (productsData[variationId]) {
            productsData[variationId].notes = notes;
        }

        // Update button appearance to show notes exist
        if (notes && notes.trim() !== '') {
            $('button.add-notes-btn[data-variation-id="' + variationId + '"]')
                .removeClass('btn-info').addClass('btn-warning');
        } else {
            $('button.add-notes-btn[data-variation-id="' + variationId + '"]')
                .removeClass('btn-warning').addClass('btn-info');
        }

        $('#notes_modal').modal('hide');
        toastr.success('@lang("messages.saved_successfully")');
    });

    // Submit PR form with specified action
    function submitPrForm(action) {
        // Validate products
        if (Object.keys(productsData).length === 0) {
            toastr.error('@lang("purchaseRequisition::lang.please_add_products")');
            return;
        }

        // Sync quantities from DataTable (handles pagination)
        productsTable.rows().every(function() {
            var data = this.data();
            if (data && productsData[data.variation_id]) {
                var node = this.node();
                var input = $(node).find('.required-qty-input');
                if (input.length) {
                    productsData[data.variation_id].required_quantity = parseFloat(input.val()) || 0;
                } else {
                    productsData[data.variation_id].required_quantity = parseFloat(data.required_quantity_raw) || 0;
                }
            }
        });

        // Filter products with quantity > 0
        var productsToSubmit = [];
        $.each(productsData, function(variationId, product) {
            if (parseFloat(product.required_quantity) > 0) {
                productsToSubmit.push(product);
            }
        });

        if (productsToSubmit.length === 0) {
            toastr.error('@lang("purchaseRequisition::lang.no_products_with_quantity")');
            return;
        }

        var saveBtn = $('#save_pr_btn');
        var submitBtn = $('#submit_pr_btn');
        saveBtn.prop('disabled', true);
        submitBtn.prop('disabled', true);

        if (action === 'submit') {
            submitBtn.html('<i class="fa fa-spinner fa-spin"></i> @lang("purchaseRequisition::lang.submitting")...');
        } else {
            saveBtn.html('<i class="fa fa-spinner fa-spin"></i> @lang("purchaseRequisition::lang.saving")...');
        }

        @if(isset($prRequest))
        var submitUrl = '{{ url("/pr-module/generate/" . $prRequest->id . "/update") }}';
        @else
        var submitUrl = '{{ url("/pr-module/generate/store") }}';
        @endif

        $.ajax({
            url: submitUrl,
            type: 'POST',
            data: {
                _token: '{{ csrf_token() }}',
                action: action,
                selling_interval: $('#selling_interval').val(),
                stock_cover_interval: $('#stock_cover_interval').val(),
                general_notes: $('#general_notes').val(),
                products: JSON.stringify(productsToSubmit)
            },
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    toastr.success(result.msg);
                    window.location.href = '{{ url("/pr-module") }}';
                } else {
                    toastr.error(result.msg || 'Error saving');
                    saveBtn.prop('disabled', false).html('<i class="fa fa-save"></i> @lang("messages.save")');
                    submitBtn.prop('disabled', false).html('<i class="fa fa-check"></i> @lang("purchaseRequisition::lang.submit")');
                }
            },
            error: function(xhr, status, error) {
                console.error('Save Error:', xhr.responseText);
                toastr.error('Error saving: ' + error);
                saveBtn.prop('disabled', false).html('<i class="fa fa-save"></i> @lang("messages.save")');
                submitBtn.prop('disabled', false).html('<i class="fa fa-check"></i> @lang("purchaseRequisition::lang.submit")');
            }
        });
    }

    // Save button click (status = generating)
    $('#save_pr_btn').click(function(e) {
        e.preventDefault();
        submitPrForm('save');
    });

    // Submit button click (status = draft)
    $('#submit_pr_btn').click(function(e) {
        e.preventDefault();
        submitPrForm('submit');
    });

    // Prevent form submission by Enter key
    $('#pr_generate_form').submit(function(e) {
        e.preventDefault();
    });

    // 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');
                },
                error: function(xhr) {
                    console.error('Error loading product view:', xhr.responseText);
                    toastr.error('Error loading product details');
                }
            });
        }
    });

    // 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 full text in modal
    $(document).on('click', '.extra-part-trigger', function(e) {
        e.preventDefault();
        var fullText = $(this).data('full-text');
        $('#extra_part_content').text(fullText);
        $('#extra_part_modal').modal('show');
    });

    // Edit mode: load existing products
    @if(isset($existingProducts))
    (function() {
        var existingProducts = @json($existingProducts);
        if (existingProducts && existingProducts.length > 0) {
            existingProducts.forEach(function(product) {
                addProductToTable(product);
            });
            productsTable.draw();
            updateSaveButton();
        }
    })();
    @endif
});
</script>
@endsection
