@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">Order</li>
            </ol>
        </nav>
    </div><!-- End Page Title -->

    <section class="section contact">

        <?php
            if( $order_dtl != null ) {
                //dd($order_dtl);
                $siteInfo = App\Http\Helper1::get_SiteInfo($order_dtl->sitename);
        ?>

        <div class="row gy-4">

            <div class="col-xl-6">

                <div class="row">

                    <div class="col-lg-12">
                        <div class="info-box card" style="padding: 10px 12px;">

                            <div class="row">

                                <div class="col-9">
                                    <h5><b>{{ $order_dtl->unique_order_id }}</b></h5>
                                    <input type="hidden" name="odr_id" id="odr_id" value="{{ base64_encode($order_dtl->id) }}">

                                    <h6>
                                        <strong>Purchase Date:</strong>
                                            @if( $order_dtl->purchase_date != '0000-00-00 00:00:00')
                                                {{ date('d/m/Y' , strtotime($order_dtl->purchase_date)) }}
                                            @endif
                                    </h6>
                                    <p>
                                        <strong>Customer Email : </strong>
                                        <a href="mailto:{{ $customer_dtl->email}}" style="color: blue">{{ $customer_dtl->email}}</a>
                                    </p>
                                    
                                </div>

                                <div class="col-3 ms-auto text-end">
                                    @if($order_dtl->order_delivery_status == 'P')
                                        <button type="button" class="btn btn-danger mb-2">Pending</button>
                                    @elseif($order_dtl->order_delivery_status == 'PC')
                                        <button type="button" class="btn btn-info mb-2">Processed</button>
                                    @elseif($order_dtl->order_delivery_status == 'H')
                                        <button type="button" class="btn btn-warning mb-2">Hold</button>
                                    @elseif($order_dtl->order_delivery_status == 'CL')
                                        <button type="button" class="btn btn-dark mb-2">Cancel</button>
                                    @elseif($order_dtl->order_delivery_status == 'D')
                                        <button type="button" class="btn btn-success mb-2">Delivered</button>
                                    @elseif($order_dtl->order_delivery_status == 'S')
                                        <button type="button" class="btn btn-primary mb-2">Shipped</button>
                                    @endif
                                </div>

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

                    <div class="col-lg-6">
                        <div class="info-box card" style="padding: 10px 12px;">
                            <h4>Delivery Address
                                <i class="bx bxs-calendar-edit del-address-edit-btn fawsm" style="font-size:25px"></i>
                            </h4>
                            
                            <div class="delivery_address_section">
                                <?php
                                    if( $order_dtl->delivery_user_name != NULL ) {
                                ?>
                                    <strong>
                                    {!! $order_dtl->delivery_user_name !!}
                                    </strong><br>
                                    {!! $order_dtl->delivery_address !!},<br>
                                    {!! $order_dtl->delivery_city !!}, {!! $order_dtl->delivery_country !!},<br>
                                    {!! $order_dtl->delivery_state !!} - {!! $order_dtl->delivery_pincode !!}<br>
                                    {!! $order_dtl->delivery_mobile !!}
                                <?php
                                    }else{
                                        echo 'NA';
                                    }
                                ?>
                            </div>

                            <div class="edit_delivery_address_section" style="display:none">
                                <table style="width:100%">
                                    <tr>
                                        <td style="width:30%">Name :</td>
                                        <td><input type="text" name="rec_name" id="rec_name" placeholder="Recipient Name" value="{!! $order_dtl->delivery_user_name !!}" class="editinputsec" required></td>
                                    </tr>
                                    <tr>
                                        <td>Address :</td>
                                        <td><input type="text" name="rec_address" id="rec_address" placeholder="Recipient Address" value="{!! $order_dtl->delivery_address !!}" class="editinputsec" required></td>
                                    </tr>
                                    <tr>
                                        <td>Country :</td>
                                        <td><input type="text" name="rec_country" id="rec_country" placeholder="Recipient Country" value="{!! $order_dtl->delivery_country !!}" class="editinputsec" readonly></td>
                                    </tr>
                                    <tr>
                                        <td>City :</td>
                                        <td><input type="text" name="rec_city" id="rec_city" placeholder="Recipient City" value="{!! $order_dtl->delivery_city !!}" class="editinputsec"></td>
                                    </tr>
                                    <tr>
                                        <td>State :</td>
                                        <td><input type="text" name="rec_state" id="rec_state" placeholder="Recipient State" value="{!! $order_dtl->delivery_state !!}" class="editinputsec"></td>
                                    </tr>
                                    <tr>
                                        <td>Zipcode :</td>
                                        <td><input type="text" name="rec_zipcode" id="rec_zipcode" placeholder="Recipient Zipcode" value="{!! $order_dtl->delivery_pincode !!}" class="editinputsec"></td>
                                    </tr>
                                    <tr>
                                        <td>Phone No :</td>
                                        <td><input type="text" name="rec_phone" id="rec_phone" placeholder="Recipient Phone" value="{!! $order_dtl->delivery_mobile !!}" class="editinputsec"></td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <input type="text" name="del_add_access_code" id="del_add_access_code" placeholder="Access Code" style="width:90%" >
                                        </td>
                                        <td>
                                            
                                            <button class="btn btn-success btn-sm update-delivery_address">Update</button>
                                            <button class="btn btn-danger btn-sm cancel-del-address-edit-btn">Cancel</button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" align="center"><span id="warning-msg-del-address" class="msgerror"></span></td>
                                    </tr>
                                </table>
                            </div>

                        </div>
                    </div>
                    <div class="col-lg-6">
                      <div class="info-box card" style="padding: 10px 12px;">
                        <h4>Billing Address</h4>
                        <div>
                            <?php
                                if( $order_dtl->billing_user_name != NULL ) {
                            ?>
                                <strong>
                                    {!! $order_dtl->billing_user_name !!}
                                </strong><br>
                                {!! $order_dtl->billing_address !!},<br>
                                {!! $order_dtl->billing_city !!}, {!! $order_dtl->billing_country !!},<br>
                                {!! $order_dtl->billing_state !!} - {!! $order_dtl->billing_pincode !!}<br>
                                {!! $order_dtl->billing_mobile !!}
                            <?php
                                }else{
                                    echo 'NA';
                                }
                            ?>
                        </div>
                      </div>
                    </div>

                    <div class="col-lg-12">
                        <div class="info-box card" style="padding: 10px 12px;">

                            <h4>Message Section
                                <i class="bx bxs-calendar-edit message-edit-btn fawsm" style="font-size:25px"></i>
                            </h4>
                            
                            <div class="message_section">
                                {{-- <strong>Message Purpose:</strong> {{ $order_dtl->order_message->message_purpose }}
                                <br>
                                <strong>Occasion Type: </strong>{{ $order_dtl->order_message->occasion_type }}
                                <br> --}}
                                <strong>Sender Name:</strong> {{ $order_dtl->order_message->sender_name }}
                                <br>
                                <strong>Sender Message: </strong>{{ $order_dtl->order_message->sender_message }}
                                <br>
                                <strong>Special Instruction: </strong>{{ $order_dtl->order_message->sender_special_instruction }}
                                
                                {{-- <br>
                                <strong>Relation to Recipient: </strong>{{ $order_dtl->order_message->relation_to_recipient }}
                                
                                <br>--}}
                                {{--@if($order_dtl->order_message->sender_demand != '')
                                    <span style="color: red; font-weight: bold;">**Note: </strong>{{ $order_dtl->order_message->sender_demand }}
                                @endif --}}
                            </div>

                            <div class="edit_message_section" style="display:none">
                                <table style="width:100%">
                                    {{-- <tr>
                                        <td style="width:25%">Message Purpose :</td>
                                        <td style="width:75%"><input type="text" name="msg_purpose" id="msg_purpose" placeholder="Message Purpose" value="{!! $messagedata->message_purpose !!}" class="editinputsec" readonly disabled></td>
                                    </tr>
                                    <tr>
                                        <td>Occasion Type :</td>
                                        <td><input type="text" name="occ_type" id="occ_type" placeholder="Occasion Type" value="{!! $messagedata->occasion_type !!}" class="editinputsec" ></td>
                                    </tr> --}}
                                    <tr>
                                        <td style="width:30%">Sender Name :</td>
                                        <td style="width:70%"><input type="text" name="sender_name" id="sender_name" placeholder="Sender Name" value="{!! $order_dtl->order_message->sender_name !!}" class="editinputsec"></td>
                                    </tr>
                                    <tr>
                                        <td>Sender Message :</td>
                                        <td>
                                            <textarea name="sender_msg" id="sender_msg" placeholder="Sender Message" class="editinputsec">{!! $order_dtl->order_message->sender_message !!}</textarea>
                                        </td>
                                    </tr>
                                    
                                    <tr>
                                        <td>Special Instruction :</td>
                                        <td>
                                            <textarea name="spl_inst" id="spl_inst" placeholder="Special Instruction" class="editinputsec">{!! $order_dtl->order_message->sender_special_instruction !!}</textarea>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>Access Code :</td>
                                        <td>
                                            <input type="text" name="message_access_code" id="message_access_code" placeholder="Access Code">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td>
                                            <button class="btn btn-success btn-sm update-message">Update</button>
                                            <button class="btn btn-danger btn-sm cancel-message-edit-btn">Cancel</button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" align="center"><span id="warning-msg-message" class="msgerror"></span></td>
                                    </tr>
                                </table>
                            </div>
                            
                        </div>
                    </div>
                
                </div>

            </div>

            <div class="col-xl-6">
                <div class="card" style="padding: 10px 25px;">
                    <h5>Order Details</h5>
                    <?php
                    $total_cart_price = 0; $final_price = 0; $shipping_charges = 0; $payable = 0;
                    $personalizeId = 1;

                    if( count($cart_array) > 0 ) {
                    ?>

                        <div class="row table-container">
                            <table class="table table-striped">
                                <thead>
                                  <tr>
                                    <th scope="col" style="text-align:center; width:15%">Image</th>
                                    <th scope="col" style="text-align:center; width:35%">Product</th>
                                    <th scope="col" style="text-align:center; width:27%">Send To</th>
                                    <th scope="col" style="text-align:center; width:8%">Qty</th>
                                    <th scope="col" style="text-align:center; width:15%">Price</th>
                                  </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    //dd($siteInfo->site_link);
                                    //dd($cart_array);
                                    foreach( $cart_array as $data ) {
                                    ?>
                                        <tr>
                                            <td style="text-align:center; width:15%">
                                                <img src="{{ $siteInfo->site_link }}uploaded/product/{{$data['image'] }}" width="60" height="60" >

                                                {{-- @if(isset($data['image']) && $data['image'] != null )
                                                    @if(file_exists(public_path('/uploaded/product/'.$data['image'])))
                                                       
                                                        <img src="{{ $siteInfo->site_link }}'uploaded/product/'{{$data['image'] }}" width="60" height="60" >

                                                    @else
                                                        {!! '<img src="' . URL::to('/').config('global.no_image') . '" width="60" height="60" >' !!}
                                                    @endif
                                                @else
                                                    {!! '<img src="'.URL::to('/').config('global.no_image').'" width="60" height="60" >' !!}
                                                @endif --}}
                                                <br>
                                                <small style="font-size:9px">
                                                    @if($data['delivery_type'] == 'C')
                                                        <span class="badge rounded-pill bg-success">{{ $data['delivery_type'] }}</span>
                                                    @else
                                                        <span class="badge rounded-pill bg-danger">{{ $data['delivery_type'] }}</span>
                                                    @endif    
                                                    {{ $data['fnid'] }}
                                                </small>
                                            </td>
                                            <td style="text-align:center; width:35%; font-size:12px">
                                                {{-- {{ ucwords($data['product_name']) }} --}}
                                                <a href="{{ route('admin.product.product-view', $data['fnid']) }}" target="_blank">{{ ucwords($data['product_name']) }}
                                                </a>
                                                <br />
                                                @php
                                                if( $data['attribute_name'] != '' ) {
                                                    echo '<small><a>('.$data['attribute_name'].')</a></small>';
                                                }
                                                echo '<br>';
                                                if( $data['product_extra_addon_name'] != null ) {
                                                    echo '<small>';
                                                    $h=1;
                                                    foreach( $data['product_extra_addon_name'] as $key_extra_addon => $val_extra_addon ) {
                                                        echo $val_extra_addon;
                                                        if( $h < count($data['product_extra_addon_name']) ) {
                                                            echo '<br />';
                                                        }
                                                        $h++;
                                                    }
                                                    echo '</small>';
                                                }
                                                @endphp


                                                @php 
                                                    $getPersonalizeImg = App\Http\Helper1::getPersonalizeImg($data['order_detail_id'], $data['product_id']); 
                                                @endphp

                                                @if(count($getPersonalizeImg) > 0)
                                                    <span class="badge rounded-pill bg-info uploaded-img-show-btn" data-imglinkid="{{$personalizeId}}" style="cursor:pointer;"><i class="bx bxs-user-detail"></i> IMAGE</span>
                                                @endif

                                                @php 
                                                    $getPersonalizeTxt = App\Http\Helper1::getPersonalizeTxt($data['order_detail_id'], $data['product_id']); 
                                                @endphp

                                                @if($getPersonalizeTxt)
                                                    <span class="badge rounded-pill bg-warning uploaded-txt-show-btn" data-txtlinkid="{{$personalizeId}}" style="cursor:pointer;"><i class="bx bxs-user-detail"></i> TEXT</span>
                                                @endif

                                            </td>
                                            <td style="text-align:center; width:27%">
                                                @php
                                                if( isset($data['product_id']) && $data['product_id'] != 0 ) {
                                                    //echo @$data['delivery_city'].', '.@$data['delivery_country'];
                                                    //echo '<br><a>'.date('D, M d y').', '.$data['delivery_date'].'</a><br>';
                                                    //'<br><a>'.
                                                    echo  date('M d,y' , strtotime($data['delivery_date'])).'</a><br>';
                                                    //echo $data['shippingmethod_name'];
                                                    echo $data['delivery_pincode'].'<br>';
                                                    echo '<span style="font-size:12px; color: blue">'.ucwords($data['shippingmethod_name']).'</span><br>';
                                                    echo '<span style="font-size:12px; color: blue">'.$data['deliverytime'].'</span>';
                                                }
                                                @endphp
                                            </td>
                                            <td style="text-align:center; width: 8%">{{ $data['qty'] }}</td>
                                            <td style="text-align:center; width:15%">
                                                @php
                                                    $total_cart_price = $total_cart_price + ( $data['unit_price'] * $data['qty'] );

                                                    $shipping_charges = $shipping_charges + $data['ship_price'];
                                                @endphp
                                                {!! Currency::default($data['total_price'], ['need_currency'=>true, 'number_format'=>config('global.number_format_limit') ]) !!}
                                            </td>
                                        </tr>

                                        <!-- Modal Personalize Image -->
                                        @if(count($getPersonalizeImg) > 0)
                                        <div class="modal fade uploaded-img-container" id="pimg{{$personalizeId}}" tabindex="-1" aria-hidden="true" style="display: none;">
                                            <div class="modal-dialog">
                                              <div class="modal-content">
                                                <div class="modal-header">
                                                  <h4 class="modal-title">User Personalized Images - {{ pathinfo($data['image'], PATHINFO_FILENAME) }}</h4>
                                                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <div class="row">
                                                        @foreach($getPersonalizeImg as $pimg)
                                                            <div class="col-4">
                                                                <div class="card">

                                                                    <img src="{{ $siteInfo->site_link }}uploaded/personalized_image/{{$pimg->image}}" style="width:150px; height: auto;" >
                                                                    <input class="form-control personalized_image_{{$personalizeId}}" type="hidden" name="personalized_image_id[]" value="{{ $siteInfo->site_link }}uploaded/personalized_image/{{$pimg->image}}"/>

                                                                    {{-- <img src="{{ URL::to('/') . '/uploaded/personalized_image/'. $pimg->image }}" alt="" style="width:150px; height: auto;"> --}}
                                                                </div>
                                                            </div>
                                                        @endforeach
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    {{-- <button class="btn btn-success download-images-zip" data-target="modal-images-123" data-orderid="{{ $order_dtl->unique_order_id }}" data-productid="{{ pathinfo($data['image'], PATHINFO_FILENAME) }}" title="Download All"><i class="bi bi-cloud-download-fill"></i></button> --}}
                                                    <button typpe="button" class= "btn btn-info copyImagePath" id="copyImagePath" ds-value="{{$personalizeId}}">
                                                        <i class="ri-file-copy-2-fill"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-primary" onclick="downloadZip('{{ $order_dtl->unique_order_id .'_'.pathinfo($data['image'], PATHINFO_FILENAME) }}', {{ $data['order_detail_id'] }}, {{ $data['product_id'] }})"><i class="bi bi-cloud-download-fill"></i></button>
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>

                                                    {{-- <button type="button" class="btn btn-primary download-all" data-targetid="pimg{{$personalizeId}}">Download All</button> --}}
                                                    
                                                </div>
                                              </div>
                                            </div>
                                        </div>
                                        @endif

                                        <!-- Modal Personalize Text -->
                                        @if($getPersonalizeTxt)
                                        <div class="modal fade uploaded-txt-container" id="ptxt{{$personalizeId}}" tabindex="-1" aria-hidden="true" style="display: none;">
                                            <div class="modal-dialog">
                                              <div class="modal-content">
                                                <div class="modal-header">
                                                  <h4 class="modal-title">User Personalized Text - {{ pathinfo($data['image'], PATHINFO_FILENAME) }}</h4>
                                                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <div class="card">
                                                        <div class="card-body">
                                                          <h5 class="card-title">{{ ucwords($data['product_name']) }}</h5>
                                                          {!! $getPersonalizeTxt->msg !!}
                                                          <input class="form-control ImgText_{{$personalizeId}}" type="text" id="ImgText_{{$personalizeId}}" value="{{ $getPersonalizeTxt->msg }}" style="display:none;"/>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button typpe="button" class= "btn btn-info copyTextPath" data-value="{{$personalizeId}}" id="copyTextPath">
                                                        <i class="ri-file-copy-2-fill"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                </div>
                                              </div>
                                            </div>
                                        </div>
                                        @endif


                                        <?php 
                                        //dd($addon_gift_array);
                                        if(count($addon_gift_array)>0){
                                            foreach ($addon_gift_array as $key => $addon_value) {
                                                if($data['order_detail_id'] == $addon_value['order_details_id_giftaddon']){
                                        ?>

                                            <tr>
                                                <td style="text-align:center; width:15%">

                                                    <img src="{{ $siteInfo->site_link }}uploaded/product/{{$addon_value['image'] }}" width="60" height="60" >

                                                    {{-- @if(isset($addon_value['image']) && $addon_value['image'] != null )
                                                        @if(file_exists(public_path('/uploaded/product/'.$addon_value['image'])))
                                                            {!! '<img src="' . URL::to('/') . '/uploaded/product/' . $addon_value['image'] . '" width="60" height="60" >' !!}
                                                        @else
                                                            {!! '<img src="' . URL::to('/').config('global.no_image') . '" >' !!}
                                                        @endif
                                                    @else
                                                        {!! '<img src="'.URL::to('/').config('global.no_image').'" >' !!}
                                                    @endif --}}
                                                     <br>
                                                    <small style="font-size:9px">
                                                        @if($addon_value['delivery_type'] == 'C')
                                                            <span class="badge rounded-pill bg-success">{{ $addon_value['delivery_type'] }}</span>
                                                        @else
                                                            <span class="badge rounded-pill bg-danger">{{ $addon_value['delivery_type'] }}</span>
                                                        @endif    
                                                        {{ $addon_value['fnid'] }}
                                                    </small>
                                                </td>
                                                <td style="text-align:center; width:35%; font-size: 12px;">
                                                    
                                                    <a href="{{ route('admin.product.product-view', $addon_value['fnid']) }}" target="_blank">{{ ucwords($addon_value['product_name']) }}
                                                    </a>
                                                    <br />
                                                    
                                                    @php
                                                    if( $addon_value['attribute_name'] != '' ) {
                                                        echo '<small><a>('.$addon_value['attribute_name'].')</a></small>';
                                                    }
                                                    echo '<br>';
                                                    if( $addon_value['product_extra_addon_name'] != null ) {
                                                        echo '<small>';
                                                        $h=1;
                                                        foreach( $addon_value['product_extra_addon_name'] as $key_extra_addon => $val_extra_addon ) {
                                                            echo $val_extra_addon;
                                                            if( $h < count($addon_value['product_extra_addon_name']) ) {
                                                                echo '<br />';
                                                            }
                                                            $h++;
                                                        }
                                                        echo '</small>';
                                                    }
                                                    @endphp
                                                </td>
                                                <td style="text-align:center; width:27%">
                                                    @php
                                                        if( isset($addon_value['gift_addon_id']) && $addon_value['gift_addon_id'] != 0 ) {
                                                            //echo @$addon_value['delivery_city'].', '.@$addon_value['delivery_country'];
                                                            //echo '<br><a>'.date('D, M d').', '.$addon_value['delivery_date'].'</a><br>';
                                                            //'<br><a>'.
                                                            echo  date('M d,y' , strtotime($addon_value['delivery_date'])).'</a><br>';
                                                            echo $addon_value['shippingmethod_name'];
                                                        }
                                                    @endphp
                                                </td>
                                                <td style="text-align:center; width:8%">{{ $addon_value['qty'] }}</td>
                                                <td style="text-align:center; width:15%">
                                                    @php
                                                        $total_cart_price = $total_cart_price + ( $addon_value['unit_price'] * $addon_value['qty'] );

                                                        $shipping_charges = $shipping_charges + $addon_value['ship_price'];
                                                    @endphp
                                                    {!! Currency::default($addon_value['total_price'], ['need_currency'=>true, 'number_format'=>config('global.number_format_limit') ]) !!}
                                                </td>
                                            </tr>

                                        <?php 
                                                }
                                            }
                                        }
                                        ?> 
                                    <?php
                                        $personalizeId++;
                                    }
                                    ?>  
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="4" style="text-align: right;"><b>Total:</b></td>
                                        <td style="text-align: right;">
                                            <?php
                                                echo Currency::default($total_cart_price, ['need_currency'=>true, 'number_format'=>config('global.number_format_limit') ]);

                                                $final_price = $total_cart_price + $final_price;
                                            ?>
                                        </td>
                                    </tr>  
                                    
                                    @if( $shipping_charges != 0 )
                                    <tr>
                                        <td colspan="4" style="text-align: right;">Shipping Charge:</td>
                                        <td style="text-align: right;">
                                            <?php
                                                echo Currency::default($shipping_charges, ['need_currency'=>true, 'number_format'=>config('global.number_format_limit') ]);

                                                $final_price = $final_price + $shipping_charges;
                                            ?>
                                        </td>
                                    </tr>
                                    @endif

                                    <?php
                                        /*$couponadata = App\Http\Helper::get_coupon_details($order_dtl->id);
                                        if( $coupondata != null ) {
                                        */
                                        if( $order_dtl->order_coupon_data != null ) {
                                            $coupondata = $order_dtl->order_coupon_data;

                                            $discount_amount = 0;
                                            if( $coupondata != null ) {
                                                $discount_amount = $order_dtl->order_coupon_data->coupon_discount_amount;
                                            }
                                    ?>
                                    <tr>
                                        <td colspan="4" style="text-align: right;"><b>Discount:</b></td>
                                        <td style="text-align: right;">
                                            <?php
                                                $final_price = $final_price - $discount_amount;
                                                echo Currency::default($discount_amount, ['need_currency'=>true, 'number_format'=>config('global.number_format_limit') ]);
                                            ?>
                                        </td>
                                    </tr>
                                    <?php
                                        }
                                    ?>    

                                    <tr>
                                        <td colspan="4" style="text-align: right;"><b>Grand Total:</b></td>
                                        <td style="text-align: right;">
                                            <?php
                                                $payable = $final_price;
                                                echo '<b>'.Currency::default($payable, ['need_currency'=>true, 'number_format'=>config('global.number_format_limit') ]).'</b>';
                                            ?>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table> 
                        </div>
                        

                        

                    <?php
                        //}
                        
                    }else{
                        echo 'No record found.';
                    }
                    ?>


                    
                </div>

            </div>

        </div>

        <?php
            }else{
                echo 'No record found.';
            }

            
        ?>


        @if($disable >= 1)

        @else
        <div class="product_content">
            <h3>Assign Agent</h3>
            <form action="{{url('/admin/order/view/')}}/{{$order->id}}" method="post">
                @csrf
                
                <!-- Appended Products -->
                <div id="appendedProduct"></div>
                
                <!-- Form Footer -->
                <table class="table">
                    <tbody>
                        <tr>
                            <td colspan="2" style="text-align:right; background-color: #cfe2ff;">
                                <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="{{$order->unique_order_id}}"/>
                <input class="form-control" type="hidden" name="OrderOriginalID" value="{{$order->id}}"/>

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

        @endif
            
            @if($disable == 0)
            @else
                <h2 style="margin-top: 1%; margin-bottom: 1%;">Processed Order Detail
                    <a href="{{ url('/admin/order/view/edit/' . encrypt($order->id)) }}"><i class="bx bxs-calendar-edit fawsm" style="font-size:25px"></i></a>
                </h2>
                {{-- <div class="text-end"> 
                    <a href="{{ url('/admin/order/view/edit/' . encrypt($order->id)) }}" class="btn btn-primary">
                        Edit
                    </a>
                </div> --}}


                @php
                    $mailDisable = 0;
                    $groupedData = [];
                    //dd($assinged);
                    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);
                                
                                $productQty = $assigned_agent_product_map
                                              ->where('product_id', $assigned_agent_product_maps->product_id)
                                              ->where('agent_assinged_id', $assigned_agent_product_maps->agent_assinged_id)
                                              ->first();
                                //dd($productQty);

                                if ($productItem && $agent) {
                                    $agentId = $assignedItem->agent_id;

                                    if (!isset($groupedData[$agentId])) {
                                        $groupedData[$agentId] = [
                                            'products' => [],
                                            'mapped_details' => [],
                                            'qty' => [],
                                            'OrderID' => $assignedItem->id,
                                            'agent_order_id' => $assignedItem->agent_order_id,
                                            'agent_id' => $assignedItem->agent_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;
                                    $groupedData[$agentId]['qty'][] = $productQty->qty;
                                }
                            }
                        }
                    }
                 

                @endphp
                    <table class="table">
                        <thead>
                            <tr>
                                <th class="processTable">Sl No</th>
                                <th class="processTable">Order Id</th>
                                <th class="processTable">Product Name & Qty</th>
                                {{--<th class="processTable">Qty</th>--}}
                                <th class="processTable">Assigned Agent</th>
                                <th class="processTable">Price</th>
                                <th class="processTable">Delivery Charge</th>
                                <th class="processTable">Extra</th>
                                <th class="processTable">Reason</th>
                                <th class="processTable">Track No</th>
                                <th class="processTable">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            @php $i = 1; @endphp
                            @php 
                                $Delivery_Price = 0;    
                                $Extra = 0;
                                $Delivery = 0; 
                                $total = 0;
                            @endphp
                            @foreach($groupedData as $data)
                                <tr>
                                    <td style="text-align:center;">{{ $i++ }}</td>
                                    <td style="text-align:center;">
                                        <a href="{{url('/admin/order/assign-order-view')}}/{{encrypt($data['agent_order_id'])}}/{{encrypt($data['agent_id'])}}" class="fawsm" target="_blank">
                                            <strong>{{ $data['agent_order_id'] }}</strong>
                                        </a>
                                    </td>
                                    {{--<td style="text-align:center;">
                                        {!! implode('<br>', $data['mapped_details']) !!} 
                                    </td>
                                    <td style="text-align:center;">
                                        {!! implode('<br>', $data['qty']) !!}
                                    </td>--}}
                                    <td style="text-align:center;">
                                        @foreach($data['mapped_details'] as $index => $detail)
                                            {{ $detail }} X {{ $data['qty'][$index] ?? 0 }}
                                            @if (!$loop->last)<br> @endif
                                        @endforeach
                                    </td>
                                    <td style="text-align:center;">{{ ucwords($data['agent_name']) }}</td>
                                    <td style="text-align:center;">{{ $data['totalPrice'] }}</td>
                                    <td style="text-align:center;">{{ $data['Deliver_charge'] }}</td>
                                    <td style="text-align:center;">{{ $data['extra'] }}</td>
                                    <td style="text-align:center;">{{ $data['reason'] }}</td>
                                    <td style="text-align:center;">{{ $data['track_no'] }}</td>
                                    <td style="text-align:center;">
                                        @if($data['status'] == 'P')
                                            <h6><span class="badge bg-danger">PENDING</span></h6>
                                        @elseif($data['status'] == 'PC')
                                            @php $mailDisable++; @endphp
                                            <h6><span class="badge bg-info">PROGRESS</span></h6>
                                        @elseif($data['status'] == 'CL')
                                            <h6><span class="badge bg-dark">CANCEL</span></h6>
                                        @elseif($data['status'] == 'H')
                                            <h6><span class="badge bg-warning">HOLD</span></h6>
                                        @elseif($data['status'] == 'S')
                                            @php $mailDisable++; @endphp
                                            <h6><span class="badge bg-primary">SHIPPED</span></h6>
                                        @elseif($data['status'] == 'D')
                                            @php $mailDisable++; @endphp
                                            <h6><span class="badge bg-success">DELIVERED</span></h6>
                                        @endif
                                    </td>
                                    <td>
                                        @if($data['isConfirmCl'] == 0 && $data['status'] == "CL")
                                            <button class="btn btn-primary btn_cancel" id="btn_cancel" ds-value="{{ $data['OrderID'] }}">Add Agent</button>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                    @foreach($groupedData as $amount)
                        @if($amount['isConfirmCl'] != 1 && $amount['status'] != "CL")
                            <!-- {{$amount['totalPrice']}} = {{$amount['extra']}} = {{$amount['Deliver_charge']}} -->
                             <!-- <br> -->
                            @php    
                                $total +=$amount['totalPrice'] + $amount['extra'] + $amount['Deliver_charge'];
                            @endphp
                         @endif
                    @endforeach

                    <div id="ReassignProduct"></div>
                    @if($order->order_delivery_status != 'CL')
                        @if($order->order_delivery_status != 'D')
                            @if($disable == $mailDisable)
                                <h3>Customer Email</h3>
                                    @php 
                                        $count = 0; 
                                        $buttonEnable = count($agentasGroupBy) + 1;
                                        $buttonCount = 1; 
                                    @endphp

                                    @foreach($agentasGroupBy as $assign)
                                        @if($assign->status != 'P')
                                            @php 
                                                $count++; 
                                                $buttonCount++; 
                                            @endphp                      
                                        @endif
                                    @endforeach
                               
                                    <table class="table">
                                        <tbody>
                                            <tr>
                                                @if($count > 0)
                                                    <td>
                                                        <select name="mail_status" id="mail_status" class="form-control mail_status">
                                                        <option value="">Select Mail Process</option>
                                                            @if($order->order_delivery_status == 'P')
                                                                <option value="PC">Progress</option>
                                                                <option value="S">Shipped</option>
                                                                <option value="D">Delivered</option>
                                                                <option value="CL">Cancel</option>
                                                            @elseif($order->order_delivery_status == 'PC')
                                                                <option value="S">Shipped</option>
                                                                <option value="D">Delivered</option>
                                                                <option value="CL">Cancel</option>
                                                            @elseif($order->order_delivery_status == 'S')
                                                                <option value="D">Delivered</option>
                                                                <option value="CL">Cancel</option>
                                                            @endif
                                                             

                                                        </select>
                                                    </td>
                                                @endif
                                                <td>
                                          
                                                </td>
                                                @if($buttonCount == $buttonEnable)
                                                    <td>
                                                    <button class="btn btn-primary" id="btn_mail_send" @if($order->order_delivery_status == 'D') Style="display:none;" @else @endif>SEND</button>
                                                    </td>
                                                @endif
                                            </tr>
                                        </tbody>
                                    </table>
                                
                            @endif
                        @endif   
                    @endif         
                    @php $grandTotal = 0; @endphp
                    @if($order->order_delivery_status == 'D')
                        @php 
                            $grandTotal = $Delivery_Price+$Extra+$Delivery+$total;
                        @endphp
                        <p><b>Paid To Agent :  {{$total}}</b></p>
                    @endif
                    @if($order->order_delivery_status == 'PC')
                        <table class="table" style="display:none;" id="AssignIds">
                            <thead>
                                <tr>
                                    <th></th>
                                    <th></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($agentasGroupBy as $assignItems)
                                    @if($assignItems->status == "CL")
                                    @else
                                    <tr>
                                        <td>
                                            <input class="form-control" name="OrderId[]" value="{{$assignItems->agent_order_id}}"/>
                                        </td>
                                        <td>
                                            <input class="form-control" name="track_no[]" value="{{$assignItems->track_no}}" />
                                        </td>
                                        <td>
                                            <input class="form-control" name="tracking_link[]" value="{{$assignItems->tracking_link}}" />
                                        </td>
                                    </tr>
                                    @endif
                                @endforeach
                            </tbody>
                        </table>
                    @endif              
            @endif
        </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;
    }

    .edit_delivery_address_section{display: none;}
    .edit_message_section{display: none;}
    .card{margin-bottom: 15px!important;}
    .msgerror{font-size:12px; color:red}
    .editinputsec{width:100%}
    .fawsm {color: #3e5569!important; }
</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="2" cols="20" style="display:none;"></textarea>
                                                            </td>
                                                            <td>
                                                                <textarea class="form-control text" id="agents[${agentIndex}][0][text][]" name="agents[${agentIndex}][0][text][]" rows="2" cols="20" 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 Instructions</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="1" cols="20" placeholder="Any Instructions"></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 {
                            $('textarea[name="agents[' + response.agentIndex + '][' + response.productIndex + '][imgLink][]"]').css('display', 'none');
                            $('textarea[name="agents[' + response.agentIndex + '][' + response.productIndex + '][text][]"]').css('display', 'none');
                            // $row.find('.imgLink').css('display', 'none');
                            // $row.find('.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();

            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="2" cols="20" style="display:none;"></textarea>
                                </td>
                                <td>
                                    <textarea class="form-control text" id="agents[${agentIndex}][${productIndex}][text][]" name="agents[${agentIndex}][${productIndex}][text][]" rows="2" cols="20" 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(){
    
        $('.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:"{{url('/admin/order/getOrderID')}}",
                type:'get',
                data:{
                    orderId:orderId,
                    reassignAggent:reassignAggent,
                },
                success:function(response){
                var agentIndex = $('#ReassignProduct .AgentAssigndProduct').length;
                console.log(agentIndex);

                var agentHTML = `
                <form action="{{url('/admin/order/ReAssignProduct')}}" method="post" id="reEnable">
                @csrf
                     <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>
                                        @foreach($agentsAfterCancel as $agent)
                                            @foreach($agent as $agents)
                                                <option value="{{$agents->id}}">{{$agents->name}}</option>
                                            @endforeach 
                                        @endforeach
                                    </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>
                                            </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>
                                            </tr>
                                            <tr>
                                                <td colspan="2">
                                                    <b>Any other requirments</b>
                                                </td>
                                            </tr>
                                            <tr>
                                                <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>
                    </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:"{{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);
            var OrderIdArray = $('[name="OrderId[]"]').map(function () {return $(this).val();}).get();
            var track_no = $('[name="track_no[]"]').map(function () {return $(this).val();}).get();
            var tracking_link = $('[name="tracking_link[]"]').map(function () {return $(this).val();}).get();

            if (OrderIdArray.some(function(val) { return val.trim() !== ''; }) ||track_no.some(function(val) { return val.trim() !== ''; }) ||tracking_link.some(function(val) { return val.trim() !== ''; })) {
                $.ajax({
                    url:"{{url('/admin/order/mailStatus')}}",
                    type:'GET',
                    data:{
                        mail_status:mail_status,
                        OrderID:OrderID,
                        OrderIdArray:OrderIdArray,
                        track_no:track_no,
                        tracking_link:tracking_link,
                    },
                    success:function(response){
                        console.log(response);
                        // location.reload();
                    },
                    error:function(error){  
                        console.log(error);
                    },
                });
            } else {
                $.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);
        });
    });

    //---------Edit Delivery Address Section----------

    $('.del-address-edit-btn').on('click', function(){
        $('.delivery_address_section').hide();
        $('.edit_delivery_address_section').show();
    });

    $('.cancel-del-address-edit-btn').on('click', function(){
        $('.delivery_address_section').show();
        $('.edit_delivery_address_section').hide();
    });

    $('.update-delivery_address').on('click', function(){
        var odr_id = $('#odr_id').val();
        var del_add_access_code = $('#del_add_access_code').val();
        var rec_name = $('#rec_name').val();
        var rec_address = $('#rec_address').val();
        var rec_city = $('#rec_city').val();
        var rec_state = $('#rec_state').val();
        var rec_zipcode = $('#rec_zipcode').val();
        var rec_phone = $('#rec_phone').val();

        if(rec_name == '' || rec_address == '' || rec_city == '' || rec_state == '' || rec_zipcode == '' || rec_phone == '' )
        {
            $('#warning-msg-del-address').html("Fill all fields");
            setTimeout(function(){ $('#warning-msg-del-address').html(""); }, 3000);
            return false;
        }

        if(del_add_access_code == ''){
            $('#warning-msg-del-address').html("Enter your access code");
            setTimeout(function(){ $('#warning-msg-del-address').html(""); }, 3000);
            return false;
        }else if(del_add_access_code != 'rspl'){
            $('#warning-msg-del-address').html("Access code didn't match");
            setTimeout(function(){ $('#warning-msg-del-address').html(""); }, 3000);
            return false;
        }

        $.ajaxSetup({
            headers: {
             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type : "POST",
            url : "{{route("admin.order.updateDeliveryAddress")}}",
            data : { odr_id : odr_id, rec_name : rec_name, rec_address : rec_address, rec_city : rec_city, rec_state : rec_state, rec_zipcode : rec_zipcode, rec_phone : rec_phone, del_add_access_code : del_add_access_code, site : $('#sitename').val() },
            success : function(response){
            response = JSON.parse(response);
            if(response.status == "success"){
              window.location.reload();
            }else if (response.status == "failed"){
                $('#warning-msg-del-address').html("Access code didn't match");
                setTimeout(function(){ $('#warning-msg-del-address').html(""); }, 3000);
                return false;
            }
            },
            error : function(){

            }
        });
    });

//---------###Edit Delivery Address Section###----------

//---------Edit Message Section----------

    $('.message-edit-btn').on('click', function(){
        $('.message_section').hide();
        $('.edit_message_section').show();
    });

    $('.cancel-message-edit-btn').on('click', function(){
        $('.message_section').show();
        $('.edit_message_section').hide();
    });

    $('.update-message').on('click', function(){
        var odr_id = $('#odr_id').val();
        var message_access_code = $('#message_access_code').val();
        var occ_type = $('#occ_type').val();
        var sender_msg = $('#sender_msg').val();
        var sender_name = $('#sender_name').val();
        var spl_inst = $('#spl_inst').val();

        if(occ_type == '' || sender_msg == '' || sender_name == '')
        {
            $('#warning-msg-del-address').html("Please Fill all fields");
            setTimeout(function(){ $('#warning-msg-message').html(""); }, 3000);
            return false;
        }

        if(message_access_code == ''){
            $('#warning-msg-message').html("Enter your access code");
            setTimeout(function(){ $('#warning-msg-message').html(""); }, 3000);
            return false;
        }else if(message_access_code != 'rspl'){
            $('#warning-msg-message').html("Access code didn't match");
            setTimeout(function(){ $('#warning-msg-message').html(""); }, 3000);
            return false;
        }

        $.ajaxSetup({
            headers: {
             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type : "POST",
            url : "{{route("admin.order.updateMessages")}}",
            data : { odr_id : odr_id, occ_type : occ_type, sender_msg : sender_msg, sender_name : sender_name, spl_inst : spl_inst, message_access_code : message_access_code, site : $('#sitename').val() },
            success : function(response){
            response = JSON.parse(response);
            if(response.status == "success"){
              window.location.reload();
            }else if (response.status == "failed"){
                $('#warning-msg-message').html("Access code didn't match");
                setTimeout(function(){ $('#warning-msg-message').html(""); }, 3000);
                return false;
            }
            },
            error : function(){

            }
        });
    });

//---------###Edit Delivery Address Section###----------



    {{-- $(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
