# /intranet-leaflet/lib/leaflet-component.tcl
#
# Variables from page:
#
# width
# height
# customer_status_id
# customer_type_id

if {![info exists width]} { set width 600 }
if {![info exists height]} { set height 400 }
if {![info exists customer_status_id]} { set customer_status_id "" }
if {![info exists customer_type_id]} { set customer_type_id "" }

# template::head::add_css -href "https://unpkg.com/leaflet@1.3.3/dist/leaflet.css" -media "screen" -order 100
# template::head::add_javascript -src "https://unpkg.com/leaflet@1.3.3/dist/leaflet.js" -order 200
template::head::add_css -href "/intranet-leaflet/resources/leaflet.css" -media "screen" -order 100
template::head::add_javascript -src "/intranet-leaflet/resources/leaflet.js" -order 200

# CSP - allow to load images from Open Street Map
security::csp::require img-src 'self'
security::csp::require img-src "*.osm.org"

set random_within_bbox_p [parameter::get_from_package_key -package_key "intranet-leaflet" -parameter RandomizePostionWithinBBoxP -default "0"]
set zoom_lat [parameter::get_from_package_key -package_key "intranet-leaflet" -parameter ZoomLatitude -default "41.4"]
set zoom_lng [parameter::get_from_package_key -package_key "intranet-leaflet" -parameter ZoomLongitude -default "2.2"]
set zoom_zoom [parameter::get_from_package_key -package_key "intranet-leaflet" -parameter ZoomZoom -default "3"]

set customer_sql "
	select	c.company_id,
		c.company_name,
		c.company_status_id,
		o.office_id,
		o.address_city as city,
		o.address_country_code as country_code,
		(select min(country_name) from country_codes where lower(iso) = lower(o.address_country_code)) as country,
		o.address_line1 as line1,
		o.address_line2 as line2,
		o.address_postal_code as zip_code,
		o.address_state as state,
		o.geo_lat,
		o.geo_lng,
		CASE WHEN ao.last_modified > coalesce(o.geo_last_modified, '2000-01-01'::date) 
		     THEN 1 ELSE 0 END as needs_update_p,
		(	select greatest(round(coalesce(sum(co.amount),0.0)), 0.0)
			from im_costs co 
			where co.cost_type_id in (select * from im_sub_categories([im_cost_type_invoice])) and 
			      co.customer_id = c.company_id
		) as invoice_amount
	from	im_companies c,
		im_offices o,
		acs_objects ao
	where	c.main_office_id = o.office_id and
		c.main_office_id = ao.object_id
"

if {"" ne $customer_type_id} { 
    append customer_sql "and c.company_type_id in ([join [im_sub_categories $customer_type_id] ","])" 
}

if {"" ne $customer_status_id} { 
    append customer_sql "and c.company_status_id in ([join [im_sub_categories $customer_status_id] ","])" 
}

set sql "
select	t.*,
	CASE WHEN invoice_amount <= 0.0 THEN 'red'
	WHEN company_status_id in ([join [im_sub_categories [im_company_status_potential]] ","]) THEN 'green'
	ELSE 'blue'
	END as color
 from	($customer_sql) t
where	invoice_amount > 0.0
order by
	t.company_id
"


# ad_return_complaint 1 [im_ad_hoc_query -format html $sql]


set store [lindex [im_sencha_sql_to_store -sql $sql] 0]

