

<?php $__env->startSection('title', 'Create QC Inspection'); ?>
<?php $__env->startPush('plugin-styles'); ?>
<style>
     .select2-container--bootstrap-5{
        border: 1px solid #e2e8f0;
        border-radius: 6px;
     }
     .select2-selection__rendered{
        padding-top: 1% !important;
    }
    .select2-container .select2-selection--single .select2-selection__rendered{
        padding-top: 2% !important;
    }

    .select2-container .select2-selection--single{
     height: 45px !important;
    }
</style>


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

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Create QC Inspection</h4>
                    <div class="card-tools">
                        <a href="<?php echo e(route('qcs.index')); ?>" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to QC List
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <?php if(session('success')): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle me-2"></i><?php echo e(session('success')); ?>

                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if(session('error')): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i><?php echo e(session('error')); ?>

                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if($errors->any()): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>Please fix the following errors:</strong>
                            <ul class="mb-0 mt-2">
                                <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <li><?php echo e($error); ?></li>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </ul>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <form action="<?php echo e(route('qcs.store')); ?>" method="POST" id="qcForm">
                        <?php echo csrf_field(); ?>

                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">QC Number *</label>
                                <input type="text" name="qc_number" id="qc_number" class="form-control" value="<?php echo e(old('qc_number')); ?>" readonly required>
                                <small class="form-text text-muted">
                                    <i class="fas fa-magic"></i> Auto-generated QC number
                                </small>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Inward Gate Pass (IGP) *</label>
                                <select name="igp_id" id="igp_id" class="form-select" required>
                                    <option value="">Select IGP...</option>
                                </select>
                                <small class="form-text text-muted">Search by IGP number, PO number, or vendor name</small>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Inspector *</label>
                                <select name="inspector_id" id="inspector_id" class="form-select" required>
                                    <option value="">Select Inspector...</option>
                                </select>
                                <small class="form-text text-muted">Select employee inspector</small>
                            </div>
                        </div>
                        <div class="row g-3 mt-2">
                            <div class="col-12">
                                <label class="form-label">Remarks</label>
                                <textarea name="remarks" id="remarks" class="form-control" rows="1" placeholder="Enter any additional remarks"><?php echo e(old('remarks')); ?></textarea>
                            </div>
                        </div>

                        <!-- IGP Details Section -->
                        <div id="igpDetails" class="row mt-3" style="display: none;">
                            <div class="col-12">
                                <div class="card bg-light">
                                    <div class="card-body">
                                        <h6 class="card-title">
                                            <i class="fas fa-info-circle me-2"></i>IGP Details
                                        </h6>
                                        <div class="row">
                                            <div class="col-md-3">
                                                <strong>IGP Number:</strong><br>
                                                <span id="igpNumber" class="text-primary fw-bold"></span>
                                            </div>
                                            <div class="col-md-3">
                                                <strong>PO Number:</strong><br>
                                                <span id="poNumber" class="text-success fw-bold"></span>
                                            </div>
                                            <div class="col-md-3">
                                                <strong>Vendor:</strong><br>
                                                <span id="vendorName" class="text-info fw-bold"></span>
                                            </div>
                                            <div class="col-md-3">
                                                <strong>Date:</strong><br>
                                                <span id="igpDate" class="text-secondary fw-bold"></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- QC Items Section -->
                        <div id="qcItemsSection" class="mt-3" style="display: none;">
                            <h6>QC Items</h6>
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped" id="qcItemsTable">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Item</th>
                                            <th>UOM</th>
                                            <th>IGP Qty</th>
                                            <th>Accepted Qty</th>
                                            <th>Warehouse</th>
                                        </tr>
                                    </thead>
                                    <tbody id="qcItemsBody">
                                        <!-- Items will be loaded here -->
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <div class="d-flex gap-2 mt-4">
                            <button type="submit" class="btn btn-primary" id="submitBtn">
                                <i class="fas fa-save"></i> Submit QC Inspection
                            </button>
                            
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('plugin-styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/select2/select2.min.css')); ?>">
<style>
    .form-control[readonly] {
        background-color: #f8f9fa !important;
        border-color: #dee2e6 !important;
        color: #495057 !important;
        cursor: not-allowed !important;
    }

    .table th {
        font-size: 0.875rem;
        font-weight: 600;
    }

    .table td {
        font-size: 0.875rem;
        vertical-align: middle;
    }

    .accepted-qty {
        text-align: right;
    }

    .accepted-qty:invalid {
        border-color: #dc3545;
        box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
    }

    .accepted-qty.is-invalid {
        border-color: #dc3545;
        box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
    }

    .invalid-feedback {
        display: none;
        width: 100%;
        margin-top: 0.25rem;
        font-size: 0.875em;
        color: #dc3545;
    }

    .invalid-feedback:not(:empty) {
        display: block;
    }

    .table td {
        position: relative;
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('plugin-scripts'); ?>
<script src="<?php echo e(asset('theme/vendors/select2/select2.min.js')); ?>"></script>
<script>
$(document).ready(function() {
    // Generate QC number on page load
    generateQcNumber();

    // Initialize IGP Select2
    $('#igp_id').select2({
        theme: 'bootstrap-5',
        placeholder: 'Search IGP...',
        allowClear: true,
        width: '100%',
        ajax: {
            url: '<?php echo e(route("api.igp.search")); ?>',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    q: params.term || ''
                };
            },
            processResults: function(data) {
                return {
                    results: data.map(function(item) {
                        return {
                            id: item.id,
                            text: item.gate_pass_number + ' - ' + item.po_number + ' (' + item.vendor_name + ')',
                        gate_pass_number: item.gate_pass_number,
                        po_number: item.po_number,
                        vendor_name: item.vendor_name,
                        purchase_order_id: item.purchase_order_id
                        };
                    })
                };
            },
            cache: true
        }
    });

    // Initialize Inspector Select2
    $('#inspector_id').select2({
        theme: 'bootstrap-5',
        placeholder: 'Select Inspector...',
        allowClear: true,
        width: '100%',
        ajax: {
            url: '<?php echo e(route("inspector.search")); ?>',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    q: params.term || '',
                    type: 'employee' // Assuming 'employee' is the type for contacts
                };
            },
            processResults: function(data) {
                return {
                    results: data.results || []
                };
            },
            cache: true
        }
    });

    // IGP selection change
    $('#igp_id').on('change', function() {
        const igpId = $(this).val();
        if (igpId) {
            const selectedData = $(this).select2('data')[0];

            // Populate IGP details with actual data from the selected option
            $('#igpNumber').text(selectedData.gate_pass_number || 'N/A');
            $('#poNumber').text(selectedData.po_number || 'N/A');
            $('#vendorName').text(selectedData.vendor_name || 'N/A');
            $('#igpDate').text(selectedData.date || new Date().toLocaleDateString());
            $('#igpDetails').show();

            // Clear any previous errors
            clearAllErrors();

            // Load IGP items
            loadIgpItems(igpId);
        } else {
            $('#igpDetails').hide();
            $('#qcItemsSection').hide();
            clearAllErrors();
        }
    });

    // Form validation
    $('#qcForm').on('submit', function(e) {
        e.preventDefault(); // Prevent default submission

        if (!validateQcForm()) {
            return false;
        }

        // Disable submit button to prevent double submission
        $('#submitBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Submitting...');

        // Submit the form
        this.submit();
    });
});

// Generate QC number
function generateQcNumber() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    $('#qc_number').val(`QC-${year}${month}${day}-${random}`);
}

// Load IGP items into table
function loadIgpItems(igpId) {
    $.get(`/qcs/igp/${igpId}/items`)
        .done(function(response) {
            if (response.success && response.data && response.data.length > 0) {
                let tableBody = '';
                response.data.forEach((item, index) => {
                    tableBody += `
                        <tr data-item-index="${index}">
                            <td>
                                <input type="hidden" name="items[${index}][purchase_order_item_id]" value="${item.purchase_order_item_id}">

                                <input type="hidden" name="items[${index}][uom_id]" value="${item.uom_id}">
                                <input type="hidden" name="items[${index}][unit_code]" value="${item.unit_code}">
                                <input type="hidden" name="items[${index}][ordered_qty]" value="${item.ordered_qty}">
                                <input type="hidden" name="items[${index}][igp_qty]" value="${item.igp_qty}">
                                <input type="hidden" name="items[${index}][dn_qty]" value="${item.dn_qty}">
                                <input type="hidden" name="items[${index}][bin_id]" value="9">
                                <input type="hidden" name="items[${index}][item_id]" value="${item.item_id}">
                                ${item.item_name}
                            </td>
                            <td>${item.uom_name}</td>
                            <td class="text-end">${item.igp_qty}</td>
                            <td>
                                <input type="number" class="form-control form-control-sm accepted-qty"
                                       name="items[${index}][accepted_qty]"
                                       min="0" max="${item.igp_qty}" step="0.000001"
                                       value="0" onchange="updateRejectedQty(${index})"
                                       onblur="validateAcceptedQty(${index})" required>
                                <div class="invalid-feedback" id="error-${index}"></div>
                            </td>
                            <td>
                                <select name="items[${index}][warehouse_id]" class="form-select form-select-sm warehouse-select">
                                    <option value="">Select Warehouse</option>
                                </select>
                                <small class="form-text text-muted warehouse-help" style="display: none;">
                                    Warehouse required when accepted quantity > 0
                                </small>
                            </td>
                        </tr>
                    `;
                });

                $('#qcItemsTable tbody').html(tableBody);

                // Load warehouses for each dropdown
                loadWarehouses();

                $('#qcItemsSection').show();
            } else {
                alert('No items found for this IGP.');
                $('#qcItemsSection').hide();
            }
        })
        .fail(function() {
            alert('Failed to load IGP items.');
            $('#qcItemsSection').hide();
        });
}

// Load warehouses for each item row
function loadWarehouses() {
    $.get('<?php echo e(route("api.warehouses.index")); ?>')
        .done(function(response) {
            if (response.data && response.data.length > 0) {
                $('.warehouse-select').each(function() {
                    const select = $(this);
                    select.empty().append('<option value="">Select Warehouse</option>');

                    response.data.forEach(function(warehouse) {
                        select.append(`<option value="${warehouse.id}">${warehouse.name}</option>`);
                    });
                });
            } else {
                $('.warehouse-select').each(function() {
                    $(this).empty().append('<option value="">No warehouses available</option>');
                });
            }
        })
        .fail(function(xhr, status, error) {
            $('.warehouse-select').each(function() {
                $(this).empty().append('<option value="">Error loading warehouses</option>');
            });
        });
}

// Update quantities
window.updateRejectedQty = function(itemIndex) {
    const row = $(`[data-item-index="${itemIndex}"]`);
    const acceptedQty = parseFloat(row.find('.accepted-qty').val()) || 0;
    const igpQty = parseFloat(row.find('input[name$="[igp_qty]"]').val()) || 0;
    const input = row.find('.accepted-qty');
    const errorDiv = row.find(`#error-${itemIndex}`);

    // Clear previous error
    input.removeClass('is-invalid');
    errorDiv.text('').hide();

    // Auto-calculate rejected quantity
    const rejectedQty = Math.max(0, igpQty - acceptedQty);

    // Store rejected quantity in hidden field for backend
    row.find('input[name$="[rejected_qty]"]').remove(); // Remove old hidden field if exists
    row.append(`<input type="hidden" name="items[${itemIndex}][rejected_qty]" value="${rejectedQty.toFixed(6)}">`);

    return true;
};

// Validate QC form
function validateQcForm() {
    const igpId = $('#igp_id').val();
    const inspectorId = $('#inspector_id').val();
    let isValid = true;

    // Clear all previous errors
    $('.accepted-qty').removeClass('is-invalid');
    $('.warehouse-select').removeClass('is-invalid');
    $('.invalid-feedback').text('').hide();

    if (!igpId) {
        alert('Please select an IGP first.');
        return false;
    }

    if (!inspectorId) {
        alert('Please select an inspector.');
        return false;
    }

    // Validate each accepted quantity input
    $('.accepted-qty').each(function() {
        const input = $(this);
        const itemIndex = input.closest('tr').data('item-index');
        const acceptedQty = parseFloat(input.val()) || 0;
        const igpQty = parseFloat(input.closest('tr').find('input[name$="[igp_qty]"]').val()) || 0;
        const errorDiv = input.closest('tr').find(`#error-${itemIndex}`);
        const warehouseSelect = input.closest('tr').find('.warehouse-select');

        // Clear previous error
        input.removeClass('is-invalid');
        errorDiv.text('').hide();
        warehouseSelect.removeClass('is-invalid');

        // Validate accepted quantity (no negative values)
        if (acceptedQty < 0) {
            input.addClass('is-invalid');
            errorDiv.text('Accepted quantity cannot be negative').show();
            isValid = false;
        }

        // Validate accepted quantity doesn't exceed IGP quantity
        if (acceptedQty > igpQty) {
            input.addClass('is-invalid');
            errorDiv.text(`Accepted quantity cannot exceed IGP quantity (${igpQty})`).show();
            isValid = false;
        }

        // Validate warehouse selection only if accepted quantity > 0
        if (acceptedQty > 0) {
            if (!warehouseSelect.val()) {
                warehouseSelect.addClass('is-invalid');
                isValid = false;
            } else {
                warehouseSelect.removeClass('is-invalid');
            }
        }
    });

    if (!isValid) {
        return false;
    }

    // Check if at least one item has accepted quantity > 0
    let hasValidItems = false;
    $('.accepted-qty').each(function() {
        const acceptedQty = parseFloat($(this).val()) || 0;
        if (acceptedQty > 0) {
            hasValidItems = true;
            return false; // break loop
        }
    });

    if (!hasValidItems) {
        alert('Please enter accepted quantities greater than 0 for at least one item.');
        return false;
    }

    return true;
}

// Validate individual accepted quantity input
window.validateAcceptedQty = function(itemIndex) {
    const row = $(`[data-item-index="${itemIndex}"]`);
    const input = row.find('.accepted-qty');
    const acceptedQty = parseFloat(input.val()) || 0;
    const igpQty = parseFloat(row.find('input[name$="[igp_qty]"]').val()) || 0;
    const errorDiv = row.find(`#error-${itemIndex}`);
    const warehouseSelect = row.find('.warehouse-select');
    const warehouseHelp = row.find('.warehouse-help');

    // Clear previous error
    input.removeClass('is-invalid');
    errorDiv.text('').hide();
    warehouseSelect.removeClass('is-invalid');

    // Validate accepted quantity (no negative values)
    if (acceptedQty < 0) {
        input.addClass('is-invalid');
        errorDiv.text('Accepted quantity cannot be negative').show();
        return false;
    }

    // Validate accepted quantity doesn't exceed IGP quantity
    if (acceptedQty > igpQty) {
        input.addClass('is-invalid');
        errorDiv.text(`Accepted quantity cannot exceed IGP quantity (${igpQty})`).show();
        return false;
    }

    // Handle warehouse selection based on accepted quantity
    if (acceptedQty > 0) {
        // If accepted quantity > 0, show warehouse help text
        warehouseHelp.show();
        warehouseSelect.addClass('border-warning');
    } else {
        // If accepted quantity is 0 or null, hide warehouse help and clear selection
        warehouseHelp.hide();
        warehouseSelect.removeClass('border-warning');
        warehouseSelect.val(''); // Clear warehouse selection
    }

    return true;
};

// Clear all validation errors
window.clearAllErrors = function() {
    $('.accepted-qty').removeClass('is-invalid');
    $('.invalid-feedback').text('').hide();
};
</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\qcs\create.blade.php ENDPATH**/ ?>