<?php
/**
 * @package    JBusinessDirectory
 *
 * @author CMSJunkie http://www.cmsjunkie.com
 * @copyright  Copyright (C) 2007 - 2021 CMSJunkie. All rights reserved.
 * @license   https://www.gnu.org/licenses/agpl-3.0.en.html
 */

defined('_JEXEC') or die('Restricted access');

// Include the component HTML helpers.
JHtml::addIncludePath(HELPERS_PATH.'html');
require_once BD_CLASSES_PATH.'/attributes/attributeservice.php';

// Load the tooltip behavior.


$attributeConfig = $this->item->defaultAtrributes;
$enablePackages = $this->appSettings->enable_packages;
$identifier = JFactory::getApplication()->input->get('identifier');
$mapKey  = JBusinessUtil::loadMapScripts();
?>
<div id="jbd-container" class="jbd-container jbd-edit-container location-container" >
    <form action="<?php echo JRoute::_('index.php?option=com_jbusinessdirectory&tmpl=component&layout=locations'); ?>" method="post" name="adminForm" id="item-form" class="form-horizontal">
    	<div class="">
            <div class="button-row">
                <button type="button" class="btn btn-success" onclick="saveLocation();">
                        <span class="ui-button-text"><?php echo JText::_("LNG_SAVE")?></span>
                </button>
                <button type="button" class="btn btn-danger" onclick="parent.jQuery.jbdModal.close();">
                        <span class="ui-button-text"><?php echo JText::_("LNG_CLOSE")?></span>
                </button>
            </div>

            <fieldset class="pr-3 py-3">
                <p><?php echo JText::_('LNG_COMPANY_DETAILS_TXT');?></p>
                <p><?php echo JText::_('LNG_ADDRESS_SUGESTION');?></p>
                
                <div class="form-box">
                    <?php if ($attributeConfig["address_autocomplete"] != ATTRIBUTE_NOT_SHOW) { ?>
                        <div class="form-group autocomplete-box" id="autocomplete-container">
                            <label for="address_id"><?php echo JText::_('LNG_ADDRESS')?></label>
                            <input type="text" id="autocomplete" class="input_txt" placeholder="Enter your address" onFocus="" />
                        </div>
                        <br/>
                    <?php } ?>

                    <div class="form-group">
                        <label for="name"><?php echo JText::_('LNG_LOCATION_NAME')?></label>
                        <input type="text" name="name" id="name" class="input_txt form-control text-input" value="<?php echo $this->location->name ?>">
                    </div>

                    <?php if($attributeConfig["street_number"]!=ATTRIBUTE_NOT_SHOW){?>
                        <div class="form-group">
                            <label for="address_id"><?php echo JText::_('LNG_STREET_NUMBER')?><?php echo JBusinessUtil::showMandatory($attributeConfig["street_number"])?></label>
                            <input type="text" name="street_number" id="street_number" class="input_txt form-control text-input <?php echo $attributeConfig["street_number"] == ATTRIBUTE_MANDATORY?"validate[required]":""?>" value="<?php echo $this->location->street_number ?>">
                        </div>
                    <?php } ?>

                    <?php if($attributeConfig["address"]!=ATTRIBUTE_NOT_SHOW){?>
                        <div class="form-group">
                            <label for="address_id"><?php echo JText::_('LNG_ADDRESS')?><?php echo JBusinessUtil::showMandatory($attributeConfig["address"])?></label>
                            <input type="text" name="address" id="route" class="input_txt form-control <?php echo $attributeConfig["address"] == ATTRIBUTE_MANDATORY?"validate[required]":""?> text-input" value="<?php echo $this->location->address ?>">
                        </div>
                    <?php } ?>

                    <?php if($attributeConfig["area"]!=ATTRIBUTE_NOT_SHOW){?>
                        <div class="form-group" id="districtContainer">
                            <label for="area_id"><?php echo JText::_('LNG_AREA')?><?php echo JBusinessUtil::showMandatory($attributeConfig["area"])?></label>
                            <input class="input_txt form-control <?php echo $attributeConfig["area"] == ATTRIBUTE_MANDATORY?"validate[required]":""?> text-input" type="text" name="area" id="area_id" value="<?php echo $this->location->area ?>" maxlength="60" />
                        </div>
                    <?php } ?>


                    <?php if($attributeConfig["country"]!=ATTRIBUTE_NOT_SHOW){?>
                        <div class="form-group">
                            <label for="countryId"><?php echo JText::_('LNG_COUNTRY')?><?php echo JBusinessUtil::showMandatory($attributeConfig["country"])?></label>
                            <select class="input_sel form-control <?php echo $attributeConfig["country"] == ATTRIBUTE_MANDATORY?"validate[required]":""?> select" name="countryId" id="country" <?php echo $this->appSettings->limit_cities_regions ? 'onclick="updateRegions()"' : ''; ?> >
                                    <option value=''></option>
                                    <?php
                                        foreach( $this->item->countries as $country ){
                                    ?>
                                        <option <?php echo $this->location->countryId==$country->id? "selected" : ""?>
                                            value='<?php echo $country->id?>'
                                        ><?php echo $country->country_name ?></option>
                                    <?php
                                        }
                                    ?>
                            </select>
                        </div>
                    <?php } ?>

                    <?php if($attributeConfig["province"]!=ATTRIBUTE_NOT_SHOW){?>
                        <div class="form-group" id="districtContainer">
                            <label for="province_id"><?php echo JText::_('LNG_PROVINCE')?><?php echo JBusinessUtil::showMandatory($attributeConfig["province"])?></label>
                            <input class="input_txt form-control <?php echo $attributeConfig["province"] == ATTRIBUTE_MANDATORY?"validate[required]":""?> text-input" type="text" name="province" id="administrative_area_level_2" value="<?php echo $this->location->province ?>" maxlength="60" />
                        </div>
                    <?php } ?>

                    <?php if($attributeConfig["region"]!=ATTRIBUTE_NOT_SHOW){?>
                        <div class="form-group" id="districtContainer">
                            <?php if ($this->appSettings->limit_cities_regions != 1) { ?>
                                <label for="district_id"><?php echo JText::_('LNG_COUNTY')?><?php echo JBusinessUtil::showMandatory($attributeConfig["region"])?></label>
                                <input type="text" class="input_txt form-control <?php echo $attributeConfig["region"] == ATTRIBUTE_MANDATORY?"validate[required]":""?> text-input" name="county" id="administrative_area_level_1" value="<?php echo $this->location->county ?>" />
                            <?php } else { ?>
                                <label for="activity_regions"><?php echo JText::_('LNG_SELECT_REGION')?> <?php echo JBusinessUtil::showMandatory($attributeConfig["region"]) ?></label>
                                <select id="activity_regions" class="form-control input-medium chosen-select <?php echo $attributeConfig["region"] == ATTRIBUTE_MANDATORY?"validate[required]":""?>" name="activity_regions[]" onchange="updateCities()">
                                    <?php
                                    foreach ($this->item->regions as $region) {
                                        $selected = false;
                                        foreach ($this->item->activityRegions as $aregion) {
                                            if ($aregion->region_id == $region->id)
                                                $selected = true;
                                        } ?>
                                        <option <?php echo $selected ? "selected" : ""?> value='<?php echo $region->id ?>'>
                                            <?php echo $region->name ?>
                                        </option>
                                        <?php
                                    } ?>
                                </select>
                            <?php } ?>
                        </div>
                    <?php } ?>

                    <?php if($attributeConfig["city"]!=ATTRIBUTE_NOT_SHOW){?>
                        <div class="form-group">
                            <?php if ($this->appSettings->limit_cities_regions != 1) { ?>
                                <label for="city_id"><?php echo JText::_('LNG_CITY')?><?php echo JBusinessUtil::showMandatory($attributeConfig["city"])?></label>
                                <input type="text" class="input_txt form-control <?php echo $attributeConfig["city"] == ATTRIBUTE_MANDATORY?"validate[required]":""?> text-input" name="city" id="locality" value="<?php echo $this->location->city ?>">
                            <?php } else { ?>
                                <label for="activity_cities"><?php echo JText::_('LNG_SELECT_CITY')?> <?php echo JBusinessUtil::showMandatory($attributeConfig["city"]) ?></label>
                                <select id="activity_cities" class="form-control input-medium chosen-select  <?php echo $attributeConfig["city"] == ATTRIBUTE_MANDATORY ? "validate[required]" : "" ?>" name="activity_cities[]">
                                    <?php
                                    foreach( $this->item->cities as $city ) {
                                        $selected = false;
                                        foreach($this->item->activityCities as $acity) {
                                            if($acity->city_id == $city->id)
                                                $selected = true;
                                        } ?>
                                        <option <?php echo $selected ? "selected" : ""?> value='<?php echo $city->id ?>'>
                                            <?php echo $city->name ?>
                                        </option>
                                        <?php
                                    } ?>
                                </select>
                            <?php } ?>
                        </div>
                    <?php } ?>

                    <?php if($attributeConfig["postal_code"]!=ATTRIBUTE_NOT_SHOW){?>
                        <div class="form-group" id="districtContainer">
                            <label for="district_id"><?php echo JText::_('LNG_POSTAL_CODE')?><?php echo JBusinessUtil::showMandatory($attributeConfig["postal_code"])?></label>
                            <input type="text" class="input_sel form-control <?php echo $attributeConfig["postal_code"] == ATTRIBUTE_MANDATORY?"validate[required]":""?>" name="postalCode" id="postal_code" value="<?php echo $this->location->postalCode ?>" />
                        </div>
                    <?php } ?>

                    <?php if($attributeConfig["phone"]!=ATTRIBUTE_NOT_SHOW) { ?>
                            <div class="form-group">
                                <label for="phone"><?php echo JText::_('LNG_TELEPHONE')?><?php echo JBusinessUtil::showMandatory($attributeConfig["phone"])?></label>
                                <input type="text"	name="phone" id="phone" class="input_txt form-control <?php echo $attributeConfig["phone"] == ATTRIBUTE_MANDATORY?"validate[required]":""?> text-input"
                                    value="<?php echo $this->location->phone ?>">
                            </div>
                    <?php } ?>

                    <?php if(!$enablePackages || isset($this->item->package->features) && in_array(GOOGLE_MAP,$this->item->package->features)){ ?>
                        <?php if($attributeConfig["map"]!=ATTRIBUTE_NOT_SHOW){?>

                            <div class="form-group">
                                <label for="latitude"><?php echo JText::_('LNG_LATITUDE')?><?php echo JBusinessUtil::showMandatory($attributeConfig["map"])?></label>
                                <p class="small"><?php echo JText::_('LNG_MAP_INFO')?></p>
                                <input class="input_txt form-control <?php echo $attributeConfig["map"] == ATTRIBUTE_MANDATORY?"validate[required]":""?>" type="text" name="latitude" id="latitude" value="<?php echo $this->location->latitude ?>">
                            </div>

                            <div class="form-group">
                                <label for="longitude"><?php echo JText::_('LNG_LONGITUDE')?><?php echo JBusinessUtil::showMandatory($attributeConfig["map"])?></label>
                                <p class="small"><?php echo JText::_('LNG_MAP_INFO')?></p>
                                <input class="input_txt form-control <?php echo $attributeConfig["map"] == ATTRIBUTE_MANDATORY?"validate[required]":""?>" type="text" name="longitude" id="longitude" value="<?php echo $this->location->longitude ?>">
                            </div>

                            <div id="map-container">
                                <div id="company-map">
                                </div>
                            </div>
                        <?php }?>
                    <?php } ?>
                </div>
            </fieldset>
            
            <div class="button-row">
                <button type="button" class="btn btn-success" onclick="saveLocation();">
                    <span class="ui-button-text"><?php echo JText::_("LNG_SAVE")?></span>
                </button>
                <button type="button" class="btn btn-danger" onclick="parent.jQuery.jbdModal.close();">
                    <span class="ui-button-text"><?php echo JText::_("LNG_CLOSE")?></span>
                </button>
            </div>
        </div>
    	<input type="hidden" name="option" value="<?php echo JBusinessUtil::getComponentName()?>" /> 
    	<input type="hidden" name="company_id" value="<?php echo !empty($this->item->id)?$this->item->id:$this->location->company_id ?>" /> 
    	<input type="hidden" name="locationId" id="locationId" value="<?php echo isset($this->location->id)?$this->location->id:"0" ?>" />
    	<input type="hidden" name="identifier" id="identifier" value="<?php echo $identifier; ?>" />
    	
    	
    	<?php if(isset($isProfile)){ ?>
    		<input type="hidden" name="task" id="task" value="managecompany.saveLocation" />
    		<input type="hidden" name="view" id="view" value="managecompany" /> 
    	<?php }else{ ?>
    		<input type="hidden" name="task" id="task" value="company.saveLocation" />
    		<input type="hidden" name="view" id="view" value="company" />
    	<?php }?>
    	<?php echo JHTML::_( 'form.token' ); ?>
    </form>
</div>

<?php

if (isset($isProfile)) {
    echo JBusinessUtil::getMapGDPRModal();
}

JBusinessUtil::loadUploadScript(true, true,true,true);

$latitude = isset($this->location->latitude) && strlen($this->location->latitude)>0?$this->location->latitude:"0";
$longitude = isset($this->location->longitude) && strlen($this->location->longitude)>0?$this->location->longitude:"0";

$map_zoom = $this->appSettings->map_zoom;
if ((empty($map_zoom)) || (!is_numeric($map_zoom))) {
	$map_zoom = 10;
}

$initparams =  array();
$initparams['map_latitude'] = $latitude;
$initparams['map_longitude'] = $longitude;
$initparams['map_zoom'] = empty($this->item->latitude)?(int)$map_zoom:15;
$initparams['longitude'] = $this->item->longitude;
$initparams['latitude'] = $this->item->latitude;
$initparams['is_admin'] = true;
if ($this->appSettings->map_type == MAP_TYPE_BING) {
	$initparams["key"] = $mapKey;
}

$initLocation = new stdClass();
$initLocation->longitude = $longitude;
$initLocation->latitude = $latitude;
$initLocations = array($initLocation);
?>

<script>
var jbdAdminMapInstance;

function initialize() {
    <?php if ($attributeConfig["map"] != ATTRIBUTE_NOT_SHOW) { ?>
        jbdAdminMapInstance  = JBDMapHelper.loadMapScript(
            <?php echo json_encode($initLocations) ?>,
            <?php echo json_encode($initparams)?>
        );
        jbdUtils.addAdminMapClickAction();
    <?php } ?>
}

function saveLocation(){
	if(!jbdUtils.validateCmpForm(false, false)){
		jQuery("#item-form").submit();
	}
}

function updateLocation(id, name, streetNumber, address, city, county, country) {
	if (parent.jQuery("#location-" + id).length > 0) {
        parent.jQuery("#location-" + id).html(name + " - " + streetNumber + ", " + address + ", " + city + ", " + county + ", " + country);
    }
    else {
        let locationContainer = '<div id="location-box-' + id + '" class="detail_box">';
        locationContainer += '<div id="location-' + id + '">' + name + " - " + streetNumber + ", " + address + ", " + city + ", " + county + " ," + country + '</div>';
        locationContainer += '<a href = "javascript:jbdListings.editLocation('+id+')"><?php echo JText::_("LNG_EDIT") ?></a>';
        locationContainer += ' | ';
        locationContainer += '<a href = "javascript:jbdListings.deleteLocation('+id+')" ><?php echo JText::_("LNG_DELETE") ?></a>';
        locationContainer += '</div>';
        parent.jQuery("#company-locations").append(locationContainer);
    }
}

window.addEventListener('load', function(){
	jQuery("#item-form").validationEngine('attach');
	<?php if(!$enablePackages || isset($this->item->package->features) && in_array(GOOGLE_MAP,$this->item->package->features)){ ?>
    initialize();
	<?php }?>
    jbdUtils.initializeAdminAutocomplete(true);

	if(jQuery("#locationId").val()>0){
        updateLocation(jQuery("#locationId").val(), jQuery("#name").val(), jQuery("#street_number").val(),jQuery("#route").val(),jQuery("#locality").val(),jQuery("#administrative_area_level_1").val(),jQuery("#country :selected").text());
	}
});

<?php if ($this->appSettings->limit_cities_regions == 1) { ?>
    var showCountryAttr = <?php echo $attributeConfig["country"]!=ATTRIBUTE_NOT_SHOW ?'true':'false'; ?>

    function updateCities(callback)
    {
        var regionIds = jQuery('#activity_regions').val();

        var dataSelected = [];
        jQuery('#activity_cities').find('option:selected').each(function(){
            dataSelected.push(jQuery(this).val());
        });

        if (regionIds == null) {
            jQuery('#activity_cities').empty();
            jbdUtils.updateChosenSelect('#activity_cities');
            return;
        }
        let url = jbdUtils.getAjaxUrl('getCitiesByRegionsAjax', 'company');
        jQuery.ajax({
            type: 'GET',
            url: url,
            data: {regionIds: regionIds},
            dataType: 'json',
            success: function (data) {
                var selectedVar;
                jQuery('#activity_cities').empty();

                var tmp = [];
                tmp.id = -1;
                tmp.name = '<?php echo JText::_('LNG_SELECT_CITY') ?>';
                data.unshift(tmp);

                jQuery.each(data, function (i, val) {
                    selectedVar = "";
                    if (jQuery.inArray(val.id, dataSelected) != '-1') {
                        selectedVar = "selected";
                    }
                    jQuery('#activity_cities').append('<option ' + selectedVar + ' value="' + val.id + '">' + val.name + '</option>');
                });
                jbdUtils.updateChosenSelect('#activity_cities');

                if (typeof callback !== "undefined") {
                    callback();
                }
            }
        });
    }

    function updateRegions(callback)
    {
        var countryId = jQuery('#country').val();

        var dataSelected = [];
        jQuery('#activity_regions').find('option:selected').each(function(){
            dataSelected.push(jQuery(this).val());
        });

        if (showCountryAttr && countryId == null) {
            jQuery('#activity_regions').empty();
            jbdUtils.updateChosenSelect('#activity_regions');
            return;
        }
        let url = jbdUtils.getAjaxUrl('getRegionsByCountryAjax', 'company');
        jQuery.ajax({
            type: 'GET',
            url: url,
            data: {countryId: countryId},
            dataType: 'json',
            success: function (data) {
                var selectedVar;
                jQuery('#activity_regions').empty();

                var tmp = [];
                tmp.id = -1;
                tmp.name = '<?php echo JText::_('LNG_SELECT_REGION') ?>';
                data.unshift(tmp);

                jQuery.each(data, function (i, val) {
                    selectedVar = "";
                    if (jQuery.inArray(val.id, dataSelected) != '-1') {
                        selectedVar = "selected";
                    }
                    jQuery('#activity_regions').append('<option ' + selectedVar + ' value="' + val.id + '">' + val.name + '</option>');
                });
                jbdUtils.updateChosenSelect('#activity_regions');

                updateCities();

                if (typeof callback !== "undefined") {
                    callback();
                }
            }
        });
    }

   
<?php } ?>
</script>