# /packages/intranet-leaflet/www/update-ofice.tcl
#
# Copyright (C) 2003-2011 ]project-open[
#
# All rights reserved. Please check
# https://www.project-open.com/license/ for details.

ad_page_contract {
    Updates the geo lat+lng parameters of an office.
    These are considered not security critical, so that
    we won't check for permissions
    
    @author frank.bergmann@project-open.com
} {
    office_id:integer
    lat:float
    lng:float
}

set user_id [auth::require_login]

# Update only if not set yet.
# This is important, because we launch multiple requests per office,
# in order from more detailed to less detailed.
set geo_already_set_p [db_string geo_p "
	select	count(*)
	from	im_offices
	where	office_id = :office_id and 
		geo_last_modified is not null and 
		geo_lat is not null and
		geo_lng is not null and
		geo_last_modified > (select last_modified from acs_objects where object_id = office_id)
"]

if {!$geo_already_set_p} {

    # Avoid two identical locations
    # Two offices in the same city, but not additional (zip, street...) information?
    set geo_duplicate_p [db_string geo_duplicate "
	select	count(*)
	from	im_offices
	where	geo_lat = :lat and
		geo_lng = :lng
    "]
    if {$geo_duplicate_p} {
	set lat [expr $lat + (rand()-0.5) * 0.1]
	set lng [expr $lng + (rand()-0.5) * 0.1]
    }

    db_dml update_office "
	update im_offices set 
		geo_lat = :lat,
		geo_lng = :lng,
		geo_last_modified = now()
	where office_id = :office_id
    "
}
doc_return 200 "text/html" "<h1>OK</h1>"

