@extends('layouts.app')

@section('content')

<div class="page-wrapper">

    <div class="row page-titles">

        <div class="col-md-5 align-self-center">
            <h3 class="text-themecolor">{{trans('lang.sos')}}</h3>
        </div>

        <div class="col-md-7 align-self-center">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{{url('/dashboard')}}">{{trans('lang.dashboard')}}</a></li>
                <li class="breadcrumb-item"><a href="{!! route('sos') !!}">{{trans('lang.sos')}}</a></li>
                <li class="breadcrumb-item">{{trans('lang.edit_sos')}}</li>
            </ol>
        </div>
    </div>

    <div class="container-fluid">

        <div class="row">

            <div class="col-12">

                <div class="card">

                    <div class="card-body p-0 pb-5">

                        <div class="user-detail" role="tabpanel">

                            <div class="row">
                                <div class="col-12">
                                    <div class="box">
                                        <div class="box-header bb-2 border-primary">
                                            <h3 class="box-title">{{trans('lang.map_view')}}</h3>
                                        </div>
                                        <div class="box-body">
                                            <div id="map" style="height:300px">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="box">
                                        <div class="box-header bb-2 border-primary">
                                            <h3 class="box-title">{{trans('lang.general_details')}}</h3>
                                        </div>
                                        <div class="box-body">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>{{trans('lang.date_created')}}</th>
                                                        <th>{{trans('lang.status')}}</th>
                                                        <th></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td id="created_date"></td>
                                                        <td> <select id="order_status" class="form-control">
                                                                <option value="Initiated" id="initiated">{{
                                                                    trans('lang.initiated')}}</option>
                                                                <option value="Processing" id="processing">{{
                                                                    trans('lang.in_process')}}</option>
                                                                <option value="Completed" id="completed">{{
                                                                    trans('lang.completed')}}</option>
                                                            </select></td>
                                                        <td><button type="button"
                                                                class="btn btn-primary edit-form-btn"><i
                                                                    class="fa fa-save"></i>
                                                                {{trans('lang.update')}}</button></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    <div class="box">
                                        <div class="box-header bb-2 border-primary">
                                            <h3 class="box-title">{{ trans('lang.billing_details')}}</h3>
                                        </div>
                                        <div class="box-body">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>{{trans('lang.name')}}</th>

                                                        <th>{{trans('lang.email_address')}}</th>
                                                        <th>{{trans('lang.phone')}}</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td id="billing_name"></td>
                                                        <td id="billing_email"></td>
                                                        <td id="billing_phone"> </td>

                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    <div class="box">
                                        <div class="box-header bb-2 border-primary">
                                            <h3 class="box-title">{{ trans('lang.ride_detail')}}</h3>
                                        </div>
                                        <div class="box-body">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>{{trans('lang.user')}}</th>
                                                        <th>{{trans('lang.driver_plural')}}</th>
                                                        <th>{{trans('lang.pickup_address')}}</th>
                                                        <th>{{trans('lang.drop_address')}}</th>
                                                        <th>{{trans('lang.status')}}</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td id="client"></td>
                                                        <td id="driver"> </td>
                                                        <td id="pickup_address"></td>
                                                        <td id="drop_address"></td>
                                                        <td id="status"> </td>

                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    <div class="box">
                                        <div class="box-header bb-2 border-primary">
                                            <h3 class="box-title">{{ trans('lang.driver_detail')}}</h3>
                                        </div>
                                        <div class="box-body">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>{{trans('lang.image')}}</th>
                                                        <th>{{trans('lang.driver_plural')}}</th>
                                                        <th>{{trans('lang.email_address')}}</th>
                                                        <th>{{trans('lang.phone')}}</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td><img src="" class="driver-img rounded-circle" alt="driver"
                                                                width="70px" height="70px"></td>
                                                        <td class="vendor-title"> </td>
                                                        <td id="vendor_email"></td>
                                                        <td id="vendor_phone"> </td>

                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    <div class="box">
                                        <div class="box-header bb-2 border-primary">
                                            <h3 class="box-title">{{ trans('lang.car_info')}}</h3>
                                        </div>
                                        <div class="box-body">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>{{trans('lang.car_number')}}</th>
                                                        <th>{{trans('lang.vehicle_type')}}</th>
                                                        <th>{{trans('lang.vehicle_color')}}</th>

                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td id="driver_carNumber"></td>
                                                        <td id="driver_car_make"> </td>
                                                        <td id="driver_car_color"> </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-group col-12 text-center btm-btn">
                <a href="{!! route('sos') !!}" class="btn btn-default"><i class="fa fa-undo"></i>{{trans('lang.cancel')}}</a>
            </div>
        </div>

        
    </div>

    
</div>


@endsection

@section('style')

@section('scripts')



<script type="text/javascript">
    
    var id_rendom="<?php echo uniqid(); ?>";
    var id="<?php echo $id; ?>";
    var driverId='';
    var fcmToken='';
    var old_order_status='';
    var vendorname='';
    var database=firebase.firestore();
    var ref=database.collection('sos').where("id","==",id);
    var orderPreviousStatus='';
    var manfcmTokenVendor='';
    var manname='';
    var geoFirestore=new GeoFirestore(database);
    var place_image='{{asset("images/default_user.png")}}';
    var setLanguageCode=getCookie('setLanguage');
    var defaultLanguageCode=getCookie('defaultLanguage');

    

    $(document).ready(function() {
        

        $('.sos_menu').addClass('active');

        $(document.body).on('click','.redirecttopage',function() {
            var url=$(this).attr('data-url');
            window.location.href=url;
        });

        jQuery("#overlay").show();

        ref.get().then(async function(snapshots) {
            var sos=snapshots.docs[0].data();

            sosStatus=sos.status;
            old_order_status=sos.status
            $("#order_status option[value='"+sos.status+"']").attr("selected","selected");

            var price=0;
            userData=await getUserInfo(sos.customerId);
            $("#billing_name").text(userData.firstName + ' ' +userData.lastName);
            var billingAddressstring='';

            if(userData.countryCode.includes('+')) {
                userData.countryCode=userData.countryCode.slice(1);
            }
            else {
                userData.countryCode=userData.countryCode;
            }
            if(userData.hasOwnProperty('phoneNumber')) {
                $("#billing_phone").text('+'+shortNumber(userData.countryCode,userData.phoneNumber));
            }


            if(userData.hasOwnProperty('email')) {
                $("#billing_email").html('<a href="mailto:'+userData.email+'">'+shortEmail(userData.email)+'</a>');
            }

            if(userData.firstName) {
                $('#client').text(userData.firstName + ' ' + userData.lastName);
            }

            if (sos.driverId) {
                try {
                    const driverDoc = await database.collection('users').doc(sos.driverId).get();
                    if (!driverDoc.exists) {
                        // If no driver document found
                        $('.driver-img').attr('src', place_image);
                        $('.vendor-title').html('-');
                        $('#vendor_email').html('-');
                        $('#vendor_phone').text('-');
                        $('#driver_carNumber').html('-');
                        $('#driver_car_make').text('-');
                        $('#driver_car_color').text('-');
                    } else {
                        const driver_data = driverDoc.data();

                        if (driver_data.id) {
                            let route_view = '{{route("users.view", ":id")}}';
                            route_view = route_view.replace(':id', driver_data.id);
                        }

                        $('#driver').text(driver_data.firstName + ' ' + driver_data.lastName);

                        if (driver_data.profilePic && driver_data.profilePic !== '') {
                            $('.driver-img').attr('src', driver_data.profilePic);
                        } else {
                            $('.driver-img').attr('src', place_image);
                        }

                        if (driver_data.firstName && driver_data.lastName) {
                            $('.vendor-title').html(driver_data.firstName + ' ' + driver_data.lastName);
                        }

                        if (driver_data.email) {
                            $('#vendor_email').html(shortEmail(driver_data.email));
                        }

                        if (driver_data.phoneNumber) {
                            $('#vendor_phone').text(shortNumber(driver_data.countryCode, driver_data.phoneNumber));
                        }
                       
                    }
                } catch (error) {
                    console.error("Error fetching driver data:", error);
                }
            }

            
            if(sos.bookingId) {               
                var rideDoc =await database.collection('booking').doc(sos.bookingId).get();
                
            
                if (rideDoc.exists) {
                    const rideData = rideDoc.data(); 

                    if(rideData.pickUpAddress) {
                        $('#pickup_address').html(rideData.pickUpAddress);
                    }
                    if(rideData.dropAddress) {
                        $('#drop_address').html(rideData.dropAddress);
                    }

                    if(rideData.status) {
                        $('#status').text(rideData.status);
                    }

                    if(rideData.createdAt) {
                        var date1=rideData.createdAt.toDate().toDateString();
                        var date=new Date(date1);
                        var dd=String(date.getDate()).padStart(2,'0');
                        var mm=String(date.getMonth()+1).padStart(2,'0'); //January is 0!
                        var yyyy=date.getFullYear();
                        var createdAt_val=yyyy+'-'+mm+'-'+dd;
                        var time=rideData.createdAt.toDate().toLocaleTimeString('en-US');

                        $('#created_date').text(createdAt_val+' '+time);
                    }

                    if(rideData.hasOwnProperty('vehicleInformation')) {

                        if(rideData.vehicleInformation.licensePlatNumber) {
                            $('#driver_carNumber').html(rideData.vehicleInformation.licensePlatNumber);
                        }
                        if(rideData.vehicleInformation.vehicleType) {
                            var vehicleType='';
                            vehicleType = rideData.vehicleInformation.vehicleType.name;                           

                            $('#driver_car_make').text(vehicleType);
                        }
                        if(rideData.vehicleInformation.vehicleColor) {
                            $('#driver_car_color').text(rideData.vehicleInformation.vehicleColor);
                        }

                    } 
                    if (
                        rideData?.pickupLocation?.geometry?.location &&
                        rideData?.dropLocation?.geometry?.location &&
                        rideData?.pickUpAddress &&
                        rideData?.dropAddress
                    ) {
                        const pickup = {
                            lat: rideData.pickupLocation.geometry.location.lat,
                            lng: rideData.pickupLocation.geometry.location.lng,
                        };
                        const drop = {
                            lat: rideData.dropLocation.geometry.location.lat,
                            lng: rideData.dropLocation.geometry.location.lng,
                        };

                        const sosLocation = sos?.sosLocation ? {
                            latitude: sos.sosLocation.latitude,
                            longitude: sos.sosLocation.longitude
                        } : null;

                        console.log('Initializing Google Map route...');
                        initGoogleMapRoute(pickup, drop, rideData.pickUpAddress, rideData.dropAddress, sosLocation);
                    } else {
                        console.warn("Missing pickup/drop location or address in rideData", rideData);
                    }


                   
                }
                

            }
            jQuery("#overlay").hide();
        })

        async function getUserInfo(userId) {
            var user={};
            await database.collection('users').where('id','==',userId).get().then(async function(snapshots) {
                if(snapshots.docs.length>0) {
                    user=snapshots.docs[0].data();
                }
            });
            return user;
        }

        $(".edit-form-btn").click(async function() {

            var clientName=$(".client_name").val();
            var orderStatus=$("#order_status").val();

            if(old_order_status!=orderStatus) {
                database.collection('sos').doc(id).update({'status': orderStatus}).then(async function(result) {
                    await $.ajax({
                        type: 'POST',
                        url: "<?php echo route('send-notification'); ?>",
                        data: {_token: '<?php echo csrf_token() ?>','orderStatus': orderStatus},
                        success: function(data) {
                            window.location.href='{{ route("sos")}}';
                        }
                    });

                });
            }
        })
       
        function initGoogleMapRoute(pickup, drop, pickupAddress, dropAddress, sosLocation = null) {
            const map = new google.maps.Map($('#map').get(0), {
                zoom: 13,
                center: pickup,
                zoomControl: true,
                zoomControlOptions: {
                    position: google.maps.ControlPosition.RIGHT_BOTTOM
                },
                mapTypeControl: false,
                streetViewControl: false,
                fullscreenControl: false,
            });

            const directionsService = new google.maps.DirectionsService();
            const directionsRenderer = new google.maps.DirectionsRenderer({
                map: map,
                suppressMarkers: true,
            });
            
            const pickupMarker = new google.maps.Marker({
                position: pickup,
                map: map,
                title: "Pickup Location",
            });
            const pickupInfo = new google.maps.InfoWindow({
                content: `<strong>Pickup:</strong><br>${pickupAddress}`,
            });
            pickupMarker.addListener("click", () => pickupInfo.open(map, pickupMarker));
           
            const dropMarker = new google.maps.Marker({
                position: drop,
                map: map,
                title: "Drop Location",
            });
            const dropInfo = new google.maps.InfoWindow({
                content: `<strong>Drop:</strong><br>${dropAddress}`,
            });
            dropMarker.addListener("click", () => dropInfo.open(map, dropMarker));

  
            if (sosLocation) {
                const sosLatLng = {
                    lat: sosLocation.latitude,
                    lng: sosLocation.longitude
                };

                const sosMarker = new google.maps.Marker({
                    position: sosLatLng,
                    map: map,
                    title: "SOS Location",
                    icon: {
                        url: '{{asset("images/sos-button-emoji.png")}}',
                        scaledSize: new google.maps.Size(32, 32), 
                    },
                });
               
                const geocoder = new google.maps.Geocoder();
                geocoder.geocode({ location: sosLatLng }, (results, status) => {
                    if (status === "OK" && results[0]) {
                        const sosAddress = results[0].formatted_address;

                        const sosInfo = new google.maps.InfoWindow({
                            content: `<strong>SOS Address:</strong><br>${sosAddress}`,
                        });

                        sosMarker.addListener("click", () => sosInfo.open(map, sosMarker));
                    } else {
                        console.warn("Geocoder failed for SOS location:", status);
                        const sosInfo = new google.maps.InfoWindow({
                            content: `<strong>SOS Location:</strong><br>Address not found`,
                        });

                        sosMarker.addListener("click", () => sosInfo.open(map, sosMarker));
                    }
                });
            }

            // Draw route
            directionsService.route(
                {
                    origin: pickup,
                    destination: drop,
                    travelMode: google.maps.TravelMode.DRIVING,
                },
                (response, status) => {
                    if (status === "OK") {
                        directionsRenderer.setDirections(response);
                    } else {
                        console.error("Directions request failed:", status);
                    }
                }
            );
        }

    })
   

   


</script>

@endsection