
<?php $__env->startSection('content'); ?>
<div class="main-header">
    <div class="admin-header">
        <div class="uk-grid">
            <div class="uk-width-1-2">
                <h1 class="uk-margin-small-top main-heading"><?php echo e($title); ?></h1>
            </div>
            <div class="uk-width-1-2 uk-text-right">
                <a class="uk-button uk-button-default" href="<?php echo e(url('admin/realtors')); ?>"> Back</a>
            </div>
        </div>
    </div>
</div>
<div class="uk-margin uk-width-1-1 uk-margin-auto uk-card uk-card-default uk-card-body small-padding">
	<?php echo $__env->make('partials.messages', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
	<?php echo e(Form::open(array('route' => ['admin.realtors.update',$data->id],'method' => 'PUT', 'class' => 'uk-form-stacked','id' => 'edit_form', 'files' => 'true'))); ?>

    <?php echo csrf_field(); ?>
	<div class="uk-grid" uk-grid>
    	<div class="uk-width-1-2@m">
            <div class="uk-margin-small">
                <label for="name" class="uk-form-label">Name <span class="uk-text-danger">*</span></label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('name', $data->name,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div>
            <div class="uk-margin-small">
                <label for="phone_number" class="uk-form-label">Phone Number</label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('phone_number', $data->phone_number,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div>
            <div class="uk-margin-small">
                <label for="email" class="uk-form-label">Email <span class="uk-text-danger">*</span></label>
                <div class="uk-form-controls">
                    <?php echo e(Form::email('email', $data->email,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div>
            <div class="uk-margin-small">
               <label for="password" class="uk-form-label">Password </label>
               <div class="uk-form-controls">
                    <?php echo e(Form::password('password',['class' => 'uk-input password','autocomplete' => 'off','id' => 'password'])); ?>

                </div>    
            </div>
            <div class="uk-margin-small">
                <label for="address" class="uk-form-label">Address <span class="uk-text-danger">*</span></label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('address', $data->email,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div> 
            <div class="uk-margin-small">
                <label for="brokerage" class="uk-form-label">Brokerage</label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('brokerage', $data->brokerage,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div> 
            <div class="uk-margin-small">
                <label for="real_estate_association" class="uk-form-label">Real Estate Association</label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('real_estate_association', $data->real_estate_association,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div> 
            <div class="uk-margin-small">
                <label for="awards" class="uk-form-label">Awards</label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('awards', $data->awards,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div> 
            <div class="uk-margin-small">
                <label for="website" class="uk-form-label">Website</label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('website', $data->website,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div>
            <div class="uk-margin-small">
                <label for="realtor" class="uk-form-label">Realtor Number</label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('realtor', $data->realtor,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div>
            <div class="uk-margin-small">
                <label for="bio" class="uk-form-label">Bio</label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('bio', $data->bio,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div>
            <div class="uk-margin-small">
                <label for="sports_played" class="uk-form-label">Sports Played</label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('sports_played', $data->sports_played,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div>
            <div class="uk-margin-small">
                <label for="interest_and_hobby" class="uk-form-label">Interests and hobbies</label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('interest_and_hobby', $data->interest_and_hobby,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div>
            <div class="uk-margin-small">
                <label for="years_with_brokerage" class="uk-form-label">Years With Brokerage</label>
                <div class="uk-form-controls">
                    <?php echo e(Form::text('years_with_brokerage', $data->years_with_brokerage,['class' => 'uk-input','autocomplete' => 'off'])); ?>

                </div>
            </div>
            <div class="additional-section">
            <?php if(count($cityRanges) > 0): ?>
            <?php $__currentLoopData = $cityRanges; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $cityRange): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <div class="uk-margin">
                <?php if($key == 0): ?>
                <label for="city" class="uk-form-label">City (Multiple Add) <span class="uk-text-danger">*</span></label>
                <?php endif; ?>
                <div class="uk-form-controls uk-margin-small-top">
                    <div class="city-section">
                        <div class="counter-section">
                            <?php echo e(Form::hidden('city_id[]',$cityRange->id)); ?>

                            <div class="uk-grid-small" uk-grid>
                                <div class="uk-width-expand">
                                    <?php echo e(Form::text('city[]', $cityRange->city_name,['class' => 'uk-input city-autocomplete','autocomplete' => 'off','placeholder' => 'Name'])); ?>

                                    <span class="uk-text-danger city-error"></span>
                                </div>
                                <?php if($key == 0): ?>
                                <div class="uk-width-auto uk-margin-small-top">
                                    <a class="uk-text-primary add-more-city" uk-tooltip="Add More City"><i class="fa-solid fa-circle-plus fa-xl"></i></a>
                                </div>
                                <?php else: ?>
                                <div class="uk-width-auto uk-margin-small-top">
                                    <a class="uk-text-danger remove-city" uk-tooltip="Remove City"><i class="fa-solid fa-circle-minus fa-xl"></i></a>
                                </div>
                                <?php endif; ?>
                            </div>
                            <div class="uk-grid-small" uk-grid>
                                <div class="uk-width-expand">
                                    <input class="uk-range" name="city_range[]" type="range" value="<?php echo e($cityRange->city_range); ?>" min="20" max="150" step="1" aria-label="Range">
                                </div>
                                <div class="uk-width-auto">
                                    <span><?php echo e($cityRange->city_range); ?> KM</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            <?php else: ?>
            <div class="uk-margin">
                <label for="city" class="uk-form-label">City (Multiple Add) <span class="uk-text-danger">*</span></label>
                <div class="uk-form-controls uk-margin-small-top">
                    <div class="city-section">
                        <div class="counter-section">
                            <div class="uk-grid-small" uk-grid>
                                <div class="uk-width-expand">
                                    <?php echo e(Form::text('city[]', '',['class' => 'uk-input city-autocomplete','autocomplete' => 'off','placeholder' => 'Name'])); ?>

                                    <span class="uk-text-danger city-error"></span>
                                </div>
                                <div class="uk-width-auto uk-margin-small-top">
                                    <a class="uk-text-primary add-more-city" uk-tooltip="Add More City"><i class="fa-solid fa-circle-plus fa-xl"></i></a>
                                </div>
                            </div>
                            <div class="uk-grid-small" uk-grid>
                                <div class="uk-width-expand">
                                    <input class="uk-range" name="city_range[]" type="range" value="20" min="20" max="150" step="1" aria-label="Range">
                                </div>
                                <div class="uk-width-auto">
                                    <span>20 KM</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            </div>
            <?php if($realtorYears->count() > 0): ?>
                <div class="uk-margin">
                    <label for="years_of_realtor" class="uk-form-label"># of years as a realtor <span class="uk-text-danger">*</span></label>
                    <div class="uk-form-controls uk-margin-small-top">
                        <div class="uk-grid-small" uk-grid>
                            <?php $__currentLoopData = $realtorYears; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $realtorYear): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <div class="uk-width-auto">
                                    <div class="realtor-years-box <?php echo e($realtorYear->name == $data->realtor_year ? 'active' : ''); ?>" data-name="<?php echo e($realtorYear->name); ?>">
                                        <?php echo e($realtorYear->name); ?>

                                    </div>
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                    </div>
                    <span class="uk-text-danger years-realtor-error"></span>
                </div>
            <?php endif; ?>
            <?php echo e(Form::hidden('years_of_realtor', $data->realtor_year)); ?>

            <?php
                $languageData = '';
                if($data->language){
                    $languageData = json_decode($data->language, true);
                }
            ?>
            <?php if($languages->count() > 0): ?>
                <div class="uk-margin">
                    <label for="language" class="uk-form-label">Languages (Multiple Select)</label>
                    <div class="uk-form-controls uk-margin-small-top">
                        <div class="uk-grid-small" uk-grid>
                            <?php $__currentLoopData = $languages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $language): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <div class="uk-width-auto">
                                    <div class="language-box <?php echo e((is_array($languageData) && in_array($language->name, $languageData)) ? 'active' : ''); ?>" data-name="<?php echo e($language->name); ?>">
                                        <?php echo e($language->name); ?>

                                    </div>
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                    </div>
                    <div class="uk-margin-small <?php echo e((is_array($languageData) && in_array('Other', $languageData)) ? '' : 'uk-hidden'); ?> other-language">
                        <?php echo e(Form::text('other_language', $data->other_language,['class' => 'uk-input','autocomplete' => 'off','placeholder' => 'Other Language'])); ?>

                    </div>
                </div>
            <?php endif; ?>
            <?php echo e(Form::hidden('language', $languageData ? implode(", ",$languageData) : '')); ?>

            <div class="uk-margin-small">
                <label for="profile_pic" class="uk-form-label">Profile Picture </label>
                <div class="uk-form-controls">
                    <?php echo e(Form::file('profile_pic', ['class' => 'uk-input','autocomplete' => 'off', 'accept' => '.jpg , .jpeg, .png'])); ?>

                    <?php if($data->profile_pic): ?>
                    <div uk-lightbox>
                        <a href="<?php echo e(url('storage/profile_pictures/realtor/'.$data->id.'/'.$data->profile_pic)); ?>" data-alt="Image"><span><img class="default-image uk-margin-small-top" src="<?php echo e(url('storage/profile_pictures/realtor/'.$data->id.'/'.$data->profile_pic)); ?>" /> <a class="remove-profile-pic uk-margin-left uk-text-danger" data-id="<?php echo e($data->id); ?>" href="javascript:void(0)"><i class="fa-solid fa-square-minus fa-xl"></i></a></span></a>
                    </div>
                    <?php endif; ?>
                </div>    
            </div>
            <div>
                
            </div>
        </div> 
        <div class="uk-width-1-2@m">
            <div id="map" class="uk-height-large" style="height: 500px;"></div>
            <div class="uk-margin-small-top list-view" uk-height-viewport="offset-bottom: 20">
                <ul id="placesContainer" class="uk-list uk-list-divider"></ul>
            </div>
        </div>
    </div>
    <div class="uk-margin">
        <div class="uk-form-controls">
        <?php echo e(Form::submit('Update', array('class' => 'uk-button uk-button-primary','name' => 'save', 'id' => 'edit_submit'))); ?>

        <a class="uk-button uk-button-default" href="<?php echo e(url('admin/realtors')); ?>">Cancel</a>
        </div>
    </div> 
    <?php echo e(Form::close()); ?>

</div>                   
<?php $__env->stopSection(); ?>
<?php $__env->startSection('footer-script'); ?>
<script src="https://maps.googleapis.com/maps/api/js?key=<?php echo e(env('MAP_KEY')); ?>&libraries=places"></script>
<script>

    function initializeAutocomplete(inputElement) {
        var options = {
            types: ['(cities)'],
            componentRestrictions: { country: ['us', 'ca'] }
        };
    
        var autocomplete = new google.maps.places.Autocomplete(inputElement, options);
    
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }
        });
    }
    
    function initialize() {
        var inputs = document.getElementsByClassName('city-autocomplete');
        for (var i = 0; i < inputs.length; i++) {
            initializeAutocomplete(inputs[i]);
        }
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    
    $.validator.addMethod('validUrl', function(value, element) {
        var url = $.validator.methods.url.bind(this);
        return url(value, element) || url('http://' + value, element);
    }, 'Please enter a valid URL');
    
    $("#edit_form").validate({
        errorClass: "uk-text-danger",
        rules:{
            name:"required",
            terms_service:"required",
            address:"required",
            email: {
				required: true,
				email:true,
				remote:{
                    url: '<?php echo e(url("check-email")); ?>',
                    type: "post",
                    data:{'userId': <?php echo e($data->id); ?>}
                }
			},
        },
        messages: {
            name: {
                required: "Complete this required field."
            },
            email: {
                required: "Complete this required field.",
                remote:"This email is already exist."
            },
            address: {
                required: "Complete this required field."
            },
            terms_service: {
                required: "Please accept Terms and Conditions."
            },
        },
        errorPlacement: function(error, element) {
            if (element.attr("name") == "name") {
                error.insertBefore('.realtor-name-error');
            }else if (element.attr("name") == "email") {
                error.insertBefore('.realtor-email-error');
            }else if (element.attr("name") == "password") {
                error.insertBefore('.realtor-password-error');
            }else if (element.attr("name") == "password_confirmation") {
                error.insertBefore('.realtor-password-confirmation-error');
            }else if (element.attr("name") == "terms_service") {
                error.insertBefore('.realtor-terms-service-error');
            }else if (element.attr("name") == "address") {
                error.insertBefore('.realtor-address-error');
            }else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            var error = 0;
            const yearsOfRealtor = $('input[name=years_of_realtor]').val();
            if(!yearsOfRealtor){
                $('.years-realtor-error').html('Please select # of years as a realtor');
                error = 1;
                return false;
            }
            $("input[name='city[]']").each(function () {
                if(!$(this).val()){
                    $(this).closest('div').find('.city-error').html('Please enter the city name.');
                    error = 1;
                }
            });
            if(error == 0){
                $('#edit_submit').attr('disabled',true);
                form.submit();
            }else{
                return false;
            }
        }
    });
    
    $(document).on('click','.remove-profile-pic',function(){
        var clst = $(this).closest('div');
        var id   = $(this).data('id');
        UIkit.modal.confirm('Are you sure you want to remove this profile picture?').then(function() {
            $.ajax(
            {
                url: "<?php echo e(url('/admin/profile-picture-remove')); ?>",
                type: 'POST',
                dataType: "JSON",
                data: {
                    'id': id,
                },
                success: function (res)
                {
                    if(res.success == 1){
                	    UIkit.modal.alert('Profile picture successfully remove.');
                        clst.remove();
                    }
                    if(res.success == 0){
                        UIkit.modal.alert(res.error);
                    }
                },
                error:function()
                {
                    UIkit.modal.alert('Oops!<br>Something went wrong. Please try again later.');
                }
            });
        }, function () {
        });
    });
    
    $(document).on("click",".realtor-years-box",function() {
        $('.realtor-years-box').removeClass('active');
        $(this).addClass('active');
        $('input[name=years_of_realtor]').val($(this).data('name'));
    });
    
    $(document).on("click", ".language-box", function() {
        var language = $(this).data('name');
    
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
            if (language == 'Other') {
                $('.other-language').addClass('uk-hidden');
                $('input[name="other_language"]').val('');
            }
        } else {
            $(this).addClass('active');
            if (language == 'Other') {
                $('.other-language').removeClass('uk-hidden');
                $('input[name="other_language"]').val('');
            }
        }
    
        var languageList = '';
        $(".language-box.active").each(function() {
            languageList += ', ' + $(this).data('name');
        });
    
        languageList = languageList.substring(2);
    
        $('input[name="language"]').val(languageList);
    });
    
    $(document).on("change",".uk-range",function() {
        $(this).closest('.uk-grid-small').find('span').html($(this).val()+' KM');
    });
    
    var cityHtml = '';
    cityHtml += '<div class="uk-margin-small-top counter-section">';
    cityHtml += '<div class="uk-grid-small" uk-grid>';
    cityHtml += '<div class="uk-width-expand">';
    cityHtml += '<input name="city[]" value="" class="uk-input city-autocomplete" autocomplete="off" placeholder="Name">';
    cityHtml += '<span class="uk-text-danger city-error"></span>';
    cityHtml += '</div>';
    cityHtml += '<div class="uk-width-auto uk-margin-small-top">';
    cityHtml += '<a class="uk-text-danger remove-city" uk-tooltip="Remove City"><i class="fa-solid fa-circle-minus fa-xl"></i></a>';
    cityHtml += '</div>';
    cityHtml += '</div>';
    cityHtml += '<div class="uk-grid-small" uk-grid>';
    cityHtml += '<div class="uk-width-expand">';
    cityHtml += '<input class="uk-range" name="city_range[]" type="range" value="20" min="20" max="150" step="1" aria-label="Range">';
    cityHtml += '</div>';
    cityHtml += '<div class="uk-width-auto">';
    cityHtml += '<span>20 KM</span>';
    cityHtml += '</div>';
    cityHtml += '</div>';
    cityHtml += '</div>';
    
    $(document).on("click",".add-more-city",function() {
        $(this).closest('.additional-section').append(cityHtml);
        initialize();
    });
    
    $(document).on("click",".remove-city",function() {
        $(this).closest('.counter-section').remove();
    });
    
    const apiKey = "<?php echo e(env('MAP_KEY')); ?>";
    
    function gatherCityData() {
        const data = [];
        $('.city-section').each(function() {
            var city = $(this).find('.city-autocomplete').val().trim();
            var range = $(this).find('.uk-range').val();
            data.push({ city: city, range: range });
        });
        return data;
    }

    function fetchCityCoordinates() {
        var data = gatherCityData();
        return $.ajax({
            url: '/admin/city-coordinates',
            method: 'POST',
            data: JSON.stringify({ data }),
            contentType: 'application/json',
        });
    }

    let nextPageToken = null;

    const fetchNearbyPlaces = (lat, lng, radius) => {
        
        $.ajax({
            url: '/admin/fetch-nearby-places',
            method: 'POST',
            dataType: 'json',
            data: {
                lat: lat,
                lng: lng,
                radius: radius,
                nextPageToken: nextPageToken,
            },
            success: function(data) {
                renderPlaces(data.results);
                nextPageToken = data.nextPageToken;
                if (nextPageToken) {
                    $.Deferred(function(deferred) {
                        setTimeout(deferred.resolve, 2000);
                    }).promise().done(function() {
                        fetchMoreResults(lat, lng, radius);
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('Error fetching nearby places:', error);
            }
        });
    };
    
    const fetchMoreResults = (lat, lng, radius) => {
        fetchNearbyPlaces(lat, lng, radius);
    };

    const renderPlacesList = (places) => {
        const $placesList = $('#places-list');

        places.forEach(place => {
            const $listItem = $('<li>');
            $listItem.text(place.name);
            $placesList.append($listItem);
        });
    };

    
    async function initMap() {
        const cityCoordinates = await fetchCityCoordinates();
    
        const map = new google.maps.Map(document.getElementById('map'), {
            zoom: 6,
            center: { lat: 49.8863235, lng: -119.4965917 }
        });
    
        cityCoordinates.forEach(city => {
            // Create marker for the city
            const marker = new google.maps.Marker({
                position: { lat: city.latitude, lng: city.longitude },
                map,
                title: city.city
            });
    
            // Create circle for the city
            const cityCircle = new google.maps.Circle({
                strokeColor: '#000000',
                strokeWeight: 2,
                fillColor: '#000',
                map,
                center: { lat: city.latitude, lng: city.longitude },
                radius: city.range * 1000
            });
    
            marker.addListener('click', async () => {
                const places = await fetchNearbyPlaces(city.latitude, city.longitude, city.range * 1000);
                displayPlaces(places);
            });
        });
    }

    function displayPlaces(places) {
        const placesList = $('#placesContainer');
        placesList.empty();

        places.forEach(place => {
            const listItem = $('<li></li>').text(`${place.name} (${place.types.join(', ')})`);
            placesList.append(listItem);
        });
    }
    
    function renderPlaces(places) {
        const placesContainer = $('#placesContainer');
        const categorizedPlaces = categorizePlaces(places);
        
        $('.list-view').addClass('uk-panel-scrollable');        

        for (const [category, places] of Object.entries(categorizedPlaces)) {
            placesContainer.append(`<h4 class="uk-text-capitalize">${category}</h4>`);
            places.forEach(place => {
                placesContainer.append(`<li>${place.name}</li>`);
            });
        }
    }

    function categorizePlaces(places) {
        const categories = {};

        places.forEach(place => {
            const types = place.types;
            types.forEach(type => {
                if (!categories[type]) {
                    categories[type] = [];
                }
                categories[type].push(place);
            });
        });

        return categories;
    }

    initMap();
    
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/kelowna/public_html/listingllama.kelowna.website/resources/views/admin/realtors/edit.blade.php ENDPATH**/ ?>