

<?php $__env->startSection('title', 'Factory POS'); ?>

<?php $__env->startPush('styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/select2/select2.min.css')); ?>">
<style>
.select2-container--bootstrap-5 {
    z-index: 1050;
}
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <div class="row">
        <!-- Main Panel - Customer & Items -->
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-cash-register"></i> Factory POS</h5>
                </div>
                <div class="card-body">
                    <form id="posForm">
                        <?php echo csrf_field(); ?>

                        <!-- Customer Selection -->
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label fw-bold">Invoice Type</label>
                                <select class="form-select form-select-lg" name="invoice_type_id" id="invoiceTypeSelect" required>
                                    <option value="">Select Type</option>
                                    <?php $__currentLoopData = $invoiceTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $type): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($type->id); ?>" data-tax-percentage="<?php echo e($type->tax_percentage); ?>"><?php echo e($type->name); ?> (<?php echo e(number_format($type->tax_percentage, 2)); ?>%)</option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold">Customer</label>
                                <select class="form-select form-select-lg" name="customer_id" required>
                                    <option value="">Select Customer</option>
                                    <?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $customer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($customer->id); ?>"><?php echo e($customer->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-bold">Supervising Employee</label>
                                <select class="form-select form-select-lg" name="supervising_employee_id" required>
                                    <option value="">Select Employee</option>
                                    <?php $__currentLoopData = $employees; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $employee): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($employee->id); ?>"><?php echo e($employee->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                        </div>

                        <!-- Item Search & Add -->
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label fw-bold">Search Item (with available stock)</label>
                                <div class="input-group">
                                    <select class="form-select form-select-lg select2" id="itemSearch" data-placeholder="Search finished goods with stock...">
                                        <option value=""></option>
                                    </select>
                                    <!-- Manual search trigger button - COMMENTED OUT AND HIDDEN -->
                                    <!-- <button type="button" class="btn btn-outline-primary" onclick="addItem()" style="display: none;">
                                        <i class="fas fa-plus"></i> Add Item
                                    </button> -->
                                </div>
                                <small class="form-text text-muted">Items are shown with their available lengths and warehouses</small>
                            </div>
                        </div>


                        <!-- Items Table -->
                        <div class="table-responsive" style="max-height: 60vh; overflow-y: auto;">
                            <table class="table table-striped table-hover" id="itemsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th width="35%" style="word-wrap: break-word; white-space: normal;">Item & Warehouse</th>
                                        <th width="10%">Length (m/f)</th>
                                        <th width="10%">Qty</th>
                                        <th width="20%">Price</th>
                                        <th width="15%">Total</th>
                                        <th width="10%"></th>
                                    </tr>
                                </thead>
                                <tbody id="itemsBody">
                                    <!-- Dynamic rows added here -->
                                </tbody>
                                <tfoot>
                                    <tr class="table-info">
                                        <th colspan="4" class="text-end pe-3">Grand Total:</th>
                                        <th id="grandTotal">Rs.0.00</th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        <br><br>
                        
                        <!-- Discount Section -->
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="card border-primary">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="card-title mb-0"><i class="fas fa-percent"></i> Discount</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label class="form-label">Discount Amount (Rs.)</label>
                                                <input type="number" class="form-control" name="discount_amount" id="discountAmount"
                                                       value="<?php echo e(old('discount_amount', 0)); ?>" min="0" step="0.01" placeholder="0.00">
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Discount Percentage (%)</label>
                                                <input type="number" class="form-control" name="discount_percentage" id="discountPercentage"
                                                       value="<?php echo e(old('discount_percentage')); ?>" min="0" max="100" step="0.01" placeholder="0.00">
                                                <small class="form-text text-muted">Enter percentage or amount (not both)</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card border-success">
                                    <div class="card-header bg-success text-white">
                                        <h5 class="card-title mb-0"><i class="fas fa-calculator"></i> Invoice Summary</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row text-center">
                                            <div class="col-4">
                                                <span>Items:</span>
                                                <span id="summaryItems" class="fw-bold">0</span>
                                            </div>
                                            <div class="col-4">
                                                <span>Total Quantity:</span>
                                                <span id="summaryQuantity" class="fw-bold">0</span>
                                            </div>
                                            <div class="col-4">
                                                <span>Total Amount:</span>
                                                <span id="summaryTotal" class="fw-bold text-primary fs-5">Rs.0.00</span>
                                            </div>
                                        </div>
                                        <div class="row text-center mt-2">
                                            <div class="col-4">
                                                <span>Discount:</span>
                                                <span id="summaryDiscount" class="fw-bold text-danger">-Rs.0.00</span>
                                            </div>
                                            <div class="col-4">
                                                <span>Tax (<span id="taxRateDisplay">0</span>%):</span>
                                                <span id="summaryTax" class="fw-bold text-warning">+Rs.0.00</span>
                                            </div>
                                            <div class="col-4">
                                                <span class="fw-bold">Gross Total:</span>
                                                <span id="summaryGrossTotal" class="fw-bold text-success fs-4">Rs.0.00</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

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

        <!-- Actions Panel - Below Main Content -->
        <div class="col-12 mt-4">
            <!-- Order Summary -->
            

            <!-- Actions -->
            <div class="card">
                <div class="card-body">
                    <button type="button" class="btn btn-success btn-lg w-100 mb-2" onclick="saveOrder()" id="saveBtn">
                        <i class="fas fa-save"></i> Save Order
                    </button>
                    <button type="button" class="btn btn-outline-secondary w-100 mb-2" onclick="clearOrder()">
                        <i class="fas fa-trash"></i> Clear Order
                    </button>
                    <hr class="my-2">
                    <button type="button" class="btn btn-outline-info btn-sm w-100" onclick="window.location.href='<?php echo e(route('factory-pos.index')); ?>'">
                        <i class="fas fa-list"></i> View All Orders
                    </button>
                </div>
            </div>

            <!-- Recent Items -->
            
        </div>
    </div>
</div>

<!-- Item Search Dropdown - REMOVED (using select2 now) -->

<?php $__env->stopSection(); ?>

<?php $__env->startPush('plugin-scripts'); ?>
<script>
let itemCounter = 0;
let selectedItems = new Map();

$(document).ready(function() {
    // Focus on customer selection
    $('[name=customer_id]').focus();

    // Load recent items
    loadRecentItems();
});

// Initialize Select2 for item search
$('#itemSearch').select2({
    theme: 'bootstrap-5',
    placeholder: 'Search finished goods...',
    allowClear: true,
    minimumInputLength: 1,
    ajax: {
        url: '<?php echo e(route("factory-pos.items")); ?>',
        dataType: 'json',
        delay: 300,
        xhrFields: {
            withCredentials: true
        },
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        },
        data: function (params) {
            return {
                q: params.term,
                show_all: false
            };
        },
        processResults: function (data) {
            return {
                results: data.results.map(function(item) {
                    return {
                        id: item.id,
                        text: item.text,
                        name: item.name,
                        sku: item.sku,
                        warehouse_name: item.warehouse_name,
                        warehouse_code: item.warehouse_code,
                        quantity: item.quantity,
                        length: item.length,
                        item_id: item.item_id,
                        warehouse_id: item.warehouse_id,
                        is_meter: item.is_meter,
                        is_foot: item.is_foot
                    };
                })
            };
        },
        cache: true
    }
});

// Handle item selection
$('#itemSearch').on('select2:select', function (e) {
    const data = e.params.data;

    // Parse the compound ID to get item_id, warehouse_id, and length
    const idParts = data.id.split('_');
    const itemId = idParts[0];
    const warehouseId = idParts[1];
    const length = idParts[2] === 'null' ? null : parseFloat(idParts[2]);

    // Check if this is a wire item (you can modify this logic based on your item categorization)
    // const isWire = data.name.toLowerCase().includes('wire') || (data.sku && data.sku.toLowerCase().includes('wire'));
    // const isPipe = data.name.toLowerCase().includes('pipe') || (data.sku && data.sku.toLowerCase().includes('pipe'));
    const isWire = data.is_meter;
    const isPipe = data.is_foot;
    const basePrice = isWire ? <?php echo e(config('app.wire.base_price')); ?> : 0;
    // alert(data.sku);
    // Auto-select warehouse
    $('#orderWarehouse').val(warehouseId).trigger('change');

    addItemRow(itemId, data.name, data.sku, basePrice, isWire, length, warehouseId, data.warehouse_name, isPipe );

    // Clear selection
    $(this).val(null).trigger('change');
});

// searchItems function removed - using select2 AJAX now

// showDropdown function removed - using select2 dropdown now

// hideDropdown function removed - using select2 now

// selectItem function removed - using select2 select event now

function addItem() {
    const query = $('#itemSearch').val();
    if (query.length > 0) {
        searchItems(query, true);
    }
}

function addItemRow(itemId, itemName, sku, price = 0, isWire = false, length = null, warehouseId = null, warehouseName = null, isPipe = false) {
    // Check if item with same warehouse and length already exists
    const itemKey = `${itemId}_${warehouseId}_${length}`;
    if (selectedItems.has(itemKey)) {
        // Item already added, just focus on it
        $(`#qty-${itemKey}`).focus().select();
        return;
    }

    itemCounter++;
    selectedItems.set(itemKey, itemCounter);

    const rowId = `row-${itemCounter}`;
    // const wireClass = isWire ? 'wire-item' : '';
    // const pipeClass = isWire ? 'pipe-item' : '';

    const rowClass = isWire ? 'wire-item' : (isPipe ? 'pipe-item' : '');
    
    let lengthValue = 0;
    let lengthDisplay = 'table-cell'; // Keep it as table-cell or default
    let inputVisibility = (isWire || isPipe) ? 'visible' : 'hidden';

    if (isWire) {
        lengthValue = length !== null ? length : 270;
    } else if (isPipe) {
        lengthValue = length !== null ? length : 10;
    } else {
        lengthValue = 0;
    }

    const row = `
        <tr id="${rowId}" data-item-id="${itemId}" data-warehouse-id="${warehouseId}" data-length="${length}" class="${rowClass}">
            <td>
                <div class="fw-bold" style="word-wrap: break-word; word-break: break-word; white-space: normal; max-width: 100%; overflow-wrap: break-word;">${itemName}</div>
                <small class="text-muted">${sku}</small>
                <br>
                <small class="text-info"><i class="fas fa-warehouse"></i> ${warehouseName}</small>
            </td>
            <td>
                <div style="visibility: ${inputVisibility};">
                    <input type="number" class="form-control length-input" style="width: 100px;" id="length-${itemKey}"
                           value="${lengthValue}" min="0.1" step="0.1" data-item-id="${itemId}" ${isWire || isPipe ? '' : 'disabled'}>
                </div>
            </td>
            <td>
                <input type="number" class="form-control qty-input" style="width: 100px;" id="qty-${itemKey}"
                       value="1" min="1" step="1" data-item-id="${itemId}">
            </td>
            <td>
                <input type="number" class="form-control price-input" style="width: 120px;" id="price-${itemKey}"
                       value="${price}" min="0" step="0.01" data-item-id="${itemId}" ${isWire ? 'readonly' : ''}>
            </td>
            <td class="total-cell fw-bold" id="total-${itemKey}">Rs.0.00</td>
            <td>
                <button type="button" class="btn btn-sm btn-outline-danger"
                        onclick="removeItem('${rowId}', '${itemKey}')">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `;

    $('#itemsBody').append(row);
    updateTotals();

    // Focus on quantity input or warehouse if length is shown
    if (isWire) {
        $(`#length-${itemKey}`).focus().select();
    } else {
        $(`#qty-${itemKey}`).focus().select();
    }
}

function removeItem(rowId, itemKey) {
    $(`#${rowId}`).remove();
    selectedItems.delete(itemKey);
    updateTotals();
}

// Alert function for notifications
function showAlert(message, type = 'info') {
    // Remove existing alerts
    $('.custom-alert').remove();

    // Create alert HTML
    const alertClass = {
        'success': 'alert-success',
        'error': 'alert-danger',
        'warning': 'alert-warning',
        'info': 'alert-info'
    }[type] || 'alert-info';

    const iconClass = {
        'success': 'fas fa-check-circle',
        'error': 'fas fa-exclamation-triangle',
        'warning': 'fas fa-exclamation-circle',
        'info': 'fas fa-info-circle'
    }[type] || 'fas fa-info-circle';

    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show custom-alert" role="alert"
             style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px;">
            <i class="${iconClass} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;

    // Add to body
    $('body').append(alertHtml);

    // Auto-hide success alerts after 5 seconds
    if (type === 'success') {
        setTimeout(function() {
            $('.custom-alert').fadeOut(function() {
                $(this).remove();
            });
        }, 5000);
    }
}

function updateTotals() {
    let grandTotal = 0;
    let totalItems = 0;
    let totalQty = 0;

    $('#itemsBody tr').each(function() {
        const qty = parseFloat($(this).find('.qty-input').val()) || 0;
        const price = parseFloat($(this).find('.price-input').val()) || 0;
        const itemTotal = qty * price;

        $(this).find('.total-cell').text('Rs.' + itemTotal.toFixed(2));

        grandTotal += itemTotal;
        totalItems++;
        totalQty += qty;
    });

    // Calculate discount
    const discountAmount = parseFloat($('#discountAmount').val()) || 0;
    const discountPercentage = parseFloat($('#discountPercentage').val()) || 0;

    let actualDiscount = discountAmount;
    if (discountPercentage > 0) {
        actualDiscount = (grandTotal * discountPercentage) / 100;
        $('#discountAmount').val(actualDiscount.toFixed(2));
    }

    const netTotal = grandTotal - actualDiscount;

    // Calculate tax
    let taxPercentage = 0;
    const selectedInvoiceType = $('#invoiceTypeSelect option:selected');
    if (selectedInvoiceType.length && selectedInvoiceType.val()) {
        taxPercentage = parseFloat(selectedInvoiceType.data('tax-percentage')) || 0;
    }
    
    const taxAmount = (netTotal * taxPercentage) / 100;
    const grossTotal = netTotal + taxAmount;

    $('#grandTotal').text('Rs.' + grandTotal.toFixed(2));
    $('#summaryTotal').text('Rs.' + grandTotal.toFixed(2));
    $('#summaryDiscount').text('-Rs.' + actualDiscount.toFixed(2));
    $('#taxRateDisplay').text(taxPercentage.toFixed(2));
    $('#summaryTax').text('+Rs.' + taxAmount.toFixed(2));
    $('#summaryGrossTotal').text('Rs.' + grossTotal.toFixed(2));
    $('#summaryItems').text(totalItems);
    $('#summaryQuantity').text(totalQty);
    
    // Store tax amount and gross total internally
    $('#posForm').data('tax_amount', taxAmount);
    $('#posForm').data('gross_total', grossTotal);
}

// Form reset function
function resetForm() {
    // Reset customer and employee selections
    $('[name=customer_id]').val('').trigger('change');
    $('[name=supervising_employee_id]').val('').trigger('change');

    // Reset discount fields
    $('#discountAmount').val('');
    $('#discountPercentage').val('');

    // Clear items table
    $('#itemsBody').empty();
    selectedItems.clear();

    // Reset search
    $('#itemSearch').val(null).trigger('change');

    // Reset totals
    updateTotals();

    // Focus on customer selection
    $('[name=customer_id]').focus();
}

// Real-time total calculation
$(document).on('input', '.qty-input, .price-input, .length-input', function() {
    // Auto-calculate price for wire items
    const $row = $(this).closest('tr');
    if ($row.hasClass('wire-item')) {
        const length = parseFloat($row.find('.length-input').val()) || 0;
        const baseLength = <?php echo e(config('app.wire.base_length')); ?>;
        const basePrice = <?php echo e(config('app.wire.base_price')); ?>;

        if (length > 0 && baseLength > 0) {
            const calculatedPrice = (length / baseLength) * basePrice;
            $row.find('.price-input').val(calculatedPrice.toFixed(2));
        }
    }

    // Update totals for this specific row
    const $thisRow = $(this).closest('tr');
    const qty = parseFloat($thisRow.find('.qty-input').val()) || 0;
    const price = parseFloat($thisRow.find('.price-input').val()) || 0;
    const itemTotal = qty * price;
    $thisRow.find('.total-cell').text('Rs.' + itemTotal.toFixed(2));

    updateTotals();
});

// Discount input event listeners
$('#discountAmount, #discountPercentage').on('input', function() {
    // Clear the other field when one is entered
    if ($(this).attr('id') === 'discountAmount' && $(this).val()) {
        $('#discountPercentage').val('');
    } else if ($(this).attr('id') === 'discountPercentage' && $(this).val()) {
        $('#discountAmount').val('');
    }
    updateTotals();
});

// Invoice type change triggers total recalculation (for tax)
$('#invoiceTypeSelect').on('change', function() {
    updateTotals();
});

function clearOrder() {
    if (confirm('Are you sure you want to clear the entire order?')) {
        resetForm();
        showAlert('Order cleared successfully', 'info');
    }
}

function saveOrder() {
    // Validate form
    const invoiceTypeId = $('[name=invoice_type_id]').val();
    const customerId = $('[name=customer_id]').val();
    const employeeId = $('[name=supervising_employee_id]').val();

    if (!invoiceTypeId) {
        showAlert('Please select an invoice type', 'warning');
        $('[name=invoice_type_id]').focus();
        return;
    }

    if (!customerId) {
        showAlert('Please select a customer', 'warning');
        $('[name=customer_id]').focus();
        return;
    }

    if (!employeeId) {
        showAlert('Please select a supervising employee', 'warning');
        $('[name=supervising_employee_id]').focus();
        return;
    }

    if (selectedItems.size === 0) {
        showAlert('Please add at least one item', 'warning');
        $('#itemSearch').focus();
        return;
    }

    // Collect items data
    const items = [];

    $('#itemsBody tr').each(function() {
        const itemId = $(this).data('item-id');
        const warehouseId = $(this).data('warehouse-id');
        const qty = parseFloat($(this).find('.qty-input').val()) || 0;
        const price = parseFloat($(this).find('.price-input').val()) || 0;

        if (qty > 0 && price >= 0) {
            if (!warehouseId) {
                showAlert('Each item must have a warehouse selected.', 'error');
                return false;
            }
            items.push({
                item_id: itemId,
                quantity: qty,
                unit_price: price,
                warehouse_id: warehouseId,
                length: $(this).find('.length-input').val() || null
            });
        }
    });

    if (items.length === 0) {
        showAlert('Please ensure all items have valid quantities and prices', 'warning');
        return;
    }

    // Collect form data
    const formData = {
        invoice_type_id: invoiceTypeId,
        customer_id: customerId,
        supervising_employee_id: employeeId,
        discount_amount: $('#discountAmount').val() || 0,
        discount_percentage: $('#discountPercentage').val() || 0,
        tax_amount: $('#posForm').data('tax_amount') || 0,
        gross_total: $('#posForm').data('gross_total') || 0,
        items: items
    };

    // Disable save button
    const saveBtn = $('#saveBtn');
    saveBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');

    // Show loading alert
    showAlert('Creating invoice...', 'info');

    // Make API call
    $.ajax({
        url: '/api/v1/factory-pos/store',
        method: 'POST',
        data: formData,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            'Accept': 'application/json'
        },
        success: function(response) {
            if (response.success) {
                showAlert(response.message, 'success');

                // Reset form after successful creation
                setTimeout(function() {
                    resetForm();
                    showAlert('Form reset. Ready for new invoice.', 'info');
                }, 2000);
            } else {
                showAlert(response.message || 'Failed to create invoice', 'error');
            }
        },
        error: function(xhr, status, error) {
            let message = 'Failed to create invoice';

            if (xhr.responseJSON && xhr.responseJSON.message) {
                message = xhr.responseJSON.message;
            } else if (xhr.responseJSON && xhr.responseJSON.errors) {
                // Handle validation errors
                const errors = Object.values(xhr.responseJSON.errors).flat();
                message = errors.join(', ');
            }

            showAlert(message, 'error');
        },
        complete: function() {
            // Re-enable save button
            saveBtn.prop('disabled', false).html('<i class="fas fa-save"></i> Save Invoice');
        }
    });
}

function loadRecentItems() {
    // This would load recently used items from localStorage or API
    // For now, just show some sample items
    const recentItems = [
        { id: 1, name: 'Cable Wire 1.5mm', sku: 'CW-001' },
        { id: 2, name: 'Cable Wire 2.5mm', sku: 'CW-002' },
        { id: 3, name: 'Electrical Switch', sku: 'SW-001' }
    ];

    let html = '';
    recentItems.forEach(item => {
        html += `<button type="button" class="btn btn-outline-secondary btn-sm" onclick="selectItem(${item.id}, '${item.name}', '${item.sku}', 0)">${item.name}</button>`;
    });

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

// Click outside handler removed - using select2 now

// Enter key handling removed - using select2 now
</script>
<script src="<?php echo e(asset('theme/vendors/select2/select2.min.js')); ?>"></script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\habibcables-ERP\resources\views/factory-pos/create.blade.php ENDPATH**/ ?>