-- =============================================================================
-- larcare_nav_portal.sql - adds a "Portal" link (/portal) to LarCare's header (last link) and to the footer's Company
-- column, as Navigation items editable in ABOS > Website > Navigation.
-- Runs ONCE: it records portalNavSeeded in the site's theme settings, so a link someone later removes or renames
-- is never put back. If the site already has a header link to /portal it is left as it is.
-- Requires larcare_header_footer_seed.sql first.
-- =============================================================================
SET @site_id := (SELECT id FROM dim_web_sites WHERE public_site_key = 'pSlfeq9OCm5MvZyoFguIK7jy0uz2aKShJkxZxTSWXwzPOpYJ' AND is_deleted = 0 LIMIT 1);
SET @tenant_id := (SELECT tenant_id FROM dim_web_sites WHERE id = @site_id LIMIT 1);
SET @business_id := (SELECT business_id FROM dim_web_sites WHERE id = @site_id LIMIT 1);
SET @once := IF(@site_id IS NOT NULL AND IFNULL((SELECT JSON_UNQUOTE(JSON_EXTRACT(IFNULL(theme_json, '{}'), '$.portalNavSeeded')) FROM dim_web_sites WHERE id = @site_id), '') <> 'true', 1, 0);

SET @header_next := (SELECT IFNULL(MAX(sort_order), 0) + 1 FROM dim_web_navigation_items WHERE site_id = @site_id AND location = 'header' AND is_deleted = 0 AND parent_id IS NULL);
INSERT INTO dim_web_navigation_items (tenant_id, business_id, site_id, parent_id, location, column_title, label, href, open_in_new_tab, sort_order, is_active, is_deleted)
SELECT @tenant_id, @business_id, @site_id, NULL, 'header', NULL, 'Portal', '/portal', 0, @header_next, 1, 0 FROM DUAL
WHERE @once = 1
  AND NOT EXISTS (SELECT 1 FROM dim_web_navigation_items WHERE site_id = @site_id AND location = 'header' AND is_deleted = 0 AND href COLLATE utf8mb4_bin = '/portal' COLLATE utf8mb4_bin);

SET @footer_next := (SELECT IFNULL(MAX(sort_order), 0) + 1 FROM dim_web_navigation_items WHERE site_id = @site_id AND location = 'footer' AND is_deleted = 0 AND column_title COLLATE utf8mb4_bin = 'Company' COLLATE utf8mb4_bin);
INSERT INTO dim_web_navigation_items (tenant_id, business_id, site_id, parent_id, location, column_title, label, href, open_in_new_tab, sort_order, is_active, is_deleted)
SELECT @tenant_id, @business_id, @site_id, NULL, 'footer', 'Company', 'Portal', '/portal', 0, @footer_next, 1, 0 FROM DUAL
WHERE @once = 1
  AND NOT EXISTS (SELECT 1 FROM dim_web_navigation_items WHERE site_id = @site_id AND location = 'footer' AND is_deleted = 0 AND href COLLATE utf8mb4_bin = '/portal' COLLATE utf8mb4_bin);

UPDATE dim_web_sites SET theme_json = JSON_SET(IFNULL(theme_json, '{}'), '$.portalNavSeeded', 'true') WHERE id = @site_id AND @once = 1;
