                     <div class="row">
                        <div class="col-sm-11">
                            <div class="page-title-box">
                                    <h2 class="page-title">Map SKUs</h2>
                            </div><!--end page-title-box-->
                        </div><!--end col-->
                        <div class="col-sm-1">
                            <div class="page-title-box">
                                    <h2 class="page-title"><a href="vendor_list"><button  class='btn btn-danger' type="button">Back</button></a></h2>
                            </div><!--end page-title-box-->
                        </div><!--end col-->
                    
                    </div>
                    
                    <div class="row" >
                        <div class="col-sm-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                             <table id="example" class="display table table-hover table-condensed" cellspacing="0" width="100%">
                                                <thead>
                                                    <tr>
                                                        <th><?php echo '#'; ?></th>
                                                        <th><?php echo 'Name'; ?></th>
                                                        <th><?php echo 'Brand'; ?></th>
                                                        <th><?php echo 'Unit Name'; ?></th>
                                                        <th><?php echo 'Price'; ?></th>
                                                        <th><?php echo 'Map'; ?>&nbsp&nbsp<input type="checkbox" id="select_all"></th>
                                                    </tr>
                                                </thead>

                                                <tbody>
                                                    <?php $x=1;
                                                        foreach ($users as $user): 
                                                            if($user[0]['vendor_price']){
                                                                $price=$user[0]['vendor_price'];
                                                                $isChecked=true;
                                                            }else{
                                                                $price=$user['inventory_skus']['price'];
                                                                $isChecked=false;
                                                            }
                                                    ?>
                                                    <tr>
                                                        <td><?php print_r($x);?></td>
                                                        <td><?php print_r($user['inventory_skus']['name']);?></td>
                                                        <td><?php print_r($user['inventory_skus']['brand']);?></td>
                                                        <td><?php print_r($user['inventory_skus']['unit_name']);?></td>
                                                        <td><?php echo $this->Form->input('price', array(
                                                                'class' => 'form-control',
                                                                'label' => '',
                                                                'required' => 'required',
                                                                'type' => 'number',
                                                                'style' => 'width:auto',
                                                                'value'=>$price,
                                                                'id' => 'price_' . $user['inventory_skus']['id'],
                                                                'step' => 'any'
                                                            )); ?>
                                                        </td>
                                                        <input type="hidden" name='vendor_id' id="vendor_id" value="<?php echo $id;?>">
                                                        <input type="hidden" name='sku_id' id="sku_id_<?php echo htmlspecialchars($user['inventory_skus']['id']); ?>" value="<?php echo $user['inventory_skus']['id'];?>">
                                                        <input type="hidden" name='sku_name' id="sku_name_<?php echo htmlspecialchars($user['inventory_skus']['id']); ?>" value="<?php echo $user['inventory_skus']['name'];?>">
                                                        <input type="hidden" name='sku_brand' id="sku_brand_<?php echo htmlspecialchars($user['inventory_skus']['id']); ?>" value="<?php echo $user['inventory_skus']['brand'];?>">
                                                        <input type="hidden" name='unit_name' id="unit_name_<?php echo htmlspecialchars($user['inventory_skus']['id']); ?>" value="<?php echo $user['inventory_skus']['unit_name'];?>">
                                                        <input type="hidden" name='unit_id' id="unit_id_<?php echo htmlspecialchars($user['inventory_skus']['id']); ?>" value="<?php echo $user['inventory_skus']['unit'];?>">
                                                        <td><input type="checkbox" class="checkbox"  id="seltask_<?php echo htmlspecialchars($user['inventory_skus']['id']); ?>" <?php echo $isChecked ? 'checked' : ''; ?>></td>
                                                    </tr>
                                                    <?php $x++;endforeach; ?>            
                                                </tbody>
                                            </table><br>
                                            <button onclick="resetAllMappings()" class="btn btn-warning" id="resetbtn" style="float:right; margin-right:8px;">Reset All</button>
                                            <button onclick="getCheckedCheckboxes()" class="btn btn-success" id="dltbtn" style="float:right;">Map Selected SKUs</button>
                                        </div>
                                    </div>
                                </div>
                            </section>
                        </div>
                    </div>
                </div>
            </div> 
        </div>
                    

<script>

    $(document).ready(function() {

$('#select_all').click(function() {
    
            var checked = this.checked;
            if(checked==true){
                var skurows = $("#example").dataTable().fnGetNodes();
                for(var i=0;i<skurows.length;i++){
    	            $(skurows[i]).find('input');
    	            var inputdata=$(skurows[i]).find('input');
    	            $(inputdata[7]).prop( "checked", true );
    
                }
            }else{
                var skurows = $("#example").dataTable().fnGetNodes();
                for(var i=0;i<skurows.length;i++){
    	            $(skurows[i]).find('input');
    	            var inputdata=$(skurows[i]).find('input');
    	            $(inputdata[7]).prop( "checked", false );
    
                }
            }
        });
    });
        
        
  function getCheckedCheckboxes() {

      var skurows = $("#example").dataTable().fnGetNodes();
var checkedData =[];
	
	for(var i=0;i<skurows.length;i++){
	
		var inputdata=$(skurows[i]).find('input');
		var currentSkuPrice = inputdata[0].value.trim();
		var currentvendorid = inputdata[1].value.trim();
		var currentSkuId = inputdata[2].value.trim();
		var currentSkuname = inputdata[3].value.trim();
		var currentSkubrand = inputdata[4].value.trim();
		var currentSkuunitname = inputdata[5].value.trim();
		var currentSkuunitid = inputdata[6].value.trim();
		if(($(inputdata[7]).prop("checked") == true) && (currentSkuPrice!="" && currentSkuPrice!="0")){
			checkedData.push({
                sku_name: currentSkuname,
                sku_brand: currentSkubrand,
                unit_name: currentSkuunitname,
                unit_id: currentSkuunitid,
                vendor_id: currentvendorid,
                id: currentSkuId,
                price: currentSkuPrice
            });
        }
	}
	
    // C9: Disable button and show spinner to prevent double-submit
    var $btn = $('#dltbtn');
    if ($btn.data('submitting')) return;
    $btn.data('submitting', true).prop('disabled', true)
        .html('<span class="spinner-border spinner-border-sm" role="status"></span> Mapping...');

	$.ajax({
        url: '<?php echo $this->Html->url(['controller' => 'dashboard', 'action' => 'map_vendor_with_sku']); ?>',
        type: 'POST',
        data: { checkedData: JSON.stringify(checkedData), vendor_id_reset: '<?php echo (int)$id; ?>' },
        success: function(response) {
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: 'Skus Mapped Successfully',
                confirmButtonColor: '#3085d6',
                confirmButtonText: 'OK'
            }).then(() => {
			
				window.location.href = '<?php echo $this->Html->url(['controller' => 'dashboard', 'action' => 'vendor_list']); ?>';

            });
        },
        error: function(xhr, status, error) {
            // Re-enable on error so user can retry
            $btn.data('submitting', false).prop('disabled', false).html('Map Selected SKUs');
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'An error occurred: ' + error,
                confirmButtonColor: '#d33'
            });
        }

    });
}

function resetAllMappings() {
    Swal.fire({
        title: 'Reset all mapped SKUs?',
        text: 'This will remove all current SKU mappings for this vendor.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, reset'
    }).then(function(result) {
        if (result.isConfirmed) {
            $.ajax({
                url: '<?php echo $this->Html->url(['controller' => 'dashboard', 'action' => 'map_vendor_with_sku']); ?>',
                type: 'POST',
                data: { checkedData: JSON.stringify([]), vendor_id_reset: '<?php echo (int)$id; ?>' },
                success: function() {
                    Swal.fire('Reset!', 'All SKU mappings cleared.', 'success')
                        .then(function() {         window.location.href = '<?php echo $this->Html->url(['controller' => 'dashboard', 'action' => 'vendor_list']); ?>';
 });
                },
                error: function(xhr) {
                    Swal.fire('Error', 'Reset failed. Please try again.', 'error');
                }
            });
        }
    });
}

</script>
                