<x-master-layout :assets="$assets ?? []">
    <?php $id = $id ?? null;?>
    @if(isset($id))
        {!! Form::model($data, ['route' => ['order.update', $id], 'method' => 'patch', 'id' => 'order_form']) !!}
    @else
        {!! Form::open(['route' => ['order.store'], 'method' => 'post', 'id' => 'order_form']) !!}
    @endif
     {{ Form::hidden('client_id',auth()->user()->id) }}
     {{ Form::hidden('status','create') }}
     <input type="hidden" id="fixed_charges" name="fixed_charges">
     <input type="hidden" id="total_amount" name="total_amount">
     <input type="hidden" id="total_distance" name="total_distance">
     <input type="hidden" id="weight_charge" name="weight_charge">
     <input type="hidden" id="distance_charge" name="distance_charge">
     <input type="hidden" id="extra_charges" name="extra_charges">

    <div class="card">
        <div class="card-header d-flex justify-content-between">
            <div class="header-title">
                <h4 class="card-title">{{ $pageTitle }}</h4>
            </div>
        </div>
        <div class="row ml-4">
            <a id="deliverNowBtn" class="btn btn-sm btn-primary m-2 mt-1 p-1"><i class="fa fa-clock"></i> {{ __('message.deliver_now') }}</a>
            <a id="calendarBtn" class="btn btn-sm m-2 mt-1 p-1"><i class="fa fa-calendar"></i> {{ __('message.schedule') }}</a>
        </div>
        <div class="card-body">
            <div class="new-user-info">
                <div class="form-group" id="scheduleSection" style="display: none;">
                    <div class="row">
                        <div class="col-md-6">
                            <h4 class="card-title">{{ __('message.pick_time') }}</h4>
                            <div class="card card-block">
                                <div class="card-header">
                                    <div class="form-group row">
                                        <div class="col-md-12">
                                            {{ Form::date('pickup_date', old('pickup_date'), ['placeholder' => __('message.date'), 'class' => 'form-control min-datepicker_tomorrow']) }}
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <div class="col-md-6">
                                            {{ Form::time('pickup_start_time', old('start_time'), ['placeholder' => __('message.from'), 'class' => 'form-control min-timerange-picker','id' => 'pickup_start_time']) }}
                                            <span class="text-danger" id="form_validation_pickup_start_time"></span>
                                        </div>
                                        <div class="col-md-6">
                                            {{ Form::time('pickup_end_time', old('end_time'), ['placeholder' => __('message.to'), 'class' => 'form-control min-timerange-picker', 'id' => 'pickup_end_time']) }}
                                            <span class="text-danger" id="form_validation_pickup_end_time"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h4 class="card-title">{{ __('message.deliver_time') }}</h4>
                            <div class="card card-block">
                                <div class="card-header">
                                    <div class="form-group row">
                                        <div class="col-md-12">
                                            {{ Form::date('delivery_date', old('date'), ['placeholder' => __('message.date'), 'class' => 'form-control min-datepicker_tomorrow']) }}
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <div class="col-md-6">
                                            {{ Form::time('delivery_start_time', old('time'), ['placeholder' => __('message.from'), 'class' => 'form-control min-timerange-picker','id' => 'delivery_start_time']) }}
                                            <span class="text-danger" id="form_validation_delivery_start_time"></span>
                                        </div>
                                        <div class="col-md-6">
                                            {{ Form::time('delivery_end_time', old('time'), ['placeholder' => __('message.to'), 'class' => 'form-control min-timerange-picker','id'=> 'delivery_end_time']) }}
                                            <span class="text-danger" id="form_validation_delivery_end_time"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="form-group col-md-4" id="parcel_type">
                        {{ Form::label('parcel_type', __('message.parcel_type'). ' <span class="text-danger">*</span>',['class' => 'form-control-label'],false) }}
                        {{ Form::text('parcel_type', old('parcel_type'), ['id' => 'parcel_type_text', 'placeholder' => __('message.name'), 'class' => 'form-control', 'required']) }}
                        <div class="row ml-3" id="parcel_type_container" style="display: none;">
                            @foreach ($staticData as $key)
                                <div class="m-1 border border-secondary pl-1 pr-1 mr-1 default-hidden rounded" onclick="setParcelType('{{ $key->label }}')" style="cursor: pointer;">{{ $key->label }}</div>
                            @endforeach
                        </div>
                    </div>

                    <div class="form-group col-md-4">
                        {{ Form::label('total_weight', __('message.weight'). ' <span class="text-danger">*</span>',['class' => 'form-control-label' ],false) }}
                        {{ Form::number('total_weight', $data->total_wight ?? null , [ 'class' => 'form-control', 'min' => 1, 'step' => 'any', 'required', 'placeholder' => __('message.weight') ]) }}
                    </div>
                    <div class="form-group col-md-4">
                        {{ Form::label('total_parcel', __('message.number_of_parcels'). ' <span class="text-danger">*</span>', ['class' => 'form-control-label' ],false) }}
                        {{ Form::number('total_parcel', $data->total_distance ?? null , [ 'class' => 'form-control', 'min' => 1, 'step' => 'any', 'required', 'placeholder' => __('message.number_of_parcels') ]) }}
                    </div>
                </div>

                <div class="row">
                    <div class="form-group col-md-12">
                        {{ Form::label('parcel_description',__('message.parcel_description'), ['class' => 'form-control-label']) }}
                        {{ Form::textarea('description', $data->description ?? null, ['class'=>"form-control textarea", 'rows'=>1, 'placeholder'=> __('message.parcel_description') ]) }}
                    </div>
                </div>

                <div class="row">
                    <div class="form-group col-md-4">
                        {{ Form::label('country_id', __('message.country'). ' <span class="text-danger">*</span>', [ 'class' => 'form-control-label' ,'required' ],false) }}
                        {{ Form::select('country_id',isset($data->country) ? [$data->country->id => $data->country->name] : [], old('country_id'), [
                            'class' => 'select2js form-group country_id',
                            'data-placeholder' => __('message.country'),
                            'data-ajax--url' => route('ajax-list', [ 'type' => 'country-list' ]),
                        ]) }}
                    </div>
                    <div class="form-group col-md-4">
                        {{ Form::label('city_id', __('message.city'). ' <span class="text-danger">*</span>', [ 'class' => 'form-control-label', 'required' ],false) }}
                        {{ Form::select('city_id', isset($data->city) ? [$data->city->id => $data->city->name] : [], old('city_id'), [
                            'class' => 'select2js form-group city_id',
                            'data-placeholder' => __('message.city'),
                        ]) }}
                    </div>
                </div>

                <div class="form-group">
                    <div class="row">
                        <div class="col-md-6">
                            <h4 class="card-title">{{ __('message.pickup_information') }}</h4>
                            <div class="card card-block">
                                <div class="card-header">
                                    <div class="form-group row">
                                        <div class="form-group col-md-12">
                                            {{ Form::hidden('pickup_point[start_time]', null, ['id' => 'combined_pickup_start_time']) }}
                                            {{ Form::hidden('pickup_point[end_time]', null, ['id' => 'combined_pickup_end_time']) }}
                                            {{ Form::label('pickup_location',__('message.pickup_location'). ' <span class="text-danger">*</span>',['class'=>'form-control-label'],false) }}
                                            {{ Form::text('pickup_point[address]', old('pickup_location'),['class' =>'form-control', 'id' => 'pickup_location' ,'required'])  }}
                                        </div>
                                            {{ Form::hidden('pickup_point[latitude]', null, ['id' => 'pickup_lat']) }}
                                            {{ Form::hidden('pickup_point[longitude]', null, ['id' => 'pickup_lng']) }}
                                        <div class="form-group col-md-12">
                                            {{ Form::label('pickup_contact_number',__('message.pickup_contact_number'). ' <span class="text-danger">*</span>',['class'=>'form-control-label'],false) }}
                                            {{ Form::text('pickup_point[contact_number]', old('pickup_contact_number'),[ 'placeholder' => __('message.pickup_contact_number'), 'class' => 'form-control ',"id"=>'contact_nbr','required']) }}
                                        </div>
                                        <div class="form-group col-md-12">
                                            {{ Form::label('pickup_description',__('message.pickup_description'). ' <span class="text-danger">*</span>', ['class' => 'form-control-label'],false) }}
                                            {{ Form::textarea('pickup_point[description]', null, ['class'=>"form-control textarea", 'rows'=>1,  'placeholder'=> __('message.pickup_description') ]) }}
                                        </div>
                                        <div class="form-group col-md-12">
                                            {{ Form::label('pickup_instruction',__('message.pickup_instruction'), ['class' => 'form-control-label']) }}
                                            {{ Form::textarea('pickup_point[instruction]', null, ['class'=>"form-control textarea", 'rows'=>1, 'placeholder'=> __('message.pickup_instruction') ]) }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <h4 class="card-title">{{ __('message.deliver_information') }}</h4>
                            <div class="card card-block">
                                <div class="card-header">
                                    <div class="form-group row">
                                        <div class="form-group col-md-12 ">
                                            {{ Form::hidden('delivery_point[start_time]', null, ['id' => 'combined_delivery_start_time']) }}
                                            {{ Form::hidden('delivery_point[end_time]', null, ['id' => 'combined_delivery_end_time']) }}
                                            {{ Form::label('delivery_location',__('message.delivery_location'). ' <span class="text-danger">*</span>',['class'=>'form-control-label'],false) }}
                                            {{ Form::text('delivery_point[address]', old('delivery_location'),['class' =>'form-control','id' => 'delivery_location','required'])  }}
                                        </div>
                                        {{ Form::hidden('delivery_point[latitude]', null, ['id' => 'delivery_lat']) }}
                                        {{ Form::hidden('delivery_point[longitude]', null, ['id' => 'delivery_lng']) }}
                                        <div class="form-group col-md-12">
                                            {{ Form::label('delivery_contact_number',__('message.delivery_contact_number'). ' <span class="text-danger">*</span>',['class'=>'form-control-label'],false) }}
                                            {{ Form::text('delivery_point[contact_number]',old('delivery_contact_number'),[ 'placeholder' => __('message.delivery_contact_number'), 'class' => 'form-control', 'id' => 'phone','required']) }}
                                        </div>
                                        <div class="form-group col-md-12">
                                            {{ Form::label('delivery_description',__('message.delivery_description'). ' <span class="text-danger">*</span>', ['class' => 'form-control-label'],false) }}
                                            {{ Form::textarea('delivery_point[description]', null, ['class'=>"form-control textarea", 'rows'=>1, 'placeholder'=> __('message.delivery_description') ]) }}
                                        </div>
                                        <div class="form-group col-md-12">
                                            {{ Form::label('delivery_instruction',__('message.delivery_instruction'), ['class' => 'form-control-label']) }}
                                            {{ Form::textarea('delivery_point[instruction]', null, ['class'=>"form-control textarea", 'rows'=>1, 'placeholder'=> __('message.delivery_instruction') ]) }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="form-group col-md-4">
                        {{ Form::label('payment_collect_from',__('message.payment_collect_form'). ' <span class="text-danger">*</span>',['class'=>'form-control-label'],false) }}
                        {{ Form::select('payment_collect_from',[ 'on_pickup' => __('message.pickup_location'), 'on_delivery' => __('message.delivery_location') ], old('payment_collect_from'), [ 'class' =>'form-control select2js']) }}
                    </div>
                    <div class="form-group col-md-4">
                        {{ Form::label('vehicle_id', __('message.vehicle'),[ 'class' => 'form-control-label' ]) }}
                        {{ Form::select('vehicle_id', isset($data->vehicle) ? [$data->vehicle->id => $data->vehicle->title] :  [], old('vehicle_id'), [
                            'class' => 'select2js form-group vehicle_id',
                            'data-placeholder' => __('message.vehicle'),
                            'data-ajax--url' => route('ajax-list', [ 'type' => 'vehicle-list' ]),
                        ]) }}
                    </div>
                </div>
                <hr>
                {{ Form::submit( __('message.save'), ['class'=>'btn btn-md btn-primary float-right']) }}
            </div>
        </div>
    </div>
    {!! Form::close() !!}
    @section('bottom_script')
        <script>
           $(document).ready(function() {
                $('#deliverNowBtn, #calendarBtn').click(function() {
                    if ($(this).attr('id') === 'deliverNowBtn') {
                        $('#scheduleSection').hide();
                        $('#deliverNowBtn').addClass('btn-primary');
                        $('#calendarBtn').removeClass('btn-primary');
                    } else if ($(this).attr('id') === 'calendarBtn') {
                        $('#scheduleSection').show();
                        $('#calendarBtn').addClass('btn-primary');
                        $('#deliverNowBtn').removeClass('btn-primary');
                    }
                });

                $('#order_form').validate({
                    rules: {
                        pickup_start_time: {
                            required: true
                        },
                        pickup_end_time: {
                            required: true,
                            greaterThanEqual: '#pickup_start_time'
                        },
                        delivery_start_time: {
                            required: true
                        },
                        delivery_end_time: {
                            required: true,
                            greaterThanEqual: '#delivery_start_time'
                        },
                        parcel_type: { required: true },
                        total_weight: { required: true },
                        total_parcel: { required: true },
                        parcel_description: { required: true },
                        country_id: { required: true },
                        city_id: { required: true },
                        'pickup_point[address]': { required: true },
                        'pickup_point[description]': { required: true },
                        'pickup_point[contact_number]': { required: true },
                        'delivery_point[address]': { required: true },
                        'delivery_point[contact_number]': { required: true },
                        'delivery_point[description]': { required: true },
                    },
                    messages: {
                        pickup_start_time: {
                            required: "{{ __('message.from_date_required') }}"
                        },
                        pickup_end_time: {
                            required: "{{ __('message.to_date_required') }}",
                            greaterThanEqual: "{{ __('message.to_time_must_be_greater_than_from_time') }}"
                        },
                        delivery_start_time: {
                            required: "{{ __('message.from_date_required') }}"
                        },
                        delivery_end_time: {
                            required: "{{ __('message.to_date_required') }}",
                            greaterThanEqual: "{{ __('message.to_time_must_be_greater_than_from_time') }}"
                        },
                        parcel_type: { required: "{{__('message.please_select_parcel_type')}}"},
                        total_weight: { required: "{{__('message.please_enter_total_weight')}}"},
                        total_parcel: { required: "{{__('message.please_enter_total_parcel')}}"},
                        parcel_description: { required: "{{__('message.please_enter_parcel_description')}}"},
                        country_id: { required: "{{__('message.please_select_country')}}"},
                        city_id: { required: "{{__('message.please_select_city')}}"},
                        'pickup_point[address]': { required: "{{__('message.please_enter_pickup_address')}}" },
                        'pickup_point[contact_number]': { required: "{{__('message.please_enter_pickup_contact_number')}}" },
                        'pickup_point[description]': { required: "{{__('message.please_enter_pickup_description')}}" },
                        'delivery_point[address]': { required: "{{__('message.please_enter_delivery_address')}}" },
                        'delivery_point[contact_number]': { required: "{{__('message.please_enter_delivery_contact_number')}}" },
                        'delivery_point[description]': { required: "{{__('message.please_enter_delivery_description')}}" },
                    },
                    errorPlacement: function(error, element) {
                        error.addClass('text-danger');
                        if (element.attr("name") == "pickup_start_time") {
                            $('#form_validation_pickup_start_time').prepend(error);
                        } else if (element.attr("name") == "pickup_end_time") {
                            $('#form_validation_pickup_end_time').prepend(error);
                        } else if(element.attr("name") == "delivery_start_time"){
                            $('#form_validation_delivery_start_time').prepend(error);
                        } else if(element.attr("name") == "delivery_end_time"){
                            $('#form_validation_delivery_end_time').prepend(error);
                        } else {
                            error.insertAfter(element);
                        }
                    },
                    highlight: function(element) {
                        $(element).addClass('is-invalid');
                    },
                    unhighlight: function(element) {
                        $(element).removeClass('is-invalid');
                    }
                });

                $('.select2js').on('change', function() {
                    $(this).valid();
                });

                $.validator.addMethod('greaterThanEqual', function(value, element, param) {
                    var startTime = $(param).val();
                    if (!value || !startTime) {
                        return true;
                    }
                    return new Date('1970/01/01 ' + value) > new Date('1970/01/01 ' + startTime);
                });

                $(document).on('change', '#country_id', function() {
                    var country_id = $(this).val();
                    $('#city_id').empty().append('<option value="" selected disabled>' + $('#city_id').data('placeholder') + '</option>');
                    cityList(country_id);
                });

                function initAutocomplete() {
                    var pickupInput = document.getElementById('pickup_location');
                    var deliveryInput = document.getElementById('delivery_location');

                    var pickupAutocomplete = new google.maps.places.Autocomplete(pickupInput);
                    var deliveryAutocomplete = new google.maps.places.Autocomplete(deliveryInput);

                    pickupAutocomplete.addListener('place_changed', function() {
                        var place = pickupAutocomplete.getPlace();
                        document.getElementById('pickup_lat').value = place.geometry.location.lat();
                        document.getElementById('pickup_lng').value = place.geometry.location.lng();
                        calculateDistance();
                    });

                    deliveryAutocomplete.addListener('place_changed', function() {
                        var place = deliveryAutocomplete.getPlace();
                        document.getElementById('delivery_lat').value = place.geometry.location.lat();
                        document.getElementById('delivery_lng').value = place.geometry.location.lng();
                        calculateDistance();
                    });
                }

             var MILES_PER_KM = 0.621371;

                function calculateDistance() {
                    var pickupLat = parseFloat(document.getElementById('pickup_lat').value);
                    var pickupLng = parseFloat(document.getElementById('pickup_lng').value);
                    var deliveryLat = parseFloat(document.getElementById('delivery_lat').value);
                    var deliveryLng = parseFloat(document.getElementById('delivery_lng').value);

                    var pickup = new google.maps.LatLng(pickupLat, pickupLng);
                    var delivery = new google.maps.LatLng(deliveryLat, deliveryLng);

                    var service = new google.maps.DistanceMatrixService();
                    service.getDistanceMatrix({
                        origins: [pickup],
                        destinations: [delivery],
                        travelMode: 'DRIVING',
                    }, function(response, status) {
                        if (status === 'OK') {
                            var distanceInKm = response.rows[0].elements[0].distance.value / 1000;
                            var totalDistanceMiles = MILES_PER_KM * distanceInKm;
                            var duration = response.rows[0].elements[0].duration.text;
                            document.getElementById('total_distance').value = distanceInKm.toFixed(2);
                        } else {
                            console.error('Error:', status);
                        }
                    });
                }

              initAutocomplete();
              $('form').submit(function() {
                    var pickupDate = $('[name="pickup_date"]').val();
                    var pickupTime = $('[name="pickup_start_time"]').val();
                    var pickupEndTime = $('[name="pickup_end_time"]').val();

                    var combinedDateTime = pickupDate + ' ' + pickupTime;
                    var combinedDateEndTime = pickupDate + ' ' + pickupEndTime;

                    $('#combined_pickup_start_time').val(combinedDateTime);
                    $('#combined_pickup_end_time').val(combinedDateEndTime);

                    var deliveryDate = $('[name="delivery_date"]').val();
                    var deliveryTime = $('[name="delivery_start_time"]').val();
                    var deliveryEndTime = $('[name="delivery_end_time"]').val();

                    combinedDateTime = deliveryDate + ' ' + deliveryTime;
                    combinedDateEndTime = deliveryDate + ' ' + deliveryEndTime;

                    $('#combined_delivery_start_time').val(combinedDateTime);
                    $('#combined_delivery_end_time').val(combinedDateEndTime);

                    return true;
                });
            });

            function cityList(country_id) {
                var section_class_route = "{{ route('ajax-list', ['type' => 'country_base_city', 'country_id' => '']) }}" + country_id;
                section_class_route = section_class_route.replace('amp;', '');

                $.ajax({
                    url: section_class_route,
                    success: function(result) {
                        $('#city_id').select2({
                            width: '100%',
                            placeholder: "{{ __('message.select_name',['select' => __('message.city')]) }}",
                            data: result.results
                        });
                    }
                });
            }

            var distanceInKm = parseFloat(document.getElementById('total_distance').value) || 0;

            $('#city_id').on('select2:select', function(e) {
                var selectedData = e.params.data;
                var extraCharges = selectedData.extra_charges || [];
                var extraChargesStatus = extraCharges.filter(charge => charge.status === 1);
                var fixedCharges = parseFloat(selectedData.fixed_charges) || 0;
                var perWeightCharges = parseFloat(selectedData.per_weight_charges) || 0;
                var min_weight = parseFloat(selectedData.min_weight) || 0;
                var min_distance = parseFloat(selectedData.min_distance) || 0;
                var perDistanceCharges = parseFloat(selectedData.per_distance_charges) || 0;

                var weight_charge = min_weight * perWeightCharges;
                var distance_charge = Math.max(min_distance, distanceInKm) * perDistanceCharges;
                var totalAmount = fixedCharges + weight_charge + distance_charge;

                $('#fixed_charges').val(fixedCharges.toFixed(2));
                $('#total_amount').val(totalAmount.toFixed(2));
                $('#weight_charge').val(weight_charge.toFixed(2));
                $('#distance_charge').val(distance_charge.toFixed(2));

                var extracharges = [
                    { 'title': 'fixed_charges', 'charges': fixedCharges},
                    { 'title': 'per_weight_charges', 'charges': perWeightCharges},
                    { 'title': 'min_weight', 'charges': min_weight},
                    { 'title': 'min_distance', 'charges': min_distance},
                    { 'title': 'per_distance_charges', 'charges': perDistanceCharges}
                ];

                var extrachargemerge = extraChargesStatus.concat(extracharges);
                $('#extra_charges').val(JSON.stringify(extrachargemerge));
            });

            function setParcelType(label) {
                document.getElementById('parcel_type_text').value = label;
            }

            $("#parcel_type").mouseover(function() {
                $("#parcel_type_container").show();
            });

            $("#parcel_type").mouseleave(function() {
                $("#parcel_type_container").hide();
            });
        </script>
    @endsection
</x-master-layout>
