@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>
                                    <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</h4>
                            
                            <P>
                                <?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';
                                    }
                                ?>
                            </P>
                        </div>
                    </div>
                    <div class="col-lg-6">
                      <div class="info-box card" style="padding: 10px 12px;">
                        <h4>Billing Address</h4>
                        <p>
                            <?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';
                                }
                            ?>
                        </p>
                      </div>
                    </div>

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

                            <h4>Message Section</h4>
                            
                            <p>
                                {{-- <strong>Message Purpose:</strong> {{ $order_dtl->order_message->message_purpose }}
                                <br>
                                <strong>Occasion Type: </strong>{{ $order_dtl->order_message->occasion_type }}
                                <br> --}}
                                <strong>Sender Message: </strong>{{ $order_dtl->order_message->sender_message }}
                                <br>
                                <strong>Sender Name:</strong> {{ $order_dtl->order_message->sender_name }}
                                {{-- <br>
                                <strong>Relation to Recipient: </strong>{{ $order_dtl->order_message->relation_to_recipient }}--}}
                                <br>
                                <strong>Special Instruction: </strong>{{ $order_dtl->order_message->sender_special_instruction }}
                                <br>
                                {{--@if($order_dtl->order_message->sender_demand != '')
                                    <span style="color: red; font-weight: bold;">**Note: </strong>{{ $order_dtl->order_message->sender_demand }}
                                @endif --}}
                            </p>
                            
                        </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']) }}
                                                <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}}">
                                                        <svg id='Interface_Files_Folder_Copy_File_24' width='24' height='24' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><rect width='24' height='24' stroke='none' fill='#000000' opacity='0'/>
                                                            <g transform="matrix(1.43 0 0 1.43 12 12)" >
                                                            <g style="" >
                                                            <g transform="matrix(1 0 0 1 -2.51 -1.96)" >
                                                            <path style="stroke: rgb(0,0,0); stroke-width: 1; stroke-dasharray: none; stroke-linecap: round; stroke-dashoffset: 0; stroke-linejoin: round; stroke-miterlimit: 4; fill: none; fill-rule: nonzero; opacity: 1;" transform=" translate(-4.49, -5.04)" d="M 1.30563 9.58887 L 1.30563 1.40889 C 1.30563 0.906922 1.71255 0.5 2.21451 0.5 L 7.66783 0.5" stroke-linecap="round" />
                                                            </g>
                                                            <g transform="matrix(1 0 0 1 1.43 1.4)" >
                                                            <path style="stroke: rgb(0,0,0); stroke-width: 1; stroke-dasharray: none; stroke-linecap: round; stroke-dashoffset: 0; stroke-linejoin: round; stroke-miterlimit: 4; fill: none; fill-rule: nonzero; opacity: 1;" transform=" translate(-8.43, -8.4)" d="M 4.16087 12.5001 L 4.16087 4.30151 C 4.16087 3.74923 4.60858 3.30151 5.16086 3.30151 L 9.59328 3.30151 C 9.97968 3.30151 10.3503 3.45501 10.6235 3.72824 L 12.2676 5.16426 C 12.5409 5.43749 12.6944 5.80807 12.6944 6.19448 L 12.6944 12.5001 C 12.6944 13.0524 12.2467 13.5001 11.6944 13.5001 L 5.16087 13.5001 C 4.60858 13.5001 4.16087 13.0524 4.16087 12.5001 Z" stroke-linecap="round" />
                                                            </g>
                                                            <g transform="matrix(1 0 0 1 4.12 -2.27)" >
                                                            <path style="stroke: rgb(0,0,0); stroke-width: 1; stroke-dasharray: none; stroke-linecap: round; stroke-dashoffset: 0; stroke-linejoin: round; stroke-miterlimit: 4; fill: none; fill-rule: nonzero; opacity: 1;" transform=" translate(-11.12, -4.73)" d="M 9.56613 3.30005 L 9.56613 6.1619 L 12.6665 6.1619" stroke-linecap="round" />
                                                            </g>
                                                            </g>
                                                            </g>
                                                        </svg>
                                                    </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">
                                                        <svg id='Interface_Files_Folder_Copy_File_24' width='24' height='24' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><rect width='24' height='24' stroke='none' fill='#000000' opacity='0'/>
                                                            <g transform="matrix(1.43 0 0 1.43 12 12)" >
                                                            <g style="" >
                                                            <g transform="matrix(1 0 0 1 -2.51 -1.96)" >
                                                            <path style="stroke: rgb(0,0,0); stroke-width: 1; stroke-dasharray: none; stroke-linecap: round; stroke-dashoffset: 0; stroke-linejoin: round; stroke-miterlimit: 4; fill: none; fill-rule: nonzero; opacity: 1;" transform=" translate(-4.49, -5.04)" d="M 1.30563 9.58887 L 1.30563 1.40889 C 1.30563 0.906922 1.71255 0.5 2.21451 0.5 L 7.66783 0.5" stroke-linecap="round" />
                                                            </g>
                                                            <g transform="matrix(1 0 0 1 1.43 1.4)" >
                                                            <path style="stroke: rgb(0,0,0); stroke-width: 1; stroke-dasharray: none; stroke-linecap: round; stroke-dashoffset: 0; stroke-linejoin: round; stroke-miterlimit: 4; fill: none; fill-rule: nonzero; opacity: 1;" transform=" translate(-8.43, -8.4)" d="M 4.16087 12.5001 L 4.16087 4.30151 C 4.16087 3.74923 4.60858 3.30151 5.16086 3.30151 L 9.59328 3.30151 C 9.97968 3.30151 10.3503 3.45501 10.6235 3.72824 L 12.2676 5.16426 C 12.5409 5.43749 12.6944 5.80807 12.6944 6.19448 L 12.6944 12.5001 C 12.6944 13.0524 12.2467 13.5001 11.6944 13.5001 L 5.16087 13.5001 C 4.60858 13.5001 4.16087 13.0524 4.16087 12.5001 Z" stroke-linecap="round" />
                                                            </g>
                                                            <g transform="matrix(1 0 0 1 4.12 -2.27)" >
                                                            <path style="stroke: rgb(0,0,0); stroke-width: 1; stroke-dasharray: none; stroke-linecap: round; stroke-dashoffset: 0; stroke-linejoin: round; stroke-miterlimit: 4; fill: none; fill-rule: nonzero; opacity: 1;" transform=" translate(-11.12, -4.73)" d="M 9.56613 3.30005 L 9.56613 6.1619 L 12.6665 6.1619" stroke-linecap="round" />
                                                            </g>
                                                            </g>
                                                            </g>
                                                        </svg>
                                                    </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;">
                                                    
                                                    {{ ucwords($addon_value['product_name']) }}
                                                    <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.';
            }

            //$assignDtl = App\Http\Helper1::assignOrderDtl($order_dtl->id);
        ?>



        {{-- <div class="row gy-4">
            <div class="col-xl-12">
                <div class="row">
                    <div class="col-lg-12">
                        <h4>Update Order Status:</h4>
                    </div>

                    <div class="info-box card" style="padding: 10px 12px;">
                        <div class="row">
                            <div class="col-9">
                                <select class="form-control" name="updatestatus" id="updatestatus">
                                    @foreach($status_array as $key => $value)
                                        <option value="{{$key}}" @if($order_dtl->order_delivery_status == $key) selected @endif >{{$value}}</option>
                                    @endforeach
                                </select>
                                
                                <input type="hidden" name="oid" id="oid" value="{{$order_dtl->id}}">
                                <input type="hidden" name="uoid" id="uoid" value="{{$order_dtl->unique_order_id}}">
                                <input type="hidden" name="ostatus" id="ostatus" value="{{$order_dtl->order_delivery_status}}">
                            </div>
                            <div class="col-3">
                                <button type="button" class="btn btn-success update-status">Submit</button>
                            </div>
                        </div>

                        @if($assignDtl)
                        <div class="row trackidrow" style="padding: 10px 12px; display: none;">
                            <div class="col-9">
                                <input type="text" class="form-control" name="trackingId" id="trackingId" placeholder="Tracking Id" value="{{$assignDtl->agent_tracking_id}}">
                            </div>
                        </div>
                        @endif

                        @if($assignDtl)
                        <div class="row tracklinkrow" style="padding: 10px 12px; display: none;">
                            <div class="col-9">
                                <input type="text" class="form-control" name="trackingLink" id="trackingLink" placeholder="Tracking Link" value="{{$assignDtl->agent_tracking_link}}">
                            </div>
                        </div>
                        @endif

                        <div class="row holdrow" style="padding: 10px 12px; display: none;">
                            <div class="col-9">
                                <input type="text" class="form-control" name="holdreason" id="holdreason" placeholder="Hold Reason" value="{{$order_dtl->hold_reason}}">
                            </div>
                        </div>
                    </div>
                </div>

                

                
            </div>
        </div> --}}



        @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;">
                                <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-primary" 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 del-address-edit-btn" 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,
                                            '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</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;">{{ $data['agent_order_id'] }}</td>
                                    <td style="text-align:center;">
                                        {!! implode('<br>', $data['mapped_details']) !!} X  {!! implode('<br>', $data['qty']) !!}
                                    </td>
                                    <td style="text-align:center;">
                                        {!! implode('<br>', $data['qty']) !!}
                                    </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;
    }
</style>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

            //     // console.log(selectedValues); 

            // if (selectedValues === 0) {    

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

                // console.log(agentIndex);

                    $.ajax({
                        url: "{{ url('/admin/order/getAgentId') }}", 
                        type: 'GET',
                        data: { 
                            // agent_id: agent_id,
                            agentsArray: selectedValues,
                            agentIndex:agentIndex,
                        },
                        success: function(response) {

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

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

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

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

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

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

                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td></td>
                                            <td>
                                                <table class="table TotalProductPrice">
                                                    <thead>
                                                        <tr>
                                                            <th>Delivery Date</th>
                                                            <th>Delivery Time</th>
                                                        </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>
                                                        <td colspan="2">
                                                            <b>Any other requirments</b>
                                                        </td>
                                                        <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>`;

                                    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="4" cols="50" style="display:none;"></textarea>
                                </td>
                                <td>
                                    <textarea class="form-control text" id="agents[${agentIndex}][${productIndex}][text][]" name="agents[${agentIndex}][${productIndex}][text][]" rows="4" cols="50" style="display:none;"></textarea>
                                </td>
                                <td>
                                    <button class="btn btn-danger btn_removeProduct">(-)</button>
                                </td>
                            </tr>`;

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

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

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

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

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

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

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

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

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

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

<script>
    $(document).ready(function(){
    
        $('.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);
        });
    });

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