<?php $__env->startSection('content'); ?>
<style type="text/css">
	.orderbadge{border-radius: 0.15rem; font-size: 1rem; font-weight: initial; line-height: 1; padding: 0.45rem 0; font-family: 'Quicksand', sans-serif; font-weight: 600; width: 100px; text-align: center;}

	.pnd{background-color: #fd3258; color: #fff}
	.pcd{background-color: #024b7a; color: #fff}
	.shp{background-color: #ff4242; color: #fff}
	.dlv{background-color: #098329; color: #fff}
	.hld{background-color: #f7822f; color: #fff}
	.cnl{background-color: #6e6e6e; color: #fff}

	.dd-flex {
	    display: flex !important;
	    gap: 100px;
	}

	.Bill-del-date {
	    background: #eeeeee;
	    padding: 10px;
	}
	.mt-4 {
	    margin-top: 1.5rem !important;
	}

	.messnote, .error {
	    color: red;
	    font-weight: bold;
	}

</style>
<main id="main" class="main">
    <div class="container">
        <div>
            <p><b>Order Id : <?php echo e($order->unique_order_id); ?></b></p> 
        </div>
        <p> Purchase Date : <?php echo e(date('d/m/Y' , strtotime($order->created_at))); ?></p>
        <?php if($user!=''): ?>
        	<div style="text-align: right;" class="processed-btn2">
                Customer Email : <a href="mailto:<?php echo e($user->email); ?>" style="color: blue"><?php echo e($user->email); ?></a>
            </div>
        <?php endif; ?>	
        <p>
		    <?php if($order->order_delivery_status=='P'): ?>
		        <div class="orderbadge pnd">PENDING</div>
		    <?php elseif($order->order_delivery_status=='PC'): ?>
		        <div class="orderbadge pcd">PROGRESS</div>
		    <?php elseif($order->order_delivery_status=='CL'): ?>
		        <div class="orderbadge cnl">CANCEL</div>
		    <?php elseif($order->order_delivery_status=='H'): ?>
		        <div class="orderbadge hld">HOLD</div>
		    <?php elseif($order->order_delivery_status=='D'): ?>
		        <div class="orderbadge dlv">DELIVERED</div>
		    <?php elseif($order->order_delivery_status=='S'): ?>
		        <div class="orderbadge shp">Shipped</div>
		    <?php endif; ?>
		</p>

        <div class="Bill-del-date dd-flex mt-4">
        	<div>
        	<P style="font-size: 20px;">Delivery Address</P>
	        	<?php if($order->delivery_user_name != NULL): ?>
				    <div>
				        <strong><?php echo $order->delivery_user_name; ?></strong><br>
	                    <?php echo $order->delivery_address; ?>,<br>
	                    <?php echo $order->delivery_country; ?>,<br>
	                    <?php echo $order->delivery_city; ?>,<br>
	                    <?php echo $order->delivery_state; ?> - <?php echo $order->delivery_pincode; ?><br>
	                    <?php echo $order->delivery_mobile; ?>

				    </div>
				<?php else: ?>
					NA    
				<?php endif; ?>
			</div>
			<div>	
			<P style="font-size: 20px;">Billing Address</P>	
				<?php if($order->billing_user_name != NULL): ?>    
				    <div>
				    	<strong><?php echo $order->billing_user_name; ?></strong><br>
	                    <?php echo $order->billing_address; ?>,<br>
	                    <?php echo $order->billing_country; ?>,<br>
	                    <?php echo $order->billing_city; ?>,<br>
	                    <?php echo $order->billing_state; ?> - <?php echo $order->billing_pincode; ?><br>
	                    <?php echo $order->billing_mobile; ?>

				    </div>
				<?php else: ?>
					NA     
				<?php endif; ?>
			</div>	
				
			<div>	
			<P style="font-size: 20px;">Message Section</P>
				<?php if($order_messages!=''): ?>
					<div>
			            Message Purpose : <?php echo e($order_messages->message_purpose); ?><br>
			            Sender Message : <?php echo e($order_messages->sender_message); ?><br>
			            Sender Name : <?php echo e($order_messages->sender_name); ?><br>
			            Special Instruction : <?php echo e($order_messages->sender_special_instruction); ?><br><br>

			            <?php if($order_messages->sender_demand != ''): ?>
		                    <div class="messnote">
		                    **Note: <?php echo e($order_messages->sender_demand); ?>

		                    </div>
		                <?php endif; ?>
		        	</div>
		        <?php else: ?>
					NA     
		        <?php endif; ?>
		    </div>        
		</div>
		<br>
        <table class="table">
            <thead>
                <tr>
                    <th>Sr No</th>
                    <th>Product Name</th>
                    <th>Send to</th>
                    <th>Price</th>
                    <th>Quantity</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <?php $i=0 ?>
                <?php $grandtotal = 0 ?>
                <?php $__currentLoopData = $order_details; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $order_detail): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php if($order->id == $order_detail->order_id): ?>
                        <?php $__currentLoopData = $product; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $products): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php if($order_detail->product_id == $products->id): ?>
                                <?php $i++; ?>
                                <tr>
                                    <td><?php echo e($i); ?></td>
                                    <td><?php echo e($products->product_name); ?></td>
                                    <td><?php echo e($order->delivery_address); ?></td>
                                    <td><?php echo e($order_detail->total_price); ?></td>
                                    <td><?php echo e($order_detail->qty); ?></td>
                                    <td><?php echo e($order_detail->qty * $order_detail->unit_price); ?></td>
                                </tr>
                                <?php $grandtotal += $order_detail->total_price ?>
                            <?php endif; ?>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    <?php endif; ?>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </tbody>
        </table>
        <div style="text-align:right">
            <p><b>Grand Total :</b><?php echo e($grandtotal); ?></p>
        </div>

        <?php if($disable >= 1): ?>

        <?php else: ?>
        <div class="product_content">
            <h3>Assign Agent</h3>
            <form action="<?php echo e(url('/admin/orders/view/')); ?>/<?php echo e($order->id); ?>" method="post">
                <?php echo csrf_field(); ?>
                
                <!-- Appended Products -->
                <div id="appendedProduct"></div>
                
                <!-- Form Footer -->
                <table class="table">
                    <tbody>
                        <tr>
                            <td colspan="2" style="text-align:right;">
                                <button class="btn btn-primary addAgent" type="button">Add Agent</button>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <div id="totalValue" style="margin-bottom:10%;display:none;">
                    <b>TOTAL CHARGES : </b><input class="form-control" name="total" id="total"/>
                </div>
                <input class="form-control" type="hidden" name="OrderID" value="<?php echo e($order->unique_order_id); ?>"/>
                <input class="form-control" type="hidden" name="OrderOriginalID" value="<?php echo e($order->id); ?>"/>

                <div id="button_assign"><button class="btn btn-primary" type="submit" id="btn_assign"  style="display:none;">ASSIGN</button></div>
            </form>

	    <?php endif; ?>
	        
	        <?php if($disable == 0): ?>
		    <?php else: ?>
		        <h2 style="margin-top: 5%;">Processed Order</h2>
		        <?php
		        	$mailDisable = 0;
		            $groupedData = [];
		            foreach ($assinged as $assignedItem) {
		                foreach ($assigned_agent_product_map as $assigned_agent_product_maps) {
		                    if ($assignedItem->id == $assigned_agent_product_maps->agent_assinged_id) {
		                        $agent = $agents->firstWhere('id', $assignedItem->agent_id);
		                        $productItem = $product->firstWhere('id', $assigned_agent_product_maps->product_id);
		                        $productMapedItem = $agent_product_list->firstWhere('id', $assigned_agent_product_maps->product_id);
		                        if ($productItem && $agent) {
		                            $agentId = $assignedItem->agent_id;

		                            if (!isset($groupedData[$agentId])) {
		                                $groupedData[$agentId] = [
		                                    'products' => [],
		                                    'mapped_details' => [],
		                                    'OrderID' => $assignedItem->id,
		                                    'agent_order_id' => $assignedItem->agent_order_id,
		                                    'totalPrice' => $assignedItem->totalPrice,
		                                    'status' => $assignedItem->status,
		                                    'agent_name' => $agent->name,
		                                    'extra' => $assignedItem->extra,
		                                    'Deliver_charge' => $assignedItem->Deliver_charge,
		                                    'reason' => $assignedItem->reason,
		                                    'track_no' => $assignedItem->track_no,
		                                    'isConfirmCl' => $assignedItem->isConfirmCl
		                                ];
		                            }

		                            $groupedData[$agentId]['products'][] = $productItem->product_name;
		                            $groupedData[$agentId]['mapped_details'][] = $productMapedItem->item;
		                        }
		                    }
		                }
		            }
		         

		        ?>
			        <table class="table">
			            <thead>
			                <tr>
			                    <th>Sr No</th>
			                    <th>Order Id</th>
			                    <th>Product Name (Mapped Details)</th>
			                    <th>Assigned Agent Name</th>
			                    <th>Delivery Price</th>
			                    <th>Extra</th>
			                    <th>Delivery Charge</th>
			                    <th>Reason</th>
			                    <th>Track No</th>
			                    <th>Status</th>
			                </tr>
			            </thead>
			            <tbody>
			                <?php $i = 1; ?>
			                <?php 
				                $Delivery_Price = 0;	
				                $Extra = 0;
				                $Delivery = 0; 
				                $total = 0;
			                ?>
			                <?php $__currentLoopData = $groupedData; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $data): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
			                    <tr>
			                        <td><?php echo e($i++); ?></td>
			                        <td><?php echo e($data['agent_order_id']); ?></td>
			                        <td>
			                            <?php echo implode('<br>', $data['mapped_details']); ?>

			                        </td>
			                        <td><?php echo e($data['agent_name']); ?></td>
			                        <td><?php echo e($data['totalPrice']); ?></td>
			                        <td><?php echo e($data['extra']); ?></td>
			                        <td><?php echo e($data['Deliver_charge']); ?></td>
			                        <td><?php echo e($data['reason']); ?></td>
			                        <td><?php echo e($data['track_no']); ?></td>
			                        <td>
			                            <?php if($data['status'] == 'P'): ?>

			                                <div class="alert alert-danger" role="alert" style="width: 100%; text-align: center;">PENDING</div>
			                            <?php elseif($data['status'] == 'PC'): ?>
			                             	<?php $mailDisable++; ?>
			                                <div class="alert alert-secondary" role="alert" style="width: 100%; text-align: center;">PROGRESS</div>
			                            <?php elseif($data['status'] == 'CL'): ?>
			                                <div class="alert alert-info" role="alert" style="width: 100%; text-align: center;">CANCEL</div>
			                            <?php elseif($data['status'] == 'H'): ?>
			                                <div class="alert alert-dark" role="alert" style="width: 100%; text-align: center;">HOLD</div>
			                            <?php elseif($data['status'] == 'S'): ?>
                                        	<?php $mailDisable++; ?>
			                                <div class="alert alert-success" role="alert" style="width: 100%; text-align: center;">Shipped</div>
			                            <?php elseif($data['status'] == 'D'): ?>
			                            	<?php $mailDisable++; ?>
			                                <div class="alert alert-success" role="alert" style="width: 100%; text-align: center;">DELIVERED</div>
			                            <?php endif; ?>
			                        </td>
			                        <td>
			                            <?php if($data['isConfirmCl'] == 0 && $data['status'] == "CL"): ?>
			                                <button class="btn btn-primary btn_cancel" id="btn_cancel" ds-value="<?php echo e($data['OrderID']); ?>">Add Agent</button>
			                            <?php endif; ?>
			                        </td>
			                    </tr>
			                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
			            </tbody>
			        </table>
			        <?php $__currentLoopData = $groupedData; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $amount): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
			            <?php if($amount['isConfirmCl'] != 1 && $amount['status'] != "CL"): ?>
			                <!-- <?php echo e($amount['totalPrice']); ?> = <?php echo e($amount['extra']); ?> = <?php echo e($amount['Deliver_charge']); ?> -->
			                 <!-- <br> -->
			                <?php    
			                    $total +=$amount['totalPrice'] + $amount['extra'] + $amount['Deliver_charge'];
			                ?>
			             <?php endif; ?>
			        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

			        <div id="ReassignProduct"></div>

			        	<?php if($order->order_delivery_status != 'D'): ?>
						    <?php if($disable == $mailDisable): ?>
						        <h3>Customer Email</h3>
						            <?php 
						                $count = 0; 
						                $buttonEnable = count($agentasGroupBy) + 1;
						                $buttonCount = 1; 
						            ?>

						            <?php $__currentLoopData = $agentasGroupBy; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $assign): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
						                <?php if($assign->status != 'P'): ?>
						                    <?php 
						                        $count++; 
						                        $buttonCount++; 
						                    ?>                      
						                <?php endif; ?>
						            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

						            <table class="table">
						                <tbody>
						                    <tr>
						                        <?php if($count > 0): ?>
						                            <td>
						                                <select name="mail_status" id="mail_status" class="form-control mail_status">
						                                <option value="">Select Mail Process</option>
						                                    <?php if($order->order_delivery_status == 'P'): ?>
						                                        <option value="PC">Progress</option>
						                                        <option value="S">Shipped</option>
						                                        <option value="D">Delivered</option>
						                                    <?php elseif($order->order_delivery_status == 'PC'): ?>
						                                        <option value="S">Shipped</option>
						                                        <option value="D">Delivered</option>
						                                    <?php elseif($order->order_delivery_status == 'S'): ?>
						                                        <option value="D">Delivered</option>
						                                    <?php endif; ?>

						                                </select>
						                            </td>
						                        <?php endif; ?>
						                        <td>
						                  
						                        </td>
						                        <?php if($buttonCount == $buttonEnable): ?>
						                            <td>
						                            <button class="btn btn-primary" id="btn_mail_send" <?php if($order->order_delivery_status == 'D'): ?> Style="display:none;" <?php else: ?> <?php endif; ?>>SEND</button>
						                            </td>
						                        <?php endif; ?>
						                    </tr>
						                </tbody>
						            </table>
						    <?php endif; ?>
						<?php endif; ?>            
		            <?php $grandTotal = 0; ?>
		            <?php if($order->order_delivery_status == 'D'): ?>
		                <?php 
		                	$grandTotal = $Delivery_Price+$Extra+$Delivery+$total;
		                ?>
		                <p><b>Paid To Agent :  <?php echo e($total); ?></b></p>
		            <?php endif; ?>
		            <?php if($order->order_delivery_status == 'PC'): ?>
		                <table class="table" style="display:none;" id="AssignIds">
		                    <thead>
		                        <tr>
		                            <th></th>
		                        </tr>
		                    </thead>
		                    <tbody>
		                        <?php $__currentLoopData = $agentasGroupBy; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $assignItems): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
		                            <?php if($assignItems->status == "CL"): ?>
		                            <?php else: ?>
		                            <tr>
		                                <td>
		                                    <input class="form-control" name="OrderId" value="<?php echo e($assignItems->agent_order_id); ?>" disabled/>
		                                </td>
		                                <td>
		                                    <input class="form-control" name="track_no" value="<?php echo e($assignItems->track_no); ?>" />
		                                </td>
		                            </tr>
		                            <?php endif; ?>
		                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
		                    </tbody>
		                </table>
		            <?php endif; ?>	  			
	    	<?php endif; ?>
    	</div>
    </div>
</main>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<script>
	$(document).ready(function(){
	    $(document).on('click', '.addAgent', function(e) {
	        e.preventDefault();

	    	let isFormAppended = 0; // Flag to track if form has been appended    

	        // Collect all selected values
		    selectedValues = [];
		    let allAgentsSelected = true; // Flag to check if all agents are selected

		    $('.getAgentId').each(function () {
		        const value = $(this).val();
		        // const value = $('.getAgentId option[disabled]:selected').val();

				// var opt = $('.getAgentId option[disabled]:selected').val();
				// alert(value);

		        selectedValues.push(value);
		        if (!value) { // If any select has no value, set the flag to false
		            allAgentsSelected = false;
		        }
		    });

		    // If not all agents are selected, show an alert and prevent form appending
		    if (!allAgentsSelected) {
		        alert('Please select an agent before adding a new one.');
		        return; // Prevent the form from being appended
		    }


		    //     selectedValues = [];
		    //     let allAgentsSelected = true; 
		        
		    //     $('.getAgentId').each(function () {
		    //         selectedValues.push($(this).val());
		    //     });

		    //     // console.log(selectedValues); 

		    // if (selectedValues === 0) {    

				var agentIndex = $('#appendedProduct .AgentAssigndProduct').length;

				// console.log(agentIndex);

		            $.ajax({
		                url: "<?php echo e(url('/admin/getAgentId')); ?>", 
		                type: 'GET',
		                data: { 
		                	// agent_id: agent_id,
		                	agentsArray: selectedValues,
							agentIndex:agentIndex,
		                },
		                success: function(response) {

		                	console.log(response);
							var agentIndex = response.agentIndex;
							var allAgents = response.agents; 

							$.each(allAgents, function(index, agent) {  
								console.log(agent.id);
							});

							// Check if the form has already been appended
						    if (isFormAppended==allAgents.length) {
						        alert('All agents are selected.');
						        return; // Prevent further action
						    }

							var agentHTML = `
								<table class="table AgentAssigndProduct tab${agentIndex}">
									<thead>
										<tr>
											<th>Agent</th>
											<th>Details</th>
										</tr>
									</thead>
									<tbody>
										<tr>
											<td>
												<select name="agents[${agentIndex}][agent_id]" class="form-control agent-select getAgentId" data-id="${agentIndex}" required>   
													<option value="">Select Agent</option>`; 

													allAgents.forEach(function(agent) {
								                        agentHTML += `<option value="${agent.id}">${agent.name}</option>`;
								                    });

								        agentHTML += `              
												</select>
											</td>
											<td>
												<table class="table">
													<thead>
														<tr>
															<th>Product</th>
															<th>Price</th>
															<th>QTY</th>
															<th>Action</th>
														</tr>
													</thead>
													<tbody class="AppendPrice">
														<tr class="default-row">
															<td>
																<select name="agents[${agentIndex}][0][products][]" class="form-control product-select" data-agent-index="${agentIndex}" data-product-index="0" required>
																	<option value="">Please Select Agent First</option>
																</select>
															</td>
															<td>
																<input class="form-control product_price" name="agents[${agentIndex}][0][product_prices][]" required />
															</td>
															<td>
																<input class="form-control product_qty" name="agents[${agentIndex}][0][product_qty][]" value="1" required/>
															</td>
															<td>
																<button class="btn btn-success btn_addProduct" data-agent-index="${agentIndex}">(+)</button>
															</td>
														</tr>
													</tbody>
												</table>
											</td>
										</tr>
										<tr>
											<td></td>
											<td>
												<table class="table TotalProductPrice">
													<thead>
														<tr>
															<th>Delivery Type</th>
															<th>Price</th>
															<th>Total Price</th>
														</tr>
													</thead>
													<tbody>
														<tr>
															<td>
																<select name="agents[${agentIndex}][delivery_type]" class="form-control deliveryType" data-agent-index="${agentIndex}" required>
																	<option value="" selected>Select Delivery Type</option>
																	<option value="s_delivery">STANDARD</option>
																	<option value="m_delivery">MIDNIGHT</option>
																</select>
															</td>
															<td>
																<input class="form-control delivery_type_price" name="agents[${agentIndex}][delivery_type_price]" required/>
															</td>
															<td>
																<input class="form-control totalprice" name="agents[${agentIndex}][total_price]" required/>
															</td>
															
														</tr>
													</tbody>
												</table>
											</td>
										</tr>
									</tbody>`;

									if(agentIndex>0){

										agentHTML += `<td colspan="2" style="text-align:right;">
				                                <button class="btn btn-danger removeAgent" type="button">Remove</button>
				                            </td>`;
			                        }
									agentHTML += `</table>`;

							$('#appendedProduct').append(agentHTML);
							$('#btn_assign').css('display', 'block');

							// Set the flag to indicate the form has been appended
            				isFormAppended++;
		                },
		                error: function(error) {
		                    console.log("Error fetching agents:", error);
		                }
		            });
	    });

		// // Prevent form submission if any agent selection is missing
		// $('form').on('submit', function(e) {
		//     let isValid = true;

		//     // Check if all agent dropdowns are selected
		//     $('.getAgentId').each(function () {
		//         if (!$(this).val()) {
		//             isValid = false;
		//         }
		//     });

		//     if (!isValid) {
		//         e.preventDefault(); // Prevent form submission
		//         alert('Please ensure all agents are selected before submitting.');
		//     }
		// });
		
	    $(document).on('change', '.agent-select', function() {
	        // var agentIndex = $(this).data('id');
	        // var agent_id = $(this).val();
	        $(this).prop('disabled', true);
	        // var agent_id = $('.agent-select option[disabled]:selected').val();
	        var agent_id = $(this).val();
	        var agentIndex = $(this).data('id');
	        // alert(agent_id);

	  		//$(this).find('option').prop('disabled',false);  
			// $(this).find('option[value="'+$(this).val()+'"]').prop('disabled',true);

			// var opt = $('.agent-select option[disabled]:selected').val();
			// // alert(opt);
			// $(this).attr('disabled', true);
			// agent_id=opt;
			

	        var $selectProduct = $(`select[name="agents[${agentIndex}][0][products][]"]`);
	        $selectProduct.html('<option value="">Loading...</option>');

	        if (agent_id) {
	            $.ajax({
	                url: "<?php echo e(url('/admin/ProductByAgent')); ?>", 
	                type: 'GET',
	                data: { agent_id: agent_id },
	                success: function(response) {
	                    var products = response;
	                    $selectProduct.html('<option value="">Select Product</option>'); 
	                    products.forEach(function(product) {
	                        $selectProduct.append(`<option value="${product.id}">${product.item}</option>`);
	                    });
	                },
	                error: function(error) {
	                    console.log("Error fetching products:", error);
	                }
	            });
	        } else {
	            $selectProduct.html('<option value="">Select Agent First</option>');
	        }
	    });

	    $('form').on('submit', function(e) {
		    $('.agent-select').prop('disabled', false); // Re-enable fields
		});

	    $(document).on('change', '.product-select', function() {
	        var agentIndex = $(this).data('agent-index'); 
	        var productIndex = $(this).data('product-index'); 
	        var product_id = $(this).val(); 
	        
	        var $totalPrice = $(`input[name="agents[${agentIndex}][${productIndex}][product_prices][]"]`);

	        if (product_id) {
	            $.ajax({
	                url: "<?php echo e(url('/admin/GetPriceByProduct')); ?>",  
	                type: 'GET',
	                data: { product_id: product_id },
	                success: function(response) {
	                    $totalPrice.val(response.price);
	                },
	                error: function(error) {
	                    console.log("Error fetching price:", error);
	                }
	            });
	        }
	    });

	    $(document).on('click', '.btn_addProduct', function(e) {
	        e.preventDefault();

	        var $thisButton = $(this); 
	        var agentIndex = $thisButton.data('agent-index'); 
	        var productIndex = $thisButton.closest('.AppendPrice').find('tr').length;
	        var agent_id = $(`[name="agents[${agentIndex}][agent_id]"]`).val();

	        if (agent_id) {
	            $.ajax({
	                url: "<?php echo e(url('/admin/ProductByAgent')); ?>", 
	                type: 'GET',
	                data: { agent_id: agent_id },
	                success: function(response) {
	                    var productRow = `
	                        <tr>
	                            <td>
	                                <select name="agents[${agentIndex}][${productIndex}][products][]" class="form-control product-select" data-agent-index="${agentIndex}" data-product-index="${productIndex}">
	                                    <option value="">Select Product</option>`;
	                    
	                    response.forEach(function(product) {
	                        productRow += `<option value="${product.id}">${product.item}</option>`;
	                    });

	                    productRow += `
	                                </select>
	                            </td>
	                            <td>
	                                <input class="form-control" name="agents[${agentIndex}][${productIndex}][product_prices][]" />
	                            </td>
	                            <td>
	                                <input class="form-control product_qty" name="agents[${agentIndex}][${productIndex}][product_qty][]" value="1"/>
	                            </td>
	                            <td>
	                                <button class="btn btn-danger btn_removeProduct">(-)</button>
	                            </td>
	                        </tr>`;

	                    $thisButton.closest('.AppendPrice').append(productRow); 
	                },
	                error: function(error) {
	                    console.log("Error fetching products:", error);
	                }
	            });
	        } else {
	            alert("Please select an agent first.");
	        }
	    });

	    $(document).on('click', '.btn_removeProduct', function(e) {
	        e.preventDefault();
	        $(this).closest('tr').remove(); 
	    });

	    // $(document).on('click', '.removeAgent', function(e) {
	    //     e.preventDefault();
	    //     // $(this).closest('tr').remove(); 
	    //     $('.AgentAssigndProduct').remove();
	    // });

	    document.addEventListener('click', function (e) {
		    // Check if the clicked element has the class 'removeAgent'
		    if (e.target && e.target.classList.contains('removeAgent')) {
		        // Get the closest table to the clicked button
		        const agentTable = e.target.closest('.AgentAssigndProduct');
		        
		        // Check if the table has a class like 'tab1', 'tab2', 'tab3', etc.
		        if (agentTable && !agentTable.classList.contains('tab0')) {
		            // Remove the table if it's not 'tab0'
		            agentTable.remove();
		        } else {
		            // Optionally, you can show an alert if trying to delete tab0
		            alert("You cannot remove the first agent table.");
		        }
		    }
		});

	    $(document).on('change', '.deliveryType', function() {
	        var $this = $(this);
	        var agentIndex = $this.data('agent-index'); 
	        var Dtype = $this.val(); 
	        var agent_id = $(`[name="agents[${agentIndex}][agent_id]"]`).val();
	        // var agent_id = $('.agent-select option[disabled]:selected').val();
	        // alert(agent_id);
	        var $totalPrice = $(`input[name="agents[${agentIndex}][delivery_type_price]"]`); 
	        var $total = $(`input[name="agents[${agentIndex}][total_price]"]`);  

	        if (!agent_id) {
	            alert('Please select an agent first.');
	            return;
	        }

	        var productPrices = [];
	        var productqty = [];
	        $(`input[name^="agents[${agentIndex}]["][name$="product_prices][]"]`).each(function() {
	            productPrices.push(parseFloat($(this).val()) || 0); 
	        });

	        $(`input[name^="agents[${agentIndex}]["][name$="product_qty][]"]`).each(function() {
	            productqty.push(parseFloat($(this).val()) || 0); 
	        });
	        // console.log(productqty);
	        var deliveryTypePrice = parseFloat($totalPrice.val()) || 0;

	        $.ajax({
	            url: "<?php echo e(url('/admin/GetDeliveryType')); ?>",
	            type: "GET",
	            data: {
	                Dtype: Dtype,
	                agent_id: agent_id,
	                productPrices: productPrices,
	                productqty:productqty,
	            },
	            success: function(response) {
	                // console.log(response);
	                // console.log();
	                var totalProductPrice = productPrices.reduce((sum, price) => sum + price, 0);
	                var deliveryCharge = 0;
	                // console.log(totalProductPrice);
	                if (Dtype === 's_delivery') {
	                    deliveryCharge = response.agent_delivery_charge.s_delivery;
	                } else if (Dtype === 'm_delivery') {
	                    deliveryCharge = response.agent_delivery_charge.m_delivery;
	                }

	                $totalPrice.val(deliveryCharge);
	                var total = response.total + deliveryCharge;
	                $total.val(total);
	            },
	            error: function(error) {
	                console.log("Error fetching delivery type:", error);
	            }
	        });
	    });
	});    
</script>

<script>
    $(document).ready(function(){
    
        $('.btn_cancel').click(function(){
            var orderId = $(this).attr('ds-value');
            var reassignAggent = $('#reassignAggent').val();
            console.log(orderId);
            console.log(reassignAggent);
            $('.reassign').css('display', 'block');
            $.ajax({
                url:"<?php echo e(url('/admin/getOrderID')); ?>",
                type:'get',
                data:{
                    orderId:orderId,
                    reassignAggent:reassignAggent,
                },
                success:function(response){
                var agentIndex = $('#ReassignProduct .AgentAssigndProduct').length;
                console.log(agentIndex);

                var agentHTML = `
                <form action="<?php echo e(url('/admin/ReAssignProduct')); ?>" method="post" id="reEnable">
                <?php echo csrf_field(); ?>
                     <input class="form-control" type="hidden" name="OrderId" id="OrderId" disabled value=${response.id}>
                    <b>ORDER ID :</b><input class="form-control" type="" name="agent_order_id" id="agent_order_id" value=${response.agent_order_id}>
                    <table class="table AgentAssigndProduct">
                        
                        <thead>
                            <tr>
                                <th>Agent</th>
                                <th>Details</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>
                                    <select name="agents[${agentIndex}][agent_id]" class="form-control agent-select" data-id="${agentIndex}" required>
                                        <option value="">Select Agent</option>
                                        <?php $__currentLoopData = $agentsAfterCancel; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $agent): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        	<?php $__currentLoopData = $agent; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $agents): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            	<option value="<?php echo e($agents->id); ?>"><?php echo e($agents->name); ?></option>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>	
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </td>
                                <td>
                                    <table class="table">
                                        <thead>
                                            <tr>
                                                <th>Product</th>
                                                <th>Price</th>
                                                <th>QTY</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody class="AppendPrice">
                                            <tr class="default-row">
                                                <td>
                                                    <select name="agents[${agentIndex}][0][products][]" class="form-control product-select" data-agent-index="${agentIndex}" data-product-index="0" required>
                                                        <option value="">Please Select Agent First</option>
                                                    </select>
                                                </td>
                                                <td>
                                                    <input class="form-control product_price" name="agents[${agentIndex}][0][product_prices][]" required />
                                                </td>
                                                <td>
                                                    <input class="form-control product_qty" name="agents[${agentIndex}][0][product_qty][]" value="1" required/>
                                                </td>
                                                <td>
                                                    <button class="btn btn-success btn_addProduct" data-agent-index="${agentIndex}">(+)</button>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                            <tr>
                                <td></td>
                                <td>
                                    <table class="table TotalProductPrice">
                                        <thead>
                                            <tr>
                                                <th>Delivery Type</th>
                                                <th>Price</th>
                                                <th>Total Price</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>
                                                    <select name="agents[${agentIndex}][delivery_type]" class="form-control deliveryType" data-agent-index="${agentIndex}" required>
                                                        <option value="" selected>Select Delivery Type</option>
                                                        <option value="s_delivery">STANDARD</option>
                                                        <option value="m_delivery">MIDNIGHT</option>
                                                    </select>
                                                </td>
                                                <td>
                                                    <input class="form-control delivery_type_price" name="agents[${agentIndex}][delivery_type_price]" required />
                                                </td>
                                                <td>
                                                    <input class="form-control totalprice" name="agents[${agentIndex}][total_price]" required />
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                   
                    <div style="text-align:right;"><button class="btn btn-primary .btn_reasiign" type="submit" id="btnReAssign">ASSIGN</button></div>
                    </form>
                `;

                $('#ReassignProduct').append(agentHTML);
                    // $('#OrderId').val(response.id);
                    // $('#agent_order_id').val(response.agent_order_id);
                    // console.log(response);
                },
                error:function(error){
                    console.log(error);
                }
            });
        });
			
	 	$(document).on('submit','#reEnable',function(){
	 		// alert('hello');
	 		$('.agent-select').prop('disabled', false); // Re-enable fields
	 	});

        $('#reassignAggent').change(function(){
            var OrderId = $('#OrderId').val();
            var reassignAggent = $('#reassignAggent').val();
            $.ajax({
                url:"<?php echo e(url('/admin/getReAssignPrice')); ?>",
                type:"GET",
                data:{
                    OrderId:OrderId,
                    reassignAggent:reassignAggent,
                },
                success:function(response){
                    // console.log(response);
                    $('#re_price').val(response);
                },
                error:function(error){
                    console.log(error);
                },
            }); 
        });
        $('#btnReAssign').click(function(){
            var OrderId = $('#OrderId').val();
            var reassignAggent = $('#reassignAggent').val();
            var re_price = $('#re_price').val();

            $.ajax({
                url:"<?php echo e(url('/admin/Reassign')); ?>",
                type:"GET",
                data:{
                    OrderId:OrderId,
                    reassignAggent:reassignAggent,
                    re_price:re_price,
                },
                success:function(response){
                    // console.log(response);
                    location.reload();
                },
                error:function(error){
                    console.log(error);
                },
            }); 
        });

        $('#btn_mail_send').click(function(){
            var mail_status = $('#mail_status').val();
            var OrderID = <?php echo json_encode($order->id, 15, 512) ?>;
            $.ajax({
                url:"<?php echo e(url('/admin/mailStatus')); ?>",
                type:'GET',
                data:{
                    mail_status:mail_status,
                    OrderID:OrderID,
                },
                success:function(response){
                    // console.log(response);
                    location.reload();
                },
                error:function(error){  
                    console.log(error);
                },
            });
        });
        $('.mail_status').change(function(){
            var mail_status = $('#mail_status').val();
            console.log(mail_status);
            if(mail_status == 'S'){
                $('#AssignIds').css('display', 'block');
            }else{
                $('#AssignIds').css('display', 'none');
            }
        });

		// $('form').on('submit', function(e) {
		//     $('.agent-select').prop('disabled', false); // Re-enable fields
		// });
		

    });
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.admin.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/rightflorist/public_html/ofadmin.rightflorist.org/resources/views/admin/view_product.blade.php ENDPATH**/ ?>