Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
112 kB
2
Indexable
Never
@extends('layouts.app')
@push('css')
    <style>
        .br-0 {
            border-radius: 0 !important;
        }

        button {
            white-space: normal !important;
        }
    </style>
{{--    <style>--}}
{{--        @page {--}}
{{--            margin:0cm;--}}
{{--            page-break-after: always;--}}
{{--            page-break-before: always;--}}
{{--        }--}}
{{--    </style>--}}
@endpush
@section('content')
    <form enctype="multipart/form-data"
          action="{{isset($order) ?route('cms.pos.update', $order->_id): route('cms.pos.store')}}"
          id="order_form"
          method="post">
        @csrf
        @isset($order)
            @method('PUT')
        @else
            @method('POST')
        @endisset

        <div class="row">
            <div class="col-md-12">
                {{--            name - code preferences--}}
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title"> {{$order->code??'New Order'}} </h4>
                    </div>
                    @if (!isset($order))
                        <div class="card-body">
                            <div class="form-group">
                                <label for="select_user" class="form-label">Select User </label>
                                <div class="row">
                                <input type="text" id="country_code" name="country_code" value="+974" hidden/>
                                    <div class="container" style="width: 20%;"">
                                        <div class="dropdown" id="country-codes">
                                            <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
                                                <span class="value">+974</span>
                                                <span class="caret"></span>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li><a href="#" value="">-</a></li>
                                                <li><a href="#" value="+974">Qatar (+974)</a></li>
                                                <li><a href="#" value="+966">SA (+966)</a></li>
                                                <li><a href="#" value="+971">UAE (+971)</a></li>
                                                <li><a href="#" value="+968">OMN (+968)</a></li>
                                                <li><a href="#" value="+973">BH (+973)</a></li>
                                            </ul>
                                        </div>
                                    </div>


                                    <input type="text"  class="form-control" style="width: 50%; margin-left:10px; margin-right: 10px"
                                           id="search_phone" >
                                    <button class="btn btn-secondary" type="button" onclick="checkPhone()"><i
                                            class="fe fe-search"></i></button>
                                </div>
                            </div>
                        </div>
                    @endif
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-7">
                                <label class="form-label" style="font-size: large">{{__('User Information')}}</label>
                                <div class="form-row">
                                    <div class="form-group col-md-6 mb-0">
                                        <div class="form-group">
                                            <input type="text" class="form-control readonly" id="phone"
                                                   placeholder="Phone" name="phone"
                                                   required>
                                        </div>
                                    </div>
                                    <div class="form-group col-md-6 mb-0">
                                        <div class="form-group">
                                            <input type="text" class="form-control " id="name"
                                                   placeholder="Name" name="name" required readonly>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="col-md-12 mb-0">
                                        <div class="form-group">
                                            <input type="email" class="form-control" id="email"
                                                   name="email" placeholder="Email Address" readonly>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-0">
                                        <div class="form-group">
                                            <input type="text" class="form-control" id="alias_name" name="alias_name"
                                                   placeholder="Alias Name">
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-0">
                                        <div class="form-group">
                                        <textarea style="width: 100%"
                                                  class="form-control" id="user_note" name="user_note"
                                                  placeholder="User Note"
                                        ></textarea>
                                        </div>
                                    </div>

                                    @if ( isset($order))
                                        <div class="col-md-6 mb-0">
                                            <div class="form-group">
                                                <a class="btn btn-secondary"
                                                   href="{{route('cms.user.edit',$order->user_id)}}"><i
                                                        class="fe fe-edit"></i> Edit User and Addresses</a>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-0">
                                            <label class="form-label">{{__('User Note')}}</label>
                                            <p> {{ $order->note??'' }}</p>
                                            @if ( $order->driver_option == 'wait')
                                                <p> Wait at the door</p>
                                            @elseif ( $order->driver_option == 'hang')
                                                <p> Hang it on the door</p>
                                            @endif
                                        </div>

                                    @endif

                                </div>


                            </div>

                            <div class="col-md-5">
                                <label class="form-label">{{__('User Preferences')}}
                                    @if ( isset($order))
                                        <button class="btn btn-secondary" type="button" onclick="openPreferenceModal()">
                                            <i class="fe fe-edit"></i></button>
                                    @endif
                                </label>
                                <div class="row" id="preferences-list">

                                </div>
                            </div>

                        </div>

                    </div>

                </div>
            </div>
            <div class="col-md-6">
                {{--            collection address --}}
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Pick up</h4>
                    </div>
                    <div class="card-body">
                        <div class=" form-group">
                            <label class="custom-switch">
                                <input type="checkbox" class="custom-switch-input" onchange="toggleOrderType()"
                                       id="order_type" name="express_order">
                                <span class="custom-switch-indicator"></span>
                                <span class="custom-switch-description">{{__('Express Order')}}</span>
                            </label>


                            @if (!isset($order))
                                <div class="form-group">
                                    <label class="form-label" for="user_addresses"> {{__('Source')}}</label>
                                    <select class="form-control select2-show-search"
                                            id="select_source" name="source">
                                        <option value="CMS">{{__('Industrial Area')}}</option>
                                        <option value="vendom">{{__('Vendom Mall')}}</option>
                                        <option value="rafeeq">{{__('Rafeeq')}}</option>
                                        <option value="snoonu">{{__('Snoonu')}}</option>
                                        <option hidden value="fifa_official">{{__('Fifa Official')}}</option>
                                        <option hidden value="fifa_personal">{{__('Fifa Personal')}}</option>
                                    </select>
                                </div>
                            @else

                                <div class="form-group">
                                    <label class="form-label"
                                           for="user_addresses"> {{__('Source: ').$order->source??''}}</label>
                                </div>
                            @endif

                        </div>

                        <div class="form-group ">
                            <div class="form-group">
                                <label for="collection_date" class="form-label">{{__('Date')}}</label>
                                <input type="datetime-local" onchange="setDate()" class="form-control"
                                       name="collection_date" id="collection_date" required
                                       placeholder="Collection Date">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="collection_address" class="form-label">{{__('Address')}}</label>
                            <input type="hidden" class="form-control" name="collection_address" id="collection_address"
                                   required>
                            <input type="text" class="form-control readonly" name="collection_address_show"
                                   id="collection_address_show"
                                   placeholder="Collection Address" required onclick="openAddressModal(this)">
                        </div>
                        @if( isset($order) and  $order->collector != null )
                            <div class="form-group ">
                                <div class="form-group">
                                    <label class="form-label">{{__('Collected By')}}</label>
                                    <input type="text" class="form-control"
                                           value="{{$order->collector->name ??''}}">
                                </div>
                            </div>

                            <div class="form-group ">
                                <div class="form-group">
                                    <label lass="form-label">{{__('Item Collected')}}</label>
                                    <input type="text" class="form-control"
                                           value="{{$order->items_collected??'0'}}">
                                </div>
                            </div>
                        @endif


                        <div class="form-group">
                            <label for="collection_note" class="form-label">{{__('PickUp Note')}}</label>
                            <textarea type="text" class="form-control" name="collection_note"
                                      id="collection_note">
                         </textarea>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                {{--            delievery address--}}
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Delivery</h4>
                    </div>
                    <div class="card-body">
                        <div class="form-group ">
                            <label for="delivery_date" class="form-label">{{__('Date')}}</label>
                            <div class="form-group">
                                <input type="datetime-local" class="form-control" id="delivery_date"
                                       name="delivery_date" required placeholder="Delivery Date">
                            </div>
                        </div>
                        @if (!isset($order))
                            <div class="form-group">
                                <label class="custom-switch">
                                    <input type="checkbox" name="same_address" id="same_address"
                                           class="custom-switch-input" onchange="$('#delivery_box').toggle()" checked>
                                    <span class="custom-switch-indicator"></span>
                                    <span
                                        class="custom-switch-description">{{__('Delivery Address same as Collection Address')}}</span>
                                </label>
                            </div>
                        @endif

                        <div class="form-group" id="delivery_box" @if (!isset($order))style="display: none"@endif>
                            <label for="delivery_address" class="form-label">{{__('Delivery Address')}}</label>
                            <input type="hidden" class="form-control" name="delivery_address" id="delivery_address">
                            <input type="text" class="form-control readonly" id="delivery_address_show"
                                   name="delivery_address_show"
                                   placeholder="Delivery Address" onclick="openAddressModal(this)">
                        </div>

                        @if( isset($order) and  $order->collector != null )
                            <div class="form-group">
                                <label class="form-label">{{__('Collected By')}}</label>
                                <input type="text" class="form-control"
                                       value="{{$order->collector->name ??''}}">
                            </div>
                            <div class="form-group">
                                <label class="form-label">{{__('Item Collected')}}</label>
                                <input type="text" class="form-control"
                                       value="{{$order->items_collected??'0'}}">
                            </div>
                        @endif

                        <div class="form-group">
                            <label for="delivery_note" class="form-label">{{__('Delivery Note')}}</label>
                            <textarea type="text" class="form-control" name="delivery_note"
                                      id="delivery_note">
                        </textarea>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-12">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3 form-group">
                                <label for="inv_sub_total" class="form-label"
                                       style="font-size: medium">{{__('Sub Total')}}</label>
                                <input type="number" step="0.01" class="form-control" id="inv_sub_total"
                                       placeholder="00.00" readonly>
                            </div>

                            <div class="col-md-3 form-group">
                                <label for="inv_addons" class="form-label"
                                       style="font-size: medium">{{__('Addons')}}</label>
                                <input type="number" step="0.01" class="form-control" id="inv_addons"
                                       placeholder="00.00" readonly>
                            </div>

                            <div class="col-md-3 form-group">
                                <label for="promo_code" class="form-label"
                                       style="font-size: medium">{{__('Promo Code')}}</label>
                                <input type="text" class="form-control" id="promo_code"
                                       value="{{$order->promo->code??''}} - {{$order->promo->percentage??''}}"
                                       readonly placeholder="{{__("NO PROMO")}}">
                            </div>

                            <div class="col-md-3 form-group">
                                <label for="inv_discount_percentage" class="form-label"
                                       style="font-size: medium">{{__('Discount Percentage %')}}</label>
                                <input type="number" step="0.01" class="form-control" 
                                id="inv_discount_percentage"
                                       name="discount_percentage"
                                       value="{{$order->discount_percentage??''}}"
                                       placeholder="00.00" onkeyup="refreshCalculation('percentage')">
                            </div>
                            <div class="col-md-3 form-group">
                                <label for="inv_discount_amount" class="form-label"
                                       style="font-size: medium">{{__('Discount Amount')}}</label>
                                <input type="number" class="form-control" id="inv_discount_amount"
                                       name="discount_amount"
                                       value="{{$order->discount_amount??''}}"
                                       placeholder="0" onkeyup="refreshCalculation('amount')" >
                            </div>

                            <div class="col-md-3 form-group">
                                <label for="inv_total" class="form-label"
                                       style="font-size: medium">{{__('Delivery Charge')}}</label>
                                <input type="number" step="0.01" class="form-control" id="delivery_charge"
                                       value="{{$order->delivery_charge??''}}" name="delivery_fees"
                                       placeholder="00.00" onkeyup="refreshCalculation()">
                            </div>


                            <div class="col-md-3 form-group pb-2" style="background-color: #72d2fe">
                                <label for="inv_total" class="form-label"
                                       style="font-size: medium">{{__('Total')}}</label>
                                <input type="number" step="0.01" class="form-control" id="inv_total"
                                       placeholder="00.00" readonly>
                            </div>


                            <div class="col-md-3 form-group">
                                <label for="inv_promo" class="form-label"
                                       style="font-size: medium">{{__('Promo Code Discount')}}</label>
                                <input type="text" class="form-control" id="inv_promo"
                                       placeholder="00.00" readonly>
                            </div>

                            <div class="col-md-3 form-group">
                                <label for="inv_discount" class="form-label"
                                       style="font-size: medium">{{__('Discount')}}</label>
                                <input type="number" step="2" class="form-control" id="inv_discount"
                                       placeholder="00.00" readonly>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Order Details</h4>
                    </div>
                    <div class="card-body">


                        <div id="items-list">

                        </div>

                        <div class="row">
                            <div class="col-12 ">
                                <button class="btn btn-azure mt-1 float-right" type="button" onclick="openItem()"
                                        id="add_item">{{__('Add Item')}}</button>
                            </div>

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

            <div class="col-md-6">
                {{--            actions --}}
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Actions</h4>
                    </div>
                    <div class="card-body">
                        @isset($order)
                            @if (!in_array($order->status->slug_name, ['canceled','done']))
                                <button type="button" onclick="makeAction('update')"
                                        class="btn btn-primary mt-4 mb-0">{{__('Update')}}</button>
                                <button type="button" class="btn btn-success mt-4 mb-0"
                                        onclick="makeAction('send_to_client')"
                                        @if (!in_array($order->status->slug_name ,['validation','rejected']))
                                            disabled style="cursor: unset"
                                    @endif
                                >{{__('Send Order To Client')}}</button>
                                <button type="button" onclick="makeAction('accept')"
                                        class="btn btn-primary mt-4 mb-0">{{__('Accept')}}</button>
                                <br/>
                                <button type="button" onclick="printTags()"
                                        class="btn btn-azure mt-4 mb-0">{{__('Print Tags')}}</button>
                                <button type="button" class="btn btn-dark mt-4 mb-0" onclick="makeAction('cancel')"
                                        @if (in_array($order->status->slug_name ,['processing','delivery','pending-payment']))
                                            disabled style="cursor: unset"
                                    @endif
                                >{{__('Cancel Order')}}</button>
                                {{--                                <button type="button" onclick="makeAction('force_delete')" class="btn btn-primary mt-4 mb-0">{{__('Force Delete')}}</button>--}}
                                {{--                                <a  href="{{route('order.send.pdf',$order->_id)}}" target="_blank" class="btn btn-primary mt-4 mb-0">{{__('Print AR')}}</a>--}}
                                <button type="button" onclick="printInvoice()"
                                        class="btn btn-primary mt-4 mb-0">{{__('Print Invoice')}}</button>
                                <button type="button" onclick="printReceipt()"
                                        class="btn btn-primary mt-4 mb-0">{{__('Print Receipt')}}</button>
                                <br/>

                                <button type="button" onclick="makeAction('deliver','cash')"
                                        class="btn btn-primary mt-4 mb-0">{{__('Deliver - Cash')}}</button>
                                <button type="button" onclick="makeAction('deliver','card')"
                                        class="btn btn-primary mt-4 mb-0">{{__('Deliver - Card')}}</button>
                                <button type="button" onclick="makeAction('deliver','credit')"
                                        class="btn btn-primary mt-4 mb-0">{{__('Deliver - Credit')}}</button>
                            @endif
                        @else
                            <button type="button" onclick="makeAction('update')"
                                    class="btn btn-primary mt-4 mb-0">{{__('Create')}}</button>
                            <button type="button" onclick="makeAction('collection')"
                                    class="btn btn-primary mt-4 mb-0">{{__('Create And Collect')}}</button>
                            <button type="button" onclick="makeAction('collection', 'cash')"
                                    class="btn btn-primary mt-4 mb-0">{{__('Create And Collect - cash')}}</button>
                            <button type="button" onclick="makeAction('collection','card')"
                                    class="btn btn-primary mt-4 mb-0">{{__('Create And Collect - card')}}</button>
                            <button type="button" onclick="makeAction('collection','credit')"
                                    class="btn btn-primary mt-4 mb-0">{{__('Create And Collect - credit')}}</button>
                        @endisset
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                {{--            status --}}
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Statuses</h4>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label class="form-label">{{__('Payment Status')}}</label>
                            <input type="text" class="form-control" readonly
                                   value="{{$order->payment_type??'-'}} : {{$order->payment_status??'-'}}">
                        </div>
                        <div class="form-group">
                            <label class="form-label">{{__('Current Status')}}</label>
                            <input type="text" class="form-control" readonly
                                   value="{{$order->status->name??'-'}}">
                        </div>
                        @if (isset($order) and in_array($order->status->slug_name, ['delivery']))
                            <div class="form-group">
                                <button type="button" onclick="makeAction('back_to_shop')"
                                        class="btn btn-primary mt-4 mb-0">{{__('Back To Shop')}}</button>
                            </div>
                        @endif
                    </div>
                </div>
            </div>

        </div>
    </form>

    <div class="modal" id="addressModal">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content modal-content-demo">
                <div class="modal-header">
                    <h6 class="modal-title" id="modal_address_title"></h6>
                    <button aria-label="Close" class="close" data-dismiss="modal" type="button"><span
                            aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-12">
                            <div class="form-group">
                                <label class="form-label" for="user_addresses"> {{__('User Addresses')}}</label>
                                <select class="form-control select2-show-search"
                                        data-placeholder="{{__('User Addresses')}}"
                                        id="user_addresses" onchange="selectAddress(this)">
                                    <option value="">{{__('Select Address')}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <input type="hidden" class="form-control"
                               id="old_content">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="modal_address_name" class="form-label">{{__('Address Name')}}</label>
                                <input type="text" class="form-control"
                                       id="modal_address_name" required>
                            </div>
                            <div class="form-group">
                                <label for="modal_address_zone" class="form-label">{{__('Address Zone')}}</label>
                                <input type="text" class="form-control"
                                       id="modal_address_zone" required>
                            </div>
                            <div class="form-group">
                                <label for="modal_address_building"
                                       class="form-label">{{__('Address Building')}}</label>
                                <input type="text" class="form-control"
                                       id="modal_address_building" required>
                            </div>
                            <div class="form-group">
                                <label for="modal_address_additional_info"
                                       class="form-label">{{__('Address Nearest Landmark')}}</label>
                                <input type="text" class="form-control"
                                       id="modal_address_additional_info">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="modal_address_area" class="form-label">{{__('Address Area')}}</label>
                                <input type="text" class="form-control"
                                       id="modal_address_area" required>
                            </div>
                            <div class="form-group">
                                <label for="modal_address_street" class="form-label">{{__('Address Street')}}</label>
                                <input type="text" class="form-control"
                                       id="modal_address_street" required>
                            </div>
                            <div class="form-group">
                                <label for="modal_address_number"
                                       class="form-label">{{__('Address Flat/Villa#')}}</label>
                                <input type="text" class="form-control"
                                       id="modal_address_number" required>
                            </div>
                        </div>

                        <div class="col-md-12">
                            <div class="form-group" style="padding: 10px">
                                <input type="text" id="modal_address_map"
                                       class="form-control map_input" required>
                                <input type="hidden" id="modal_address_location"/>
                                <div id="modal-address-map-container" style="width:100%;height:400px; ">
                                    <div style="width: 100%; height: 100%" id="modal-address-map"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row " id="error_address_message_box" style="display: none">
                        <div class="col">
                            <div class="bg-danger-transparent-2 text-danger px-4 py-2 br-3 mb-4"
                                 role="alert" id="error_address_message"></div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-indigo" id="modal_address_btn_set" type="button" onclick="setAddress(this)"
                            data-id="">{{__('Set')}}</button>
                    <button class="btn btn-light" data-dismiss="modal" type="button">Close</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal" id="preferencesModel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content modal-content-demo">
                <form enctype="multipart/form-data"
                      action="{{route('cms.ajax.set-user-pre', $order->_id??"-1")}}"
                      method="post">
                    @csrf
                    <div class="modal-header">
                        <h6 class="modal-title" id="user_pre_title">Preferences </h6>
                        <button aria-label="Close" class="close" data-dismiss="modal" type="button"><span
                                aria-hidden="true">&times;</span></button>
                    </div>
                    <div class="modal-body">

                        <div class="row" id="user_pre">

                        </div>

                        <div class="row " id="error_user_pre_box" style="display: none">
                            <div class="col">
                                <div class="bg-danger-transparent-2 text-danger px-4 py-2 br-3 mb-4"
                                     role="alert" id="error_user_pre_message"></div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-light" type="submit">Update</button>
                        <button class="btn btn-light" data-dismiss="modal" type="button">Close</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal" id="itemModal">
        <div class="modal-dialog" style="max-width: 80%;" role="document">
            <div class="modal-content modal-content-demo">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-5">
                            <div class="row border-primary mb-2" style="border: 1px solid;min-height: 60px">
                                <label class="col-12 form-label" style="font-size: medium">{{__('Categories')}}</label>
                                @foreach($modal_categories as $category)
                                    <button
                                        class="col-4 btn btn-outline-primary br-0 py-3 mc-categories mc-{{$category->_id}}"
                                        onclick="showItems('{{$category->_id}}')">
                                        {{$category->name}}
                                    </button>
                                @endforeach
                                <button class="col-4 btn btn-outline-primary br-0 py-3 mc-categories "
                                        onclick="selectCustomItem()">
                                    Custom Item
                                </button>
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="category"> {{ __('Items') }}</label>
                                <select class="form-control select2-show-search"
                                    data-placeholder="{{ __('Select Item') }}" id="select_category"
                                     onchange="selectCategoryItem(this)">
                                    <option value="">{{ __('Select Item') }}</option>
                                </select>
                            </div>

                            <div class="row border-primary mb-2" >
                                {{-- <label class="col-12 form-label" style="font-size: medium">{{__('Items')}}</label> --}}
                                @foreach($modal_items as $item)
                                    <button
                                        class="col-4 btn btn-outline-primary br-0 py-3 mi-items mi-{{$item->category_id}}"
                                        onclick="showTypes('{{$item->_id}}')" id="item-{{$item->_id}}"
                                        data-id="{{$item->_id}}" data-value="{{json_encode($item)}}">
                                        {{$item->name}}
                                    </button>
                                @endforeach
                            </div>
                            <div class="row border-primary" style="border: 1px solid;min-height:60px">
                                <label class="col-12 form-label" style="font-size: medium">{{__('Service')}}</label>
                                <button class="col-4 btn btn-outline-primary br-0 py-3 mt-type mt-pressing"
                                        onclick="selectType(this)" data-value="p">
                                    Pressing
                                </button>
                                <button class="col-4 btn btn-outline-primary br-0 py-3 mt-type mt-press-wash"
                                        onclick="selectType(this)" data-value="pw">
                                    Press & Wash
                                </button>
                                <button class="col-4 btn btn-outline-primary br-0 py-3 mt-type mt-dry-clean"
                                        onclick="selectType(this)" data-value="dc">
                                    Dry Clean
                                </button>
                                <button class="col-4 btn btn-outline-primary br-0 py-3 mt-type mt-dry-clean"
                                onclick="selectType(this)" data-value="c">
                                Cleaning
                                </button>
                                {{--                                <button class=" btn btn-outline-primary m-1 py-3 mt-type mt-folding"--}}
                                {{--                                        onclick="toggleFolding(this)" data-value="folding">--}}
                                {{--                                    Folding--}}
                                {{--                                </button>--}}
                            </div>

                        </div>
                        <div class="col-3">

                            <div class="row pl-5 pr-5 pb-2">
                                <div class="row border-primary" style="border: 1px solid;min-height:60px">

                                    <input class="col-12 text-center form-control-lg  br-0" step="2" type="text"
                                           id="modal_quantity">

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value.toString() + '1';">
                                        1
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value.toString() + '2';">
                                        2
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value.toString() + '3';">
                                        3
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value.toString() + '4';">
                                        4
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value.toString() + '5';">
                                        5
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value.toString() + '6';">
                                        6
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value.toString() + '7';">
                                        7
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value.toString() + '8';">
                                        8
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value.toString() + '9';">
                                        9
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value='';">
                                        Clear
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=document.getElementById('modal_quantity').value.toString() + '0';">
                                        0
                                    </button>

                                    <button type="button" class="col-4 btn btn-outline-primary br-0 py-3 modal-number"
                                            onclick="document.getElementById('modal_quantity').value=
                                            !document.getElementById('modal_quantity').value.toString().includes('.')?(document.getElementById('modal_quantity').value.toString() + '.')
                                            :document.getElementById('modal_quantity').value.toString() ;">
                                        .
                                    </button>

                                </div>
                            </div>
                            <div class="row pl-5 pr-5 pb-2 ">
                                <div class="row border-primary" style="border: 1px solid;min-height:60px">
                                    <label class="col-12 form-label" style="font-size: medium">{{__('Note')}}</label>
                                    <textarea style="width: 90%;margin:5%" id="item_note"></textarea>
                                </div>
                            </div>
                            <div class="row pl-5 pr-5 pb-2 ">
                                <div class="row border-primary" style="border: 1px solid;min-height:60px">
                                    <label class="col-12 form-label"
                                           style="font-size: medium">{{__('Item Images')}}</label>
                                    <input type="file"
                                           multiple
                                           data-height="180"
                                           id="modal_image"/>

                                </div>
                            </div>


                        </div>
                        <div class="col-4">
                            <div class="row border-primary" style="border: 1px solid;min-height:60px">
                                <label class="col-12 form-label" style="font-size: medium">{{__('Addons')}}</label>
                                @foreach($addons as $addon)
                                    <button class="col-4 btn btn-outline-primary br-0 py-3 mi-addons mi-{{$addon->_id}}"
                                            onclick="toggleAddon('{{$addon->_id}}')"
                                            id="addon-{{$addon->_id}}" style="display: none">
                                        {{$addon->name}} <span class="price"></span>
                                    </button>
                                @endforeach
                            </div>

                            <div class="row border-primary mt-2" style="border: 1px solid;min-height:60px">
                                <div class="col-12 form-group" id="custom_item_box" style="display: none">
                                    <label for="modal_custom_item" class="form-label">{{__('Name')}}</label>
                                    <input type="text" step="2" class="form-control"
                                           id="modal_custom_item">
                                </div>

                                <div class="col-12 form-group">
                                    <label for="modal_unit" class="form-label" style="font-weight:600">{{__('Unit')}}</label>
                                    <input id="modal_unit" type="checkbox" class="form-control" 
                                    data-toggle="switchbutton" checked data-onlabel="Kg" data-offlabel="SqM" data-onstyle="success" data-offstyle="outline-info">
                                </div>

                                <div class="col-12 form-group" id="kgs">
                                    <label for="modal_width" class="form-label">{{__('Kgs')}}</label>
                                    <input type="number" step="2" class="form-control" id="modal_kg" onchange="makeRowCalculation()">
                                </div>

                                <div class="col-12 form-group" id="sqm">
                                    <label for="modal_width" class="form-label">{{__('Width')}}</label>
                                    <input type="number" class="form-control" id="modal_width" onchange="makeRowCalculation()">
                                    <br/>
                                    <label for="modal_height" class="form-label">{{__('Height')}}</label>
                                    <input type="number" class="form-control" id="modal_height" onchange="makeRowCalculation()">
                                </div>

                                <div class="col-12 form-group">
                                    <label for="modal_price" class="form-label">{{__('Price')}}</label>
                                    <input type="number" step="2" class="form-control"
                                           onchange="makeRowCalculation()"
                                           id="modal_price">
                                </div>
                                <div class="col-12 form-group">
                                    <label for="modal_total" class="form-label">{{__('Total')}}</label>
                                    <input type="text" class="form-control"
                                           id="modal_total" readonly>
                                </div>

                                <div class="col-12 form-group">
                                    <label for="modal_discount" class="form-label">{{__('Discount %')}}</label>
                                    <input type="number" step="0.01" class="form-control"
                                           onchange="makeRowCalculation()"
                                           id="modal_discount">
                                </div>

                                <div class="col-12 form-group">
                                    <label for="modal_discount_amount" class="form-label">{{__('Discount Amount')}}</label>
                                    <input type="number" step="0.01" class="form-control"
                                           onchange="makeRowCalculationAmount()"
                                           id="modal_discount_amount">
                                </div>

                                <div class="col-12 form-group">
                                    <label for="modal_addons" class="form-label">{{__('Addons')}}</label>
                                    <input type="text" class="form-control" readonly
                                           id="modal_addons">
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button class="btn btn-indigo" id="modal_address_btn_set" type="button"
                            onclick="setItem()" data-id="">{{__('Set')}}</button>
                    <button class="btn btn-light" data-dismiss="modal" type="button">Close</button>
                </div>
            </div>
        </div>
    </div>
    <div id="printJS-div"></div>
@endsection

@once
    @push('css')
        <link href="../../assets/plugins/fancyuploder/fancy_fileupload.css" rel="stylesheet"/>
        <link href="../../assets/plugins/fileupload/css/fileupload.css" rel="stylesheet" type="text/css"/>
        <link href="../../assets/plugins/select2/select2.min.css" rel="stylesheet"/>
        <link href="../../assets/plugins/time-picker/jquery.timepicker.css" rel="stylesheet"/>
        <link href="../../assets/plugins/date-picker/date-picker.css" rel="stylesheet"/>
        <link href="../../assets/plugins/fileupload/css/fileupload.css" rel="stylesheet" type="text/css"/>
        <link rel="stylesheet" type="text/css" href="https://printjs-4de6.kxcdn.com/print.min.css">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui@4.0/dist/fancybox.css"/>
        <link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap-switch-button@1.1.0/css/bootstrap-switch-button.min.css" rel="stylesheet">
        <style>
            #printJS-div {
                display: none;
            }

            .modal {
                z-index: 1001 !important;
            }

            .modal-backdrop {
                z-index: 1000 !important;
            }

            .pac-container {
                z-index: 1055 !important;
            }

            .single-item {
                padding: 10px 0;
            }

            .single-item:nth-child(even) {
                background-color: #e2e2e2;
            }

            .mi-items {
                font-size: 12px;
            }
        </style>
    @endpush

    @push('js')
        <!--Print js -->
        <script src="https://printjs-4de6.kxcdn.com/print.min.js"></script>
        <!--Select2 js -->
        <script src="../../assets/plugins/select2/select2.full.min.js"></script>
        <!-- Timepicker js -->
        <script src="../../assets/plugins/time-picker/jquery.timepicker.js"></script>
        <script src="../../assets/plugins/time-picker/toggles.min.js"></script>
        <!-- Datepicker js -->
        <script src="../../assets/plugins/date-picker/date-picker.js"></script>
        <script src="../../assets/plugins/date-picker/jquery-ui.js"></script>
        <script src="../../assets/plugins/input-mask/jquery.maskedinput.js"></script>
        <!-- fancybox js -->
        <script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui@4.0/dist/fancybox.umd.js"></script>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"
                integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA=="
                crossorigin="anonymous" referrerpolicy="no-referrer"></script>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script>
        <script
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD09iSHyrRM-3QoqXubT6bCSQRcawyCYKo&libraries=places&callback=initialize"
            async defer></script>

        <!-- File uploads js -->
        <script src="../../assets/plugins/fileupload/js/dropify.js"></script>
        <script src="../../assets/js/filupload.js"></script>
        <script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap-switch-button@1.1.0/dist/bootstrap-switch-button.min.js"></script>

        <script type="text/javascript">
            $("#modal_unit").change(function(){
                $("#modal_width").val('');
                $("#modal_height").val('');
                $("#modal_kg").val('');
                if($(this).prop("checked") == true){
                    /* If KG is true, hide width and height */
                    $('#sqm').hide();
                    $('#kgs').show();
                }else{
                    /* If KG is false, show width and height */
                    $('#kgs').hide();
                    $('#sqm').show();
                }
                makeRowCalculation()
            });

             $('#country-codes li a').on('click', function() {
                $('#country-codes button span.value').text($(this).attr('value'));
                $('input[id="country_code"]').val($(this).attr('value'));
            });

        
            $("#modal_discount").keyup(function() {
                $(this).blur();
                $(this).focus();
            });
            $("#modal_discount").change(function(){
                var itemPrice = $('#modal_price').val();
                var itemPricePercentage = $('#modal_discount').val();
                var discount_amount = (itemPrice) * (itemPricePercentage) / 100;  
           
                $("#modal_discount_amount").val(discount_amount.toFixed(2));
                makeRowCalculation();
            }); 

            $("#modal_discount_amount").keyup(function() {
                $(this).blur();
                $(this).focus();
            });
            $("#modal_discount_amount").change(function(){
                var itemPrice = $('#modal_price').val();
                var itemDiscountPrice = $('#modal_discount_amount').val();

                var percentage = ((itemDiscountPrice)/ (itemPrice)) * 100;  
         
                $("#modal_discount").val(percentage.toFixed(2));
                makeRowCalculation();
            }); 


            function setDate() {
                let date = new Date($("#collection_date").val() + "Z");
                if ($('#order_type').prop("checked"))
                    date.setDate(date.getDate() + 1)
                else {
                    date.setDate(date.getDate() + 2)
                }
                $("#delivery_date").val(date.toJSON().slice(0, 16));
            }

            $(function () {
                $('.modal-number').on('click', function () {
                    makeRowCalculation()
                })
            })

            let modalSelectedItem, oldModalSelectedItem, modalSelectedFolding, modalSelectedType;
            let orderItems = [];
            let zones = [];
            let promoCode = null;
            let addonsList = [];
            let retail = true;
            let allAddons = @json($addons);

            function walkInToggle() {
                let walkin = $('#walk_in').is(':checked');
                if (walkin) {
                    let address = @json(\App\Models\StaticInfo::query()->first()->address??'{}');
                    $('#collection_address').val(JSON.stringify(address));
                    $('#collection_address_show').val(address.name);
                    $('#delivery_address').val(JSON.stringify(address));
                    $('#delivery_address_show').val(address.name);
                    let now = new Date();
                    now.setHours(now.getHours() + 3);
                    $("#collection_date").val(now.toJSON().slice(0, 16));

                    let date = new Date($("#collection_date").val() + "Z");
                    if ($('#order_type').prop("checked"))
                        date.setDate(date.getDate() + 1)
                    else {
                        date.setDate(date.getDate() + 2)
                    }
                    $("#delivery_date").val(date.toJSON().slice(0, 16));
                } else {
                    $('#collection_address_show').val('');
                    $('#collection_address').val('');
                    $('#delivery_address_show').val('');
                    $('#delivery_address').val('');
                }
            }

            function checkPhone() {
                $('#user_no_result').hide();
                let phone = $('#search_phone').val();
                let countryCode = $('#country_code').val();
               
                let formattedPhone = countryCode+phone;
           
                $.ajax({
                    type: 'GET',
                    url: '{{route('cms.ajax.pos-check-user')}}/' + formattedPhone,
                    dataType: 'json', 

                }).done(function (result) {
                    $('#preferences-list').html('');
                    if (result.user != null) {
                        let user = result.user;
                        $('#phone').val(phone);
                        $('#user_id').val(user._id);
                        $('#name').val(user.name);
                        $('#email').val(user.email);
                        $('#name').attr('readonly', 'readonly');
                        $('#email').attr('readonly', 'readonly');
                        if (Array.isArray(user.preferences_list)) {
                            user.preferences_list.forEach(function (item) {
                                let div = '<div class="col-6">' +
                                    item.question.name + ':';
                                if (item.question.type == "image") {
                                    div += '<a href="' + item.answer + '" target="_blank">Open Image</a> <br/>';
                                } else {
                                    div += JSON.stringify(item.answer) + '<br/>';
                                }
                                div += '</div>';
                                $('#preferences-list').append(div);
                            });
                        }
                        retail = !(user.is_business_acoount == true || user.is_business_account == 'true');

                    } else {
                        $('#phone').val(phone);
                        $('#user_id').val('');
                        $('#name').val('');
                        $('#email').val('');
                        $('#name').removeAttr('readonly');
                        $('#email').removeAttr('readonly');
                        $('#user_no_result').show();

                    }

                }).fail(function (data) {

                });
            }

            function getPreferences() {


                $.ajax({
                    type: 'GET',
                    url: '{{route('cms.ajax.get-user-pre', $order->user_id??'-1')}}',
                    dataType: 'text',

                }).done(function (result) {

                    if (result != null) {
                        $('#user_pre').html(result)
                    }

                }).fail(function (data) {

                });
            }

            function openPreferenceModal() {
                $('#preferencesModel').modal().show();
                getPreferences()
            }

            function getAddresses() {
                let phone = $('#search_phone').val();
                @if ( $order??null  != null )
                    phone = '{{$order->user->phone}}'
                @endif
                $('#user_addresses').empty();
                $('#user_addresses').select2({
                    placeholder: "{{__('Select Address')}}",
                    allowClear: true
                });

                $.ajax({
                    type: 'GET',
                    url: '{{route('cms.ajax.addresses-user')}}/' + phone,
                    dataType: 'json',

                }).done(function (result) {

                    if (result.addresses != null) {
                        $('#user_addresses').append($('<option>', {
                            value: "",
                            text: "{{__('Select Address')}}"
                        }));
                        $.each(result.addresses, function (i, item) {
                            $('#user_addresses').append($('<option>', {
                                value: JSON.stringify(item),
                                text: item.name
                            }));
                        });

                    }

                }).fail(function (data) {

                });
            }

            function openAddressModal(input) {
                $('#addressModal').modal().show();
                getAddresses();
                var content = $('#' + input.id.replace("_show", "")).val()
                    .replace('"{', '{').replace('}"', '}').split('\\').join('');


                if (content !== '') {
                    let values = JSON.parse(content);
                    $('#old_content').val(JSON.stringify(values));
                    $('#modal_address_name').val(values.name);
                    $('#modal_address_area').val(values.area);
                    $('#modal_address_zone').val(values.zone);
                    $('#modal_address_building').val(values.building);
                    $('#modal_address_number').val(values.number);
                    $('#modal_address_street').val(values.street);
                    $('#modal_address_title').html(input.placeholder);
                    $('#modal_address_location').val(values.coordinates);
                    $('#modal_address_map').val(values.coordinates);
                    $('#modal_address_btn_set').data('id', input.id);
                    $('#modal_address_additional_info').val(values.additional_info);

                } else {
                    $('#modal_address_name').val('');
                    $('#modal_address_area').val('');
                    $('#modal_address_zone').val('');
                    $('#modal_address_building').val('');
                    $('#modal_address_number').val('');
                    $('#modal_address_street').val('');
                    $('#modal_address_title').html(input.placeholder);
                    $('#modal_address_location').val('');
                    $('#modal_address_btn_set').data('id', input.id);
                    $('#modal_address_additional_info').val('');

                }
            }

            function setAddress(btn) {
                $('#error_address_message').html("")
                $('#error_address_message_box').hide()
                if ($(btn).data('id') != null) {
                    let content = ""
                    try {
                        content = JSON.parse($('#old_content').val());
                    } catch (e) {

                    }

                    if (content !== '') {

                    } else {
                        content = {}
                    }

                    if ($('#modal_address_name').val() == '') {
                        $('#error_address_message').html("Name Field is required")
                        $('#error_address_message_box').show()
                        return false;
                    }

                    if ($('#modal_address_area').val() == '') {
                        $('#error_address_message').html("Area Field is required")
                        $('#error_address_message_box').show()
                        return false;
                    }

                    if ($('#modal_address_zone').val() == '') {
                        $('#error_address_message').html("Zone Field is required")
                        $('#error_address_message_box').show()
                        return false;
                    }

                    if ($('#modal_address_building').val() == '') {
                        $('#error_address_message').html("Building Field is required")
                        $('#error_address_message_box').show()
                        return false;
                    }

                    if ($('#modal_address_number').val() == '') {
                        $('#error_address_message').html("Number Field is required")
                        $('#error_address_message_box').show()
                        return false;
                    }

                    if ($('#modal_address_street').val() == '') {
                        $('#error_address_message').html("Street Field is required")
                        $('#error_address_message_box').show()
                        return false;
                    }
                    if ($('#modal_address_location').val() == '') {
                        $('#error_address_message').html("Location Field is required")
                        $('#error_address_message_box').show()
                        return false;
                    }

                    content.name = $('#modal_address_name').val();
                    content.area = $('#modal_address_area').val();
                    content.zone = $('#modal_address_zone').val();
                    content.building = $('#modal_address_building').val();
                    content.number = $('#modal_address_number').val();
                    content.street = $('#modal_address_street').val();
                    content.coordinates = $('#modal_address_location').val();
                    content.additional_info = $('#modal_address_additional_info').val();

                    $('#' + $(btn).data('id').replace("_show", '')).val(JSON.stringify(content));
                    $('#' + $(btn).data('id')).val($('#modal_address_name').val());
                    $('#addressModal').modal('toggle');
                }
            }

            function selectAddress(select) {
                if ($(select).val() !== '') {
                    var values = JSON.parse($(select).val());
                    $('#old_content').val($(select).val());
                    $('#modal_address_name').val(values.name);
                    $('#modal_address_name').prop('readonly', true);
                    $('#modal_address_area').val(values.area);
                    $('#modal_address_area').prop('readonly', true);
                    $('#modal_address_zone').val(values.zone);
                    $('#modal_address_zone').prop('readonly', true);
                    $('#modal_address_building').val(values.building);
                    $('#modal_address_building').prop('readonly', true);
                    $('#modal_address_number').val(values.number);
                    $('#modal_address_number').prop('readonly', true);
                    $('#modal_address_street').val(values.street);
                    $('#modal_address_street').prop('readonly', true);
                    $('#modal_address_additional_info').val(values.additional_info);
                    $('#modal_address_additional_info').prop('readonly', true);
                    try {
                        $('#modal_address_location').val(values.coordinates[0] + "," + values.coordinates[1]);
                        $('#modal_address_map').val(values.coordinates[0] + "," + values.coordinates[1]);
                        $('#modal_address_map').prop('readonly', true);
                    } catch (e) {

                    }

                } else {
                    $('#modal_address_name').val('');
                    $('#modal_address_name').removeProp('readonly');
                    $('#modal_address_name').removeAttr('readonly');
                    $('#modal_address_area').val('');
                    $('#modal_address_area').removeProp('readonly');
                    $('#modal_address_area').removeAttr('readonly');
                    $('#modal_address_zone').val('');
                    $('#modal_address_zone').removeProp('readonly');
                    $('#modal_address_zone').removeAttr('readonly');
                    $('#modal_address_building').val('');
                    $('#modal_address_building').removeProp('readonly');
                    $('#modal_address_building').removeAttr('readonly');
                    $('#modal_address_number').val('');
                    $('#modal_address_number').removeProp('readonly');
                    $('#modal_address_number').removeAttr('readonly');
                    $('#modal_address_street').val('');
                    $('#modal_address_street').removeProp('readonly');
                    $('#modal_address_street').removeAttr('readonly');
                    $('#modal_address_location').val('');
                    $('#modal_address_location').removeProp('readonly');
                    $('#modal_address_location').removeAttr('readonly');
                    $('#modal_address_map').val('');
                    $('#modal_address_map').removeProp('readonly');
                    $('#modal_address_map').removeAttr('readonly');
                    $('#modal_address_additional_info').val('');
                    $('#modal_address_additional_info').removeProp('readonly');
                    $('#modal_address_additional_info').removeAttr('readonly');
                }
            }

            function randomString(length) {
                var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');

                if (!length) {
                    length = Math.floor(Math.random() * chars.length);
                }

                var str = '';
                for (var i = 0; i < length; i++) {
                    str += chars[Math.floor(Math.random() * chars.length)];
                }
                return str;
            }

            function openItem() {
                if ( !retail ) {
                    confirm("This account is corporate, save the order first to get the account prices");
                    return;
                }
         
                $('#itemModal').modal().show();
                showItems()
                showTypes()
                drawItems()
                selectType()
                modalSelectedItem = null;
                oldModalSelectedItem = null;
                modalSelectedType = null;
                modalSelectedFolding = false;
                addonsList = [];
                fetchAddons(null, null)
                $('#modal_discount').val('');
                $('#modal_discount_amount').val('');
                $('#modal_custom_item').val('');
                $('#modal_quantity').val('');
                $('#modal_price').val('');
                $('#modal_total').val('');
                $('#item_note').val('');
                $('#modal_image').val('');

            }

            function showItems(id = null) {
                if ($('#custom_item_box').is(":visible")) {
                    $('#custom_item_box').toggle()
                }
                getCategoryItems(id);
                $('.mc-categories').removeClass('active');
                $('.mc-' + id).addClass('active');
                $('.mi-items').hide();
                // $('.mi-' + id).show();
                modalSelectedItem = null;
                modalSelectedType = null;
                modalSelectedFolding = false;
                $('#modal_price').val(0);
                makeRowCalculation()
            }

            function selectCategoryItem(item) {
                if ($(item).val() !== '') {
                    var values = JSON.parse($(item).val());
                    showTypes(values._id);
                }
            }

            function getCategoryItems(category_id) {
                $('#select_category').empty();
                $('#select_category').select2({
                    placeholder: "{{ __('Select Item') }}",
                    allowClear: true
                });

                $.ajax({
                    type: 'GET',
                    url: '{{ route('cms.ajax.get_category_items') }}/' + category_id,
                    dataType: 'json',

                }).done(function(result) {

                    if (result.category_items != null) {
                        $('#select_category').append($('<option>', {
                            value: "",
                            text: "{{ __('Select Item') }}"
                        }));
                        $.each(result.category_items, function(i, item) {
                            $('#select_category').append($('<option>', {
                                value: JSON.stringify(item),
                                text: item.name
                            }));
                        });

                    }

                }).fail(function(data) {

                });
            }

            function showTypes(id = null) {
                $('.mt-type').hide()
                let item = $('#item-' + id).data('value');
                $('.mi-items').removeClass('active');
                $('#item-' + id).addClass('active');
                let expressOrder = $('#order_type').is(':checked');
                if (id == null) return;
                //
                // if ( item.price_folding != null )
                //     $('.mt-folding').show()
                // else
                //     $('.mt-folding').hide()

                if (!expressOrder) {
                    if (item.price_p != null)
                        $('.mt-pressing').show()
                    else
                        $('.mt-pressing').hide()
                    if (item.price_pw != null)
                        $('.mt-press-wash').show()
                    else
                        $('.mt-press-wash').hide()
                    if (item.price_dc != null)
                        $('.mt-dry-clean').show()
                    else
                        $('.mt-dry-clean').hide()
                } else {
                    if (item.price_p_e != null)
                        $('.mt-pressing').show()
                    else
                        $('.mt-pressing').hide()
                    if (item.price_pw_e != null)
                        $('.mt-press-wash').show()
                    else
                        $('.mt-press-wash').hide()
                    if (item.price_dc_e != null)
                        $('.mt-dry-clean').show()
                    else
                        $('.mt-dry-clean').hide()
                }
                if (item != modalSelectedItem) {
                    addonsList = [];
                }
                modalSelectedItem = item;
                fetchAddons(item.addons != null ? item.addons['item'] : null,
                    item.addons != null ? item.addons['price'] : null)
            }

            function fetchAddons(addons, prices) {
                $('.mi-addons').hide();
                $('.mi-addons').removeClass('active');
                if (addons != null)
                    addons.forEach(function (item) {
                        $('#addon-' + item).show();
                        $('#addon-' + item).find('.price').html('');
                        $('#addon-' + item).find('.price')
                            .html(' (' + prices[addons.indexOf(item)] + ')');
                    });
                addonsList.forEach(function (item) {
                    $('#addon-' + item).addClass('active');

                });
            }

            function toggleAddon(item) {
                if ($('#addon-' + item).hasClass('active')) {
                    if (addonsList.includes(item)) {
                        addonsList = addonsList.filter(function (it) {
                            return it !== item
                        })
                    }
                    $('#addon-' + item).removeClass('active')
                } else {
                    if (!addonsList.includes(item)) {
                        addonsList.push(item);
                    }
                    $('#addon-' + item).addClass('active')
                }

                makeRowCalculation()
            }

            function selectType(id = null) {
                $('.mt-type').removeClass('active');
                $(id).addClass('active');

                if (id != null) {
                    modalSelectedType = $(id).data('value');
                    setModalPrice();
                } else {
                    modalSelectedType = null;
                }

                makeRowCalculation()
            }

            function selectCustomItem() {
                showItems();
                $('#custom_item_box').toggle()
            }

            function setModalPrice() {
                let expressOrder = $('#order_type').is(':checked');
                let choice = expressOrder ? (modalSelectedType + "_e") : modalSelectedType;
                let price = 0;
                switch (choice) {
                    case 'p':
                        price = modalSelectedItem.price_p;
                        break;
                    case 'p_e':
                        price = modalSelectedItem.price_p_e;
                        break;
                    case 'pw':
                        price = modalSelectedItem.price_pw;
                        break;
                    case 'pw_e':
                        price = modalSelectedItem.price_pw_e;
                        break;
                    case 'dc':
                        price = modalSelectedItem.price_dc;
                        break;
                    case 'dc_e':
                        price = modalSelectedItem.price_dc_e;
                        break;
                    case 'c':
                        price = modalSelectedItem.price_c;
                    case 'c_e':
                        price = modalSelectedItem.price_c_e;
                    break;
                }
                $('#modal_price').val(price)
                makeRowCalculation()
            }

            function makeRowCalculation() {
                $('#modal_total').val(0);
                $('#modal_addons').val(0);
                let quantity = parseInt($('#modal_quantity').val());
                if (isNaN(quantity)) return;
                let price = parseFloat($('#modal_price').val());
                let addonPrice = 0;
                addonsList.forEach(function (ad) {
                    addonPrice += parseFloat(modalSelectedItem.addons['price'][modalSelectedItem.addons['item']
                        .indexOf(ad)]);
                });
                let sub_total = quantity * price;
                let addons_total = quantity * addonPrice;
                let discount_price = 0;
                if (!isNaN($('#modal_discount').val()))
                    discount_price = (sub_total + addons_total) * $('#modal_discount').val() / 100;
                var total = 0
                var width = $('#modal_width').val();
                var height = $('#modal_height').val();
                var kgs = $('#modal_kg').val();
                if (kgs != '') {
                    // When Kgs are given
                    total = (kgs * sub_total) + addons_total - discount_price
                } else if (isNaN(width) || isNaN(height) || width == '' || height == '') {
                    // inside normal flow
                    total = (sub_total + addons_total) - discount_price
                } else {
                    // When SqM are given
                    total = (width * height * sub_total) + addons_total - discount_price
                }
            
                $('#modal_total').val((total).toFixed(2))
                $('#modal_addons').val((addons_total).toFixed(2))
                refreshCalculation()

            }

            /* function makeRowCalculationAmount() {
                $('#modal_total').val(0);
                $('#modal_addons').val(0);
                let quantity = parseInt($('#modal_quantity').val());
                if (isNaN(quantity)) return;
                let price = parseFloat($('#modal_price').val());
                let addonPrice = 0;
                addonsList.forEach(function (ad) {
                    addonPrice += parseFloat(modalSelectedItem.addons['price'][modalSelectedItem.addons['item']
                        .indexOf(ad)]);
                });
                let sub_total = quantity * price;
                let addons_total = quantity * addonPrice;
                let discount_price = 0;
                if (!isNaN($('#modal_discount_amount').val()))
                    discount_price = $('#modal_discount_amount').val();

                $('#modal_total').val(((sub_total + addons_total) - discount_price).toFixed(2))
                $('#modal_addons').val((addons_total).toFixed(2))
                refreshCalculation()
            } */

            function toggleOrderType() {
                let expressOrder = $('#order_type').is(':checked');
                orderItems.forEach(function (item) {
                    item.express_order = expressOrder;
                    if (item.item._id !== 0) {
                        let choice = expressOrder ? (item.item_type + "_e") : item.item_type;
                        let price = 0;
                        switch (choice) {
                            case 'p':
                                price = item.item.price_p;
                                break;
                            case 'p_e':
                                price = item.item.price_p_e;
                                break;
                            case 'pw':
                                price = item.item.price_pw;
                                break;
                            case 'pw_e':
                                price = item.item.price_pw_e;
                                break;
                            case 'dc':
                                price = item.item.price_dc;
                                break;
                            case 'dc_e':
                                price = item.item.price_dc_e;
                                break;
                        }
                        item.price = price;
                        item.sub_total = item.quantity * price;
                        item.discount_total = item.quantity * price * item.discount / 100;
                        item.folding_total = item.quantity * item.item.price_folding;
                        item.total = item.sub_total + item.folding_total - item.discount_total;

                    }
                })
                drawItems()
            }

            async function setItem() {
                if (isNaN($('#modal_quantity').val())) return;
                let expressOrder = $('#order_type').is(':checked');
                let item = {};
                try {
                    item = JSON.parse(JSON.stringify(oldModalSelectedItem));
                } catch (e) {

                }
                if (item == null || item == undefined)
                    item = {};

                let quantity = parseInt($('#modal_quantity').val());
                let discountPer = parseFloat(isNaN($('#modal_discount').val()) || $('#modal_discount').val() == ''  ||   $('#modal_discount').val() == undefined? 0 : $('#modal_discount').val());                
                let discountAmt = parseFloat(isNaN($('#modal_discount_amount').val()) || $('#modal_discount_amount').val() == ''  ||   $('#modal_discount_amount').val() == undefined? 0 : $('#modal_discount_amount').val());
               
                let price = parseFloat(isNaN($('#modal_price').val() || $('#modal_price').val() == '') ? 0 : $('#modal_price').val());
                if ( quantity == 0 || price == 0)return;
                let addonsPrice = 0;
                addonsList.forEach(function (ad) {
                    addonsPrice += parseFloat(modalSelectedItem.addons['price'][modalSelectedItem.addons['item']
                        .indexOf(ad)]);
                });

                if (modalSelectedItem != null) {
                    item.quantity = quantity;
                    item.price = price;
                    item.item_type = modalSelectedType;
                    item.folding = 0;
                    item.express_order = expressOrder;
                    item.item = modalSelectedItem;
                    item.addons_total = quantity * addonsPrice;
                    item.sub_total = quantity * price;
                    item.folding_total = 0;
                    let total = (item.sub_total + item.addons_total);
                   
                    item.discount_amount = discountAmt;
            
                    item.discount_total = (total * discountPer / 100);
                    item.discount = discountPer;
         
                    item.total = total - item.discount_total;
                    item.addons = addonsList;
                    item.item_note = $('#item_note').val();

                    orderItems = orderItems.filter(function (ob, index, arr) {
                        return JSON.stringify(ob) !== JSON.stringify(oldModalSelectedItem);
                    });

                } else {
                    if ($('#modal_custom_item').val() == '') return;
                    item.quantity = quantity;
                    item.discount = discount;
                    item.price = !isNaN(price) ? price : 0;
                    item.item_type = null;
                    item.folding = 0;
                    item.express_order = expressOrder;
                    item.item = {
                        _id: 0,
                        name: $('#modal_custom_item').val(),
                        price: $('#modal_price').val(),
                    };
                    item.addons_total = 0;
                    item.sub_total = quantity * price;
                    item.discount_total = quantity * price * discount / 100;
                    item.folding_total = 0;
                    item.total = item.sub_total + item.folding_total - item.discount_total;
                    item.addons = addonsList;
                    item.item_note = $('#item_note').val();
                }

                try {

                    for (let i = 0; i < $('#modal_image')[0].files.length; i++) {
                        let file = $('#modal_image')[0].files.item(i);
                        var f = await getBase64(file);
                        if (item.images == undefined) item.images = [];
                        item.images.push(f);
                    }


                } catch (e) {

                }

                orderItems.push(item)
                drawItems()
                modalSelectedItem = null;
                oldModalSelectedItem = null;
                modalSelectedType = null;
                modalSelectedFolding = false;
                $('#modal_discount').val('');
                $('#modal_discount_amount').val('');
                $('#modal_custom_item').val('');
                $('#modal_quantity').val('');
                $('#modal_price').val('');
                $('#modal_addons').val('');
                $('#modal_total').val('');
                showTypes()
                $('#itemModal').modal('toggle');
            }

            function drawItems() {
                $('#items-list').html('');
                let expressOrder = $('#order_type').is(':checked');
                orderItems.forEach(function (item) {
                    let type = '';
                    let choice = expressOrder ? (item.item_type + "_e") : item.item_type;
                    switch (choice) {
                        case 'p':
                            type = 'Pressing';
                            break;
                        case 'p_e':
                            type = 'Pressing';
                            break;
                        case 'pw':
                            type = 'Pressing & Wash';
                            break;
                        case 'pw_e':
                            type = 'Pressing & Wash';
                            break;
                        case 'dc':
                            type = 'Dry Clean';
                            break;
                        case 'dc_e':
                            type = 'Dry Clean';
                            break;
                    }
                    let itemrow = randomString(10);
                    let addonsString = ''
                    if (item.addons != null)
                        item.addons.forEach(function (it) {
                            allAddons.forEach(function (itt) {
                                if (itt._id == it) {
                                    let p = item.item.addons['price'][item.item.addons['item']
                                        .indexOf(it)] * item.quantity;
                                    addonsString += (addonsString == '' ? '' : ', ') + itt.name + ' (' + p + ')';
                                }

                            })
                        });
                    let div = '<div class="row single-item">' +
                        '<input value="" id="' + itemrow + '" type="hidden"/>';
                    div += '<label class="col-6"><strong>' + item.item.name + ' [' + type + ']</strong></label>';
                    div += '<label class="col-6">( Price )&nbsp;<strong>' + item.price + '</strong> &nbsp;X&nbsp; (QTY)&nbsp;<strong>' + item.quantity + '</strong> &nbsp;= &nbsp;<strong>' + item.total.toFixed(2) + '</strong></label>';

                    div += '<label class="col-6"> Addons: <strong>' + addonsString + '</strong></label>';
                    
                    div += '<label class="col-2"> Discount Amount: <strong>' + item.discount_total.toFixed(2) + ' (' + (item.discount==undefined?0: item.discount) + '%)</strong></label>';
                  
                    div += '<div class="col-1 btn btn-danger" onclick="deleteItem(this)"><i class="fa fa-trash"></i></div>';
                    div += '<div class="col-1 ml-1 btn btn-info" onclick="updateItem(this)"><i class="fa fa-edit"></i></div>';
                    @if (isset($order) and  $order != null )
                        div += '<div class="col-1 ml-1 btn btn-success" onclick="printTags(this)"><i class="fa fa-tags"></i></div>';
                    @endif
                        div += '<label class="col-12"> Note: <strong>' + (item.item_note != '' &&
                    item.item_note != undefined ? item.item_note : '') + '</strong></label>';
                    div += '<label class="col-12"> Zone(s): <strong>' + (zones != undefined &&
                    zones[item.item._id] != undefined ? zones[item.item._id] : '') + '</strong></label>';
                    if (item.images != '' &&
                        item.images != undefined) {
                        item.images.forEach(function (it) {
                            div += '<a data-fancybox href="{{asset("")}}' + it + '" style="margin-inline-start:10px"> Image</a>';
                        })
                    }

                    div += '<br/></div>';

                    $('#items-list').append(div);
                    $('#' + itemrow).val(JSON.stringify(item));

                })
                refreshCalculation()
            }

            function deleteItem(event) {
                let item = $(event).closest('.single-item').find('input').val();
                orderItems = orderItems.filter(function (ob, index, arr) {
                    return JSON.stringify(ob) !== item;
                });
                drawItems()
            }

            function updateItem(event) {

                oldModalSelectedItem = JSON.parse($(event).closest('.single-item').find('input').val());
                $('#itemModal').modal().show();
                $('#sqm').hide();
                showItems(oldModalSelectedItem.item.category_id)
                showTypes(oldModalSelectedItem.item._id)
                selectType($('#itemModal').find('button[data-value="' + oldModalSelectedItem.item_type + '"]'))
                
              
                $('#modal_discount').val(oldModalSelectedItem.discount);
                $('#modal_discount_amount').val(oldModalSelectedItem.discount_amount);

                if (oldModalSelectedItem.item._id == 0) {
                    selectCustomItem()
                }
                addonsList = oldModalSelectedItem.addons;
                fetchAddons(oldModalSelectedItem.item.addons != null ? oldModalSelectedItem.item.addons['item'] : null,
                    oldModalSelectedItem.item.addons != null ? oldModalSelectedItem.item.addons['price'] : null)
                $('#modal_custom_item').val(oldModalSelectedItem.item.name);
                $('#modal_quantity').val(oldModalSelectedItem.quantity);
                $('#modal_price').val(oldModalSelectedItem.price);
                $('#modal_total').val(oldModalSelectedItem.total);
            
                $('#modal_addons').val(oldModalSelectedItem.addons_total);
                $('#item_note').val(oldModalSelectedItem.item_note == undefined ? '' : oldModalSelectedItem.item_note);
            }

            @if (isset($order) and  $order != null )

            $('#collection_address').val('{!! json_encode($order->collection_address) !!}');
            $('#collection_address_show').val('{{$order->collection_address['name']}}');
            $('#collection_date').val('{{str_replace(' ','T',$order->collection_date)}}');
            $('#delivery_date').val('{{str_replace(' ','T',$order->delivery_date)}}');
            if ('{{$order->express_order}}' === '1')
                $('#order_type').attr('checked', 'checked');
            $('#delivery_address').val('{!! json_encode($order->delivery_address) !!}');
            $('#delivery_address_show').val('{{$order->delivery_address['name']}}');
            $('#phone').val('{{$order->user->phone??''}}');
            $('#name').val('{{$order->user->name??''}}');
            $('#email').val('{{$order->user->email??''}}');
            $('#alias_name').val('{{$order->user->alias_name??''}}');
            $('#collection_note').html('{{$order->collection_note??''}}');
            $('#delivery_note').html('{{$order->delivery_note??''}}');
            $('#user_note').html("{!!  str_replace(array("\r", "\n"), ' ', $order->user->user_note??'') !!} ");
            $('#user_id').val('{{$order->user->_id??''}}');

            orderItems = @json($order->orderDetails);
            zones = @json($order->zones??'{}');
            drawItems()
            @endif

 function refreshCalculation(type) {
    let promoCodePercentage = parseFloat('{{$order->promo->percentage??0}}');
    let deliveryCharge = parseFloat($('#delivery_charge').val() == '' || isNaN($('#delivery_charge').val()) ? 0 : $('#delivery_charge').val());
    let discountPercentage = parseFloat($('#inv_discount_percentage').val() == '' || isNaN($('#inv_discount_percentage').val()) ? 0 : $('#inv_discount_percentage').val());
    let discountAmount = parseFloat($('#inv_discount_amount').val() == '' || isNaN($('#inv_discount_amount').val()) ? 0 : $('#inv_discount_amount').val());
    let sub_total = 0;
    let addons = 0;

    // For percentage, item.discount_amount needs to be taken into account
 
    orderItems.forEach(function (item) {
        sub_total += item.sub_total * (100 - (item.discount == undefined ? 0 : item.discount)) / 100;
        addons += item.addons_total * (100 - (item.discount == undefined ? 0 : item.discount)) / 100;
    });

    // Calculate discount based on either percentage or amount
    let discount;
    if (discountAmount > 0) {
        discount = discountAmount;
        discountPercentage = (discountAmount / (sub_total + addons)) * 100;
        $('#inv_discount_percentage').val(discountPercentage.toFixed(2));
    } 
    else if (!discountAmount && type == "amount"){
        discountPercentage = 0
        discount = 0
        $('#inv_discount_percentage').val(discountPercentage.toFixed(2));
    }
    else {
        discount = (sub_total + addons) * discountPercentage / 100;
        
    }

    let promo_discount = (sub_total + addons) * promoCodePercentage / 100;
    let total = (sub_total + addons) - discount - promo_discount + deliveryCharge;

    $('#inv_total').val(total.toFixed(2));
    $('#inv_discount').val(discount.toFixed(2));
    $('#inv_promo').val(promo_discount.toFixed(2));
    $('#inv_addons').val(addons.toFixed(2));
    $('#inv_sub_total').val(sub_total.toFixed(2));
} 

/* function refreshCalculation(){
            let promoCodePercentage = parseFloat('{{$order->promo->percentage??0}}');
            let deliveryCharge = parseFloat( $('#delivery_charge').val() == '' || isNaN($('#delivery_charge').val()) ? 0: $('#delivery_charge').val());
            let discountPercentage = parseFloat($('#inv_discount_percentage').val() == '' || isNaN($('#inv_discount_percentage').val()) ? 0: $('#inv_discount_percentage').val());
            let sub_total = 0;
            let addons = 0;

            orderItems.forEach(function(item){
                sub_total+= item.sub_total * ( 100 - item.discount ) /100;
                addons += item.addons_total * ( 100 - item.discount ) /100;
            })
            let discount = (sub_total+addons) * discountPercentage /100;
            let promo_discount =  (sub_total+addons) * promoCodePercentage / 100;
            let total =  (sub_total+addons) - discount - promo_discount + deliveryCharge;

            $('#inv_total').val( total.toFixed(2));
            $('#inv_discount').val( discount.toFixed(2));
            $('#inv_promo').val( promo_discount.toFixed(2));
            $('#inv_addons').val( addons.toFixed(2));
            $('#inv_sub_total').val( sub_total.toFixed(2));


        } */

            function makeAction(action, type= null) {
                swal({
                    title: "Are you sure?",
                    text: "",
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                }).then((willDelete) => {
                    if (!willDelete) {
                        return false;
                    } else {
                        var route = $('#order_form').attr('action');
                        var formData = $("#order_form").serializeArray();

                        formData.push({name: 'action', value: action})
                        formData.push({name: 'payment_type', value: type})
                        formData.push({name: 'order_details', value: JSON.stringify(orderItems)})
                        console.log({formData})
                        $.ajax({
                            url: route,
                            type: "POST",
                            data: formData,
                            success: function (data) {
                                if (action == 'update' || action == 'accept') {
                                    window.location.href = '{{route('cms.pos.order',$order->_id??'null')}}';
                                } else {
                                    window.location.href = '{{route('cms.order.index')}}';
                                }

                            },
                            error: function (data) {
                                swal(
                                    'Error!',
                                    data.responseJSON.message,
                                    'error'
                                );
                            }
                        });
                    }
                });
            }

            function printReceipt() {
                @if (isset($order) and  $order != null)
                $.ajax({
                    type: 'GET',
                    url: '{{route('cms.ajax.pos.invoice-printer', ['id' => $order->_id])}}',
                    dataType: 'json',
                }).done(function (result) {
                    if (result.view != null) {
                        document.getElementById('printJS-div').innerHTML = result.view;
                        printJS({
                            printable: 'printJS-div',
                            type: 'html',
                            onPrintDialogClose: () => {
                                document.getElementById('printJS-div').innerHTML = ''
                            },
                        });
                    }
                }).fail(function (result) {

                });
                @endif
            }

            function printInvoice() {
                @if (isset($order) and  $order != null)
                $.ajax({
                    type: 'GET',
                    url: '{{route('ajax.pos.order.print', ['order_id' => $order->_id])}}',
                    dataType: 'json',
                }).done(function (result) {
                    if (result.view != null) {
                        document.getElementById('printJS-div').innerHTML = result.view;
                        printJS({
                            printable: 'printJS-div',
                            type: 'html',
                            onPrintDialogClose: () => {
                                document.getElementById('printJS-div').innerHTML = ''
                            },
                        });
                    }
                }).fail(function (result) {

                });
                @endif
            }

            function printTags(event = null) {
                @if (isset($order) and  $order != null )
                let url = '{{route('cms.ajax.pos.print-tags', ['order_id' => $order->_id])}}';

                if (event != null) {
                    let item = JSON.parse($(event).closest('.single-item').find('input').val());
                    url += '/' + item.item._id;
                }

                $.ajax({
                    type: 'GET',
                    url: url,
                    dataType: 'json',
                }).done(function (result) {
                    if (result.views != null && result.views) {
                        recursivePrintIndex = 0;
                        recursivePrint(result.views)
                    }
                }).fail(function (data) {

                });

                @endif
            }

            var recursivePrintIndex = 0
            function recursivePrint(views) {
                if (views.length == recursivePrintIndex) {
                    recursivePrintIndex = 0
                    return;
                }
                // recursivePrintIndex++;
                // printDiv(views[recursivePrintIndex]);
                document.getElementById('printJS-div').innerHTML = views[recursivePrintIndex];
                printJS({
                    printable: 'printJS-div',
                    type: 'html',
                    onPrintDialogClose: () => {
                        document.getElementById('printJS-div').innerHTML = ''
                        recursivePrintIndex++;
                        recursivePrint(views);
                    },
                });
            }
            function printDiv(text) {
                var a = window.open('', '', 'height=3cm, width=7cm');
                a.document.write('<html>');
                a.document.write('<body >');
                a.document.write(text);
                a.document.write('</body></html>');
                a.document.close();
                a.print();
            }

            function initialize() {
                $('form').on('keyup keypress', function (e) {
                    var keyCode = e.keyCode || e.which;
                    if (keyCode === 13) {
                        e.preventDefault();
                        return false;
                    }
                });
                let latitude = 0;
                let longitude = 0
                try {
                    latitude = parseFloat(document.getElementById("modal_address_location").value.split(',')[0]) || -33.8688;
                    longitude = parseFloat(document.getElementById("modal_address_location").value.split(',')[1]) || 151.2195;
                } catch (e) {

                }
                const map = new google.maps.Map(document.getElementById("modal-address-map"), {
                    center: {lat: latitude, lng: longitude},
                    zoom: 13,
                    mapTypeId: "roadmap",
                });
                // Create the search box and link it to the UI element.
                const input = document.getElementById("modal_address_map");
                const searchBox = new google.maps.places.SearchBox(input);
                map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
                // Bias the SearchBox results towards current map's viewport.
                map.addListener("bounds_changed", () => {
                    searchBox.setBounds(map.getBounds());
                });
                let markers = [];
                // Listen for the event fired when the user selects a prediction and retrieve
                // more details for that place.
                searchBox.addListener("places_changed", () => {
                    const places = searchBox.getPlaces();

                    if (places.length == 0) {
                        return;
                    }
                    if (places.length == 1) {
                        const lat = places[0].geometry.location.lat();
                        const lng = places[0].geometry.location.lng();
                        setLocationCoordinates(lat, lng);
                        @if (!isset($order) )
                        const service = new google.maps.places.PlacesService(map);

                        const request = {
                            placeId: places[0].place_id,
                            fields: ["ALL"],
                        };

                        service.getDetails(request, (place, status) => {
                            if (
                                status === google.maps.places.PlacesServiceStatus.OK &&
                                place &&
                                place.geometry &&
                                place.geometry.location
                            ) {
                                fillAddress(place)
                            }
                        });
                        @endisset
                    }
                    // Clear out the old markers.
                    markers.forEach((marker) => {
                        marker.setMap(null);
                    });
                    markers = [];
                    // For each place, get the icon, name and location.
                    const bounds = new google.maps.LatLngBounds();
                    places.forEach((place) => {
                        if (!place.geometry || !place.geometry.location) {
                            console.log("Returned place contains no geometry");
                            return;
                        }
                        const icon = {
                            url: place.icon,
                            size: new google.maps.Size(71, 71),
                            origin: new google.maps.Point(0, 0),
                            anchor: new google.maps.Point(17, 34),
                            scaledSize: new google.maps.Size(25, 25),
                        };
                        // Create a marker for each place.
                        markers.push(
                            new google.maps.Marker({
                                map,
                                icon,
                                title: place.name,
                                position: place.geometry.location,
                            })
                        );

                        if (place.geometry.viewport) {
                            // Only geocodes have viewport.
                            bounds.union(place.geometry.viewport);
                        } else {
                            bounds.extend(place.geometry.location);
                        }
                    });
                    map.fitBounds(bounds);
                });
            }

            function setLocationCoordinates(lat, lng) {
                const location = document.getElementById("modal_address_location");
                location.value = lat + "," + lng;
            }

            function fillAddress(place) {
                for (elem in place.address_components) {
                    if (place.address_components[elem].types[0] == "route") {
                        $('#modal_address_street').val(place.address_components[elem].long_name)
                    }
                    if (place.address_components[elem].types[0] == "sublocality_level_1") {
                        $('#modal_address_area').val(place.address_components[elem].long_name)
                    }
                    if (place.address_components[elem].types[0] == "locality") {
                        $('#modal_address_zone').val(place.address_components[elem].long_name)
                    }

                }
                $('#modal_address_additional_info').val(place.formatted_address)
            }


            function getBase64(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = () => resolve(reader.result);
                    reader.onerror = error => reject(error);
                });
            }


        </script>
    @endpush
@endonce
Leave a Comment