@extends('layouts.admin.app')

@section('content')

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.0/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>

<main id="main" class="main">
    <div class="pagetitle">
        <h1>Order</h1>
        <nav>
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{{ url('/admin/order') }}">Home</a></li>
                <li class="breadcrumb-item active"><a href="{{ route('admin.order.view', base64_encode($order->id)) }}">{{ $order->unique_order_id }}</a></li>
                <li class="breadcrumb-item active">Edit</li>
            </ol>
        </nav>
    </div>

    <section class="section contact">
        <div class="product_content">
            <h4>Edit :: Order Id - {{ $order->unique_order_id }}</h4>
            <form action="{{ url('/admin/order/view/edit/' . encrypt($order->id)) }}" method="POST">
                @csrf

                @php 
                $agentIndex = 0; 
                @endphp
                <div id="appendedProduct">
                    @foreach($tableItem as $tableItems)
                    @php  $productIndex = 0; @endphp
                    <table class="table AgentAssigndProduct tab{{$agentIndex}}">
                        <thead>
                            <tr>
                                <th>Agent</th>
                                <th>Details</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>
                                    <input class="form-control" name="agents[{{ $agentIndex }}][agent_order_id][]" value="{{$tableItems['agent_order_id']}}" disabled style="width:100%;"/>
                                    <input class="form-control" name="agents[{{ $agentIndex }}][agent_order_id]" value="{{$tableItems['agent_order_id']}}" type="hidden"/>
                                    <input class="form-control" name="agents[{{ $agentIndex }}][agentAssignId]" value="{{$tableItems['agentAssignId']}}" type="hidden"/>
                                    <select name="agents[{{ $agentIndex }}][agent_id]" class="form-control agent-select getAgentId" data-id="{{ $agentIndex }}" disabled>
                                        <option value="">Select Agent</option>
                                        @foreach($agents as $agent)
                                        <option value="{{ $agent->id }}" {{ $tableItems['agent']->id == $agent->id ? 'selected' : '' }}>
                                            {{ $agent->name }}
                                        </option>
                                        @endforeach
                                    </select></br>
                                </td>
                                <td>
                                    <table class="table">
                                        <thead>
                                            <tr>
                                                <th>Product</th>
                                                <th>Price</th>
                                                <th>QTY</th>
                                                <th class="imageLinkHeader" >Image Link</th>
                                                <th class="textHeader" >Text</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody class="AppendPrice">
                                            @php $addBtnRmv = 0; @endphp
                                            @forelse($tableItems['products'] as $product)
                                            <tr class="default-row">
                                                <td>
                                                    
                                                    <select name="agents[{{$agentIndex}}][{{$productIndex}}][products][]" class="form-control product-select" data-agent-index="{{$agentIndex}}" data-product-index="0" required>
                                                        <option value="">Please Select Product</option>
                                                        @foreach($agent_product_list as $agent_product_lists)
                                                            @if($agent_product_lists->agent_id == $tableItems['agent']->id)
                                                                <option value="{{ $agent_product_lists->id }}" {{ $agent_product_lists->id == $product['product']->id ? 'selected' : '' }}>
                                                                    {{ $agent_product_lists->item }}
                                                                </option>
                                                            @endif
                                                        @endforeach
                                                    </select>
                                                </td>
                                                <td>
                                                    <input class="form-control product_price" name="agents[{{$agentIndex}}][{{$productIndex}}][product_prices][]" value="{{ $product['price'] }}" required />
                                                </td>
                                                <td>
                                                    <input class="form-control product_qty" name="agents[{{$agentIndex}}][{{$productIndex}}][product_qty][]" value="{{ $product['qty'] }}" required />
                                                </td>
                                                <td>
                                                    @if($product['imagePath'])
                                                        @php 
                                                            $imagePathDecoded = json_decode($product['imagePath'], true); 
                                                            $flatImages = collect($imagePathDecoded)->flatten(); // In case it's nested arrays
                                                        @endphp
                                                        <textarea class="form-control imgLink" name="agents[{{$agentIndex}}][{{$productIndex}}][imgLink][]" rows="4" cols="50">
                                                    @foreach($flatImages as $img)
                                                    {{ $img }}
                                                    @endforeach
                                                        </textarea>
                                                    @endif
                                                </td>
                                                
                                                <td>
                                                    @if($product['imageText'])
                                                        <textarea class="form-control text" name="agents[{{$agentIndex}}][{{$productIndex}}][text][]" rows="4" cols="50" >{{$product['imageText']}}</textarea>
                                                    @endif
                                                </td>
                                                <td>
                                                    @if($addBtnRmv > 0)
                                                        <a href="{{ url('/admin/order/view/delete/' . encrypt($product['id'])) }}" onclick="return confirm('Do you really want to Remove this Product Permanently?');"  class="btn btn-danger" type="button">(-)</a>
                                                    
                                                    @else
                                                        <button class="btn btn-success btn_addProduct" data-agent-index="{{ $agentIndex }}">(+)</button>
                                                            </br>
                                                        <a href="{{ url('/admin/order/view/delete/' . encrypt($product['id'])) }}" onclick="return confirm('Do you really want to Remove this Agent Permanently?');"  class="btn btn-danger" type="button" style="margin-top: 5px;">(-)</a>
                                                    @endif
                                                </td>
                                               
                                                 @php $addBtnRmv++; @endphp
                                            </tr>
                                            @php $productIndex++; @endphp
                                            @empty
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td  style="text-align: right;">
                                                    <button class="btn btn-success btn_addProduct" data-agent-index="{{ $agentIndex }}">(+)</button>
                                                </td>
                                            @endforelse
                                        </tbody>
                                    </table>
                                </td>
                            </tr>

                            <!-- Delivery Info -->
                            <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" {{ $tableItems['delivery_type'] == 's_delivery' ? 'selected' : '' }}>STANDARD</option>
                                                        <option value="m_delivery" {{ $tableItems['delivery_type'] == 'm_delivery' ? 'selected' : '' }}>MIDNIGHT</option>
                                                    </select>
                                                </td>
                                                <td>
                                                    

                                                        @if($tableItems['delivery_type'] == 's_delivery')
                                                            @php $value = $tableItems['delivery_price']->s_delivery; @endphp
                                                        @else
                                                            @php $value = $tableItems['delivery_price']->m_delivery; @endphp
                                                        @endif
                                                   
                                                    <input class="form-control delivery_type_price" name="agents[{{$agentIndex}}][delivery_type_price]" value="{{ $value }}" required />
                                                </td>
                                                <td>
                                                    <input class="form-control totalprice" name="agents[{{$agentIndex}}][total_price]" value="{{ $tableItems['totalPrice'] }}" required />
                                                </td>
                                            </tr>

                                        </tbody>
                                    </table>
                                </td>
                            </tr>

                            <!-- Delivery Date/Time -->
                            <tr>
                                <td></td>
                                <td>
                                    <table class="table">
                                        <thead>
                                            <tr>
                                                <th>Delivery Date</th>
                                                <th>Delivery Time</th>
                                                <th>Any other requirments</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>
                                                    <input type="date" class="form-control" name="agents[{{$agentIndex}}][date]" value="{{ $tableItems['delivery_date'] }}" required />
                                                </td>
                                                <td>
                                                    <input type="text" class="form-control" name="agents[{{$agentIndex}}][time]" value="{{ $tableItems['delivery_time'] }}" required />
                                                </td>
                                                <td colspan="2">
                                                    <textarea class="form-control" id="comments" name="agents[{{$agentIndex}}][comments]" rows="4" cols="50" placeholder="Any Speacial Requirments">{{$tableItems['comments']}}</textarea>
                                                </td>
                                            </tr>
                                            
                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="2" style="text-align:right;">
                                    <a class="btn btn-danger" href="{{ url('/admin/order/view/delete/' . encrypt($order->id) . '/' . encrypt($tableItems['agentAssignId'])) }}" onclick="return confirm('Do you really want to Remove this Agent Permanently?');" type="button" >Remove</a>
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                    @php $agentIndex++; @endphp
                    @endforeach
                </div>

                <!-- Footer Add Button -->
                <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 type="hidden" name="OrderID" value="{{ $order->unique_order_id }}" />
                <input type="hidden" name="OrderOriginalID" value="{{ $order->id }}" />

                <div id="button_assign">
                    <button class="btn btn-primary" type="submit" id="btn_assign" >ASSIGN</button>
                </div>
            </form>
        </div>
    </section>
</main>


<style type="text/css">
    .table-container {
        height: 450px; 
    /*    overflow-y: scroll;*/
    }

    .table-container table {
        width: 100%;
        border-collapse: collapse;
    }

    .table-container thead, .table-container tfoot {
        background-color: #f2f2f2; /* Optional: background color to differentiate the head and foot */
        position: sticky;
        top: 0;
        z-index: 1;
    }

    .table-container tfoot {
        bottom: 0;
        top: auto;
    }

    .table-container tbody {
        display: block;
        /*height: 100%;*/
        height: 250px;
        overflow-y: scroll;
        width: 100%;
    }

    .table-container tbody tr {
        display: table;
        width: 100%;
        table-layout: fixed;
    }

    .table-container thead tr, .table-container tfoot tr {
        display: table;
        width: 100%;
        table-layout: fixed;
    }

    .processTable{
        background-color: #efefef !important;
        padding: 10px 5px;
        text-align: center;
    }
</style>

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

<script>
    $(document).ready(function(){

        $('.copyImagePath').click(function () {
            let id = $(this).attr("ds-value"); 
            let imagePaths = [];

            $('.personalized_image_' + id).each(function () {
                imagePaths.push($(this).val());
            });

            const textToCopy = imagePaths.join('\n');
            console.log(id);

            navigator.clipboard.writeText(textToCopy)
                .then(() => {
                    alert('Image paths copied to clipboard!');
                })
                .catch(err => {
                    console.error('Failed to copy text: ', err);
                    alert('Failed to copy image paths. Please try again.');
                });
        });

        $('.copyTextPath').click(function () {
            let id = $(this).attr("data-value");
            let ImgText = $('#ImgText_' + id).val(); 

            navigator.clipboard.writeText(ImgText)
                .then(() => {
                    alert('Image Text copied to clipboard!');
                })
                .catch(err => {
                    console.error('Failed to copy text: ', err);
                    alert('Failed to copy image text. Please try again.');
                });
        });

        $(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: "{{ url('/admin/order/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 class="imageLinkHeader" style="display:none;">Image Link</th>
                                                            <th class="textHeader" style="display:none;">Text</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>
                                                                <textarea class="form-control imgLink" id="agents[${agentIndex}][0][imgLink][]" name="agents[${agentIndex}][0][imgLink][]" rows="4" cols="50" style="display:none;"></textarea>
                                                            </td>
                                                            <td>
                                                                <textarea class="form-control text" id="agents[${agentIndex}][0][text][]" name="agents[${agentIndex}][0][text][]" rows="4" cols="50" style="display:none;"></textarea>
                                                            </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>
                                        <tr>
                                            <td></td>
                                            <td>
                                                <table class="table TotalProductPrice">
                                                    <thead>
                                                        <tr>
                                                            <th>Delivery Date</th>
                                                            <th>Delivery Time</th>
                                                            <th>Any other requirments</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr>
                                                            <td>
                                                                <input type="date" class="form-control totalprice" name="agents[${agentIndex}][date]" required/>
                                                            </td>
                                                            <td>
                                                                <input type="text" class="form-control totalprice" name="agents[${agentIndex}][time]" required/>
                                                            </td>
                                                            <td colspan="2">
                                                                <textarea class="form-control" id="comments" name="agents[${agentIndex}][comments]" rows="4" cols="50" placeholder="Any Speacial Requirments"></textarea>
                                                            </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: "{{ url('/admin/order/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: "{{ url('/admin/order/GetPriceByProduct') }}",  
                    type: 'GET',
                    data: { 
                        product_id: product_id,
                        agentIndex:agentIndex,
                        productIndex:productIndex,
                     },
                    success: function(response) {
                        console.log(response);
                        $totalPrice.val(response.price.price);

                        if (response.price.is_personalized === 'Y') {
                            // $row.find('.imgLink').css('display', 'block');
                            // $row.find('.text').css('display', 'block');
                            $('textarea[name="agents[' + response.agentIndex + '][' + response.productIndex + '][imgLink][]"]').css('display', 'block');
                            $('textarea[name="agents[' + response.agentIndex + '][' + response.productIndex + '][text][]"]').css('display', 'block');
                            $('.imageLinkHeader').css('display', 'table-cell');
                            $('.textHeader').css('display', 'table-cell');
                        } else {
                            // $row.find('.imgLink').css('display', 'none');
                            // $row.find('.text').css('display', 'none');
                            $('textarea[name="agents[' + response.agentIndex + '][' + response.productIndex + '][imgLink][]"]').css('display', 'none');
                            $('textarea[name="agents[' + response.agentIndex + '][' + response.productIndex + '][text][]"]').css('display', 'none');
                        }
                        $(`[name="agents[${agentIndex}][delivery_type]"]`).prop('selectedIndex', 0);
                        $(`[name="agents[${agentIndex}][delivery_type_price]"]`).val('');
                        $(`[name="agents[${agentIndex}][total_price]"]`).val('');
                    },
                    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();
            console.log(productIndex);

            if (agent_id) {
                $.ajax({
                    url: "{{ url('/admin/order/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>
                                    <textarea class="form-control imgLink" id="agents[${agentIndex}][${productIndex}][imgLink][]" name="agents[${agentIndex}][${productIndex}][imgLink][]" rows="4" cols="50" style="display:none;"></textarea>
                                </td>
                                <td>
                                    <textarea class="form-control text" id="agents[${agentIndex}][${productIndex}][text][]" name="agents[${agentIndex}][${productIndex}][text][]" rows="4" cols="50" style="display:none;"></textarea>
                                </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: "{{ url('/admin/order/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(){

        $(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:"{{url('/admin/order/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:"{{url('/admin/order/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 = @json($order->id);
            $.ajax({
                url:"{{url('/admin/order/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>

<script type="text/javascript">

    $(document).on('click', '.uploaded-txt-show-btn', function () {
        //alert("ff");
        var txtlinkid = $(this).data("txtlinkid");
        $('#ptxt' + txtlinkid).modal('show');
    });

    $(document).on('click', '.uploaded-img-show-btn', function () {
        //alert("ff");
        var imglinkid = $(this).data("imglinkid");
        $('#pimg' + imglinkid).modal('show');
    });

    $(function () {
        $(".btn-default, .close").click(function () {
            $(".uploaded-img-container").modal("hide");
        });
    });

    function downloadZip(zipId, orderDtlId, productId) {
        window.location.href = '/admin/orders/download-personalized-images/' + zipId + '/' + orderDtlId + '/' + productId;
    }

    $(document).on('click', '.download-all', function () {
        var targetId = $(this).data('targetid'); // e.g., pimg1, pimg2
        $('#' + targetId + ' .modal-body img').each(function () {
            var imageUrl = $(this).attr('src');
            var link = document.createElement('a');
            link.href = imageUrl;
            link.download = imageUrl.split('/').pop(); // gets the filename
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });
    });

    {{-- $(document).on('click', '.download-images-zip', async function () {
        const containerId = $(this).data('target');
        const productId = $(this).data('productid');
        const orderId = $(this).data('orderid');

        const zip = new JSZip();
        const folder = zip.folder("images");

        const images = $('#' + containerId + ' img');
        const fetchImageAsBlob = async (url) => {
            const res = await fetch(url);
            return await res.blob();
        };

        let count = 0;

        for (const img of images) {
            const src = $(img).attr('src');
            if (!src) continue;

            try {
                const blob = await fetchImageAsBlob(src);
                const filename = `image_${++count}${src.substr(src.lastIndexOf('.'))}`;
                folder.file(filename, blob);
            } catch (e) {
                console.error('Failed to fetch image:', src, e);
            }
        }

        zip.generateAsync({ type: "blob" }).then(function (content) {
            saveAs(content, `${orderId}_${productId}.zip`);
        });
    }); --}}

    {{-- $(document).on('click', '.download-images-zip', async function () {
        const containerId = $(this).data('target');
        const productId = $(this).data('productid');

        const zip = new JSZip();
        const folder = zip.folder("images");

        const images = $('#' + containerId + ' img');
        let count = 0;

        for (const img of images) {
            const src = $(img).attr('src');
            if (!src) {
                console.warn('Image without src found');
                continue;
            }

            try {
                console.log(`Fetching image: ${src}`);
                const res = await fetch(src, { mode: 'cors' });
                if (!res.ok) {
                    console.error(`Failed to fetch image: ${src}`, res.status);
                    continue;
                }

                const blob = await res.blob();
                const ext = src.split('.').pop().split(/\#|\?/)[0];
                const filename = `image_${++count}.${ext}`;
                folder.file(filename, blob);
            } catch (e) {
                console.error('Error fetching image:', src, e);
            }
        }

        if (count === 0) {
            alert("No images could be added. Check CORS or image paths.");
            return;
        }

        zip.generateAsync({ type: "blob" }).then(function (content) {
            saveAs(content, `product_${productId}.zip`);
        });
    }); --}}
 
</script>

@endsection

@section('script')



@endsection
