
-- Clear previous proc
DROP PROCEDURE IF EXISTS p_dog_user_eval;
DROP PROCEDURE IF EXISTS p_dog_calc_user_access;
DROP PROCEDURE IF EXISTS p_dog_user_calc;
DROP PROCEDURE IF EXISTS p_dog_calc_user_access;

DELIMITER //
CREATE PROCEDURE fetchmetrics.p_dog_calc_user_access (
	  IN a_guid BINARY(36)
    , IN a_get_all_user BIT
    , IN a_get_inactive_user BIT
	, IN a_ids_user TEXT
    , IN a_auth0_ids_user TEXT
    , IN a_names_user TEXT
    , IN a_emails_user TEXT
    /*
    , IN a_get_all_company BIT
    , IN a_get_inactive_company BIT
    , IN a_ids_company TEXT
    , IN a_names_company TEXT
    , IN a_websites_company TEXT
    */
    , IN a_require_all_id_search_filters_met BIT
    , IN a_require_any_id_search_filters_met BIT
    , IN a_require_all_non_id_search_filters_met BIT
    , IN a_require_any_non_id_search_filters_met BIT
    , IN a_ids_permission_required TEXT
    , IN a_ids_access_level_required TEXT
    , IN a_show_errors BIT
    , IN a_debug BIT
)
BEGIN
    DECLARE v_code_type_error_bad_data VARCHAR(200);
    DECLARE v_has_filter_access_level BIT;
    DECLARE v_has_filter_permission BIT;
    DECLARE v_has_filter_user_auth0_id BIT;
    DECLARE v_has_filter_user_id BIT;
    DECLARE v_has_filter_user_email BIT;
    DECLARE v_has_filter_user_name BIT;
    DECLARE v_id_access_level_required INT;
    DECLARE v_id_access_level_view INT;
    DECLARE v_id_permission_required INT;
    DECLARE v_id_type_error_bad_data INT;
	DECLARE v_ids_row_delete VARCHAR(500);
    DECLARE v_priority_access_level_admin INT;
    DECLARE v_priority_access_level_edit INT;
    DECLARE v_priority_access_level_none INT;
    DECLARE v_priority_access_level_required INT;
    DECLARE v_priority_access_level_view INT;
    DECLARE v_time_start TIMESTAMP(6);
    
    DECLARE exit handler for SQLEXCEPTION
    BEGIN
        GET DIAGNOSTICS CONDITION 1
            @sqlstate = RETURNED_SQLSTATE
            , @errno = MYSQL_ERRNO
            , @text = MESSAGE_TEXT
		;
        
        ROLLBACK;
        
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error_Calc_User_Access (
			  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
			, id_type INT
			, code VARCHAR(250) NOT NULL
			, msg TEXT NOT NULL
		);

        INSERT INTO tmp_Msg_Error_Calc_User_Access (
			  id_type
            , code
            , msg
		)
        SELECT 
			  MET.id_type
            , @errno
            , @text
		FROM fetchmetrics.CORE_Msg_Error_Type MET
        WHERE MET.code = 'MYSQL_ERROR'
		;
        
        SELECT 
            t_ERROR.id_error
            , t_ERROR.id_type
            , t_ERROR.code
            , ERROR_TYPE.name
            , ERROR_TYPE.description
            , ERROR_TYPE.is_breaking_error
            , ERROR_TYPE.background_colour
            , ERROR_TYPE.text_colour
            , t_ERROR.msg
        FROM tmp_Msg_Error_Calc_User_Access t_ERROR
        INNER JOIN fetchmetrics.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
        ;
        
		DROP TABLE IF EXISTS tmp_Msg_Error_Calc_User_Access;
    END;
    
    SET v_time_start := CURRENT_TIMESTAMP(6);
    SET v_code_type_error_bad_data := 'BAD_DATA';
    SET v_id_type_error_bad_data := (SELECT id_type FROM fetchmetrics.CORE_Msg_Error_Type WHERE code = v_code_type_error_bad_data LIMIT 1);
    SET v_id_access_level_view = (SELECT id_access_level FROM fetchmetrics.DOG_Access_Level WHERE code = 'VIEW' LIMIT 1);
    SET v_priority_access_level_view = (SELECT priority FROM fetchmetrics.DOG_Access_Level WHERE id_access_level = v_id_access_level_view);
    SET v_priority_access_level_edit = (SELECT priority FROM fetchmetrics.DOG_Access_Level WHERE code = 'EDIT' LIMIT 1);
    SET v_priority_access_level_admin = (SELECT priority FROM fetchmetrics.DOG_Access_Level WHERE code = 'ADMIN' LIMIT 1);
    SET v_priority_access_level_none = (SELECT priority FROM fetchmetrics.DOG_Access_Level WHERE code = 'NONE' LIMIT 1);
    
    CALL fetchmetrics.p_validate_guid ( a_guid );
    SET a_get_all_user := IFNULL(a_get_all_user, 0);
    SET a_get_inactive_user := IFNULL(a_get_inactive_user, 0);
    SET a_ids_user := TRIM(IFNULL(a_ids_user, ''));
    SET a_auth0_ids_user := TRIM(IFNULL(a_auth0_ids_user, ''));
    SET a_names_user := TRIM(IFNULL(a_names_user, ''));
    SET a_emails_user := TRIM(IFNULL(a_emails_user, ''));
    /*
    SET a_get_all_company := IFNULL(a_get_all_company, 0);
    SET a_get_inactive_company := IFNULL(a_get_inactive_company, 0);
    SET a_ids_company := TRIM(IFNULL(a_ids_company, ''));
    SET a_names_company := TRIM(IFNULL(a_names_company, ''));
    SET a_websites_company := TRIM(IFNULL(a_websites_company, ''));
    */
    SET a_require_all_id_search_filters_met := IFNULL(a_require_all_id_search_filters_met, 0);
    SET a_require_any_id_search_filters_met := IFNULL(a_require_any_id_search_filters_met, 0);
    SET a_require_all_non_id_search_filters_met := IFNULL(a_require_all_non_id_search_filters_met, 0);
    SET a_require_any_non_id_search_filters_met := IFNULL(a_require_any_non_id_search_filters_met, 0);
    SET a_ids_permission_required := TRIM(IFNULL(a_ids_permission_required, ''));
    SET a_ids_access_level_required := TRIM(IFNULL(a_ids_access_level_required, ''));
    SET a_show_errors := IFNULL(a_show_errors, 0);
    SET a_debug := IFNULL(a_debug, 0);
    
    IF a_debug = 1 THEN
		SELECT
			  a_guid
            , a_get_all_user
            , a_get_inactive_user
            , a_ids_user
            , a_auth0_ids_user
            , a_names_user
            , a_emails_user
            /*
            , a_get_all_company
            , a_get_inactive_company
            , a_ids_company
            , a_names_company
            , a_websites_company
            */
            , a_require_all_id_search_filters_met
            , a_require_any_id_search_filters_met
            , a_require_all_non_id_search_filters_met
            , a_require_any_non_id_search_filters_met
            , a_ids_permission_required
            , a_ids_access_level_required
            , a_show_errors
            , a_debug
		;

		SELECT 
			  v_priority_access_level_view
			, v_priority_access_level_edit
			, v_priority_access_level_admin
			, v_id_access_level_view
			, v_id_type_error_bad_data
			, v_code_type_error_bad_data
		;
    END IF;
    
	-- Clear previous proc results
	DROP TABLE IF EXISTS tmp_Split_Email_Calc_User_Access;
	DROP TABLE IF EXISTS tmp_Split_Name_Calc_User_Access;
	DROP TABLE IF EXISTS tmp_Split_Auth0_Id_Calc_User_Access;
	DROP TABLE IF EXISTS tmp_Split_Id_Calc_User_Access;
	DROP TABLE IF EXISTS tmp_Msg_Error_Calc_User_Access;
	DROP TABLE IF EXISTS tmp_Calc_User_Access_Calc_User_Access;
    
    -- Permanent Table
    /*
    CREATE TEMPORARY TABLE tmp_Company_Calc_User_Access (
		  id_company INT NOT NULL
        , name VARCHAR(250) NOT NULL
        , websites VARCHAR(1000)
        , active BIT NOT NULL
        , does_meet_id_filters BIT NOT NULL
        , does_meet_non_id_filters BIT NOT NULL
    );
    */

	CREATE TEMPORARY TABLE tmp_Calc_User_Access_Calc_User_Access (
		  id_temp INT PRIMARY KEY AUTO_INCREMENT NOT NULL
		, id_user INT
		, id_permission_required INT NOT NULL
		, priority_access_level_required INT NOT NULL
        , is_super_user BIT
		, priority_access_level_user INT
		, has_access BIT
		, can_view BIT
		, can_edit BIT
		, can_admin BIT

        , does_meet_id_filters BIT
        , does_meet_non_id_filters BIT
	);
    
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error_Calc_User_Access (
		  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
		, id_type INT
        , code VARCHAR(250) NOT NULL
        , msg TEXT NOT NULL
	);
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split_Id_Calc_User_Access (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT
	);
    DELETE FROM tmp_Split_Id_Calc_User_Access;
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split_Auth0_Id_Calc_User_Access (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT
	);
    DELETE FROM tmp_Split_Auth0_Id_Calc_User_Access;
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split_Name_Calc_User_Access (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT
	);
    DELETE FROM tmp_Split_Name_Calc_User_Access;
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split_Email_Calc_User_Access (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT
	);
    DELETE FROM tmp_Split_Email_Calc_User_Access;
	
    SET v_has_filter_user_id = CASE WHEN a_ids_user <> '' THEN 1 ELSE 0 END;
    SET v_has_filter_user_auth0_id = CASE WHEN a_auth0_ids_user <> '' THEN 1 ELSE 0 END;
    SET v_has_filter_user_name = CASE WHEN a_names_user <> '' THEN 1 ELSE 0 END;
    SET v_has_filter_user_email = CASE WHEN a_emails_user <> '' THEN 1 ELSE 0 END;
    /*
    */
    SET v_has_filter_permission = CASE WHEN a_ids_permission_required <> '' THEN 1 ELSE 0 END;
    SET v_has_filter_access_level = CASE WHEN a_ids_access_level_required <> '' THEN 1 ELSE 0 END;

    IF a_debug = 1 THEN
		SELECT 
			  v_has_filter_user_id
			, v_has_filter_user_auth0_id
			, v_has_filter_user_name
			, v_has_filter_user_email
			, v_has_filter_permission
			, v_has_filter_access_level
		;
    END IF;
    
    # Access levels
	IF v_has_filter_access_level = 1 THEN
        IF a_debug = 1 THEN
            SELECT
                  'p_core_split'
                , a_guid
                , a_ids_access_level_required
                , ','
                , a_debug
            ;
        END IF;

		CALL fetchmetrics.p_core_split(a_guid, a_ids_access_level_required, ',', a_debug);
		
		INSERT INTO tmp_Split_Id_Calc_User_Access (
			  substring
			, as_int
		)
		SELECT 
			  SPLIT_T.substring
			, CONVERT(SPLIT_T.substring, DECIMAL(10,0)) -- AS as_int
		FROM fetchmetrics.CORE_Split_Temp SPLIT_T
		WHERE
			    GUID = a_guid
			AND IFNULL(SPLIT_T.substring, '') != ''
		;

        IF a_debug = 1 THEN
            SELECT 'Access Levels split', a_ids_access_level_required;
            SELECT *
            FROM tmp_Split_Id_Calc_User_Access;
        END IF;
		
		CALL fetchmetrics.p_core_clear_split( a_guid );
		
		# Invalid IDs
		IF EXISTS (
			SELECT t_SPLIT.substring 
			FROM tmp_Split_Id_Calc_User_Access t_SPLIT
			LEFT JOIN fetchmetrics.DOG_Access_Level ACCESS_LEVEL ON t_SPLIT.as_int = ACCESS_LEVEL.id_access_level
			WHERE 
				    ISNULL(t_SPLIT.as_int)
				OR  ISNULL(ACCESS_LEVEL.id_access_level)
				OR  ACCESS_LEVEL.active = 0
		) THEN
			INSERT INTO tmp_Msg_Error_Calc_User_Access (
				  id_type
				, code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
				, v_code_type_error_bad_data
				, CONCAT('Invalid or inactive access level IDs: ', GROUP_CONCAT(t_SPLIT.substring SEPARATOR ','))
			FROM tmp_Split_Id_Calc_User_Access t_SPLIT 
			LEFT JOIN fetchmetrics.DOG_Access_Level ACCESS_LEVEL ON t_SPLIT.as_int = ACCESS_LEVEL.id_access_level
			WHERE 
				    ISNULL(t_SPLIT.as_int)
				OR  ISNULL(ACCESS_LEVEL.id_access_level)
				OR  ACCESS_LEVEL.active = 0
			;

            SET v_has_filter_access_level = 0;
        ELSE
            SET v_id_access_level_required := (
                SELECT ACCESS_LEVEL.id_access_level 
                FROM tmp_Split_Id_Calc_User_Access t_SPLIT
                INNER JOIN fetchmetrics.DOG_Access_Level ACCESS_LEVEL 
                    ON  t_SPLIT.as_int = ACCESS_LEVEL.id_access_level
                    AND ACCESS_LEVEL.active = 1
                ORDER BY ACCESS_LEVEL.priority ASC 
                LIMIT 1
            );
		END IF;
	END IF;
	DELETE FROM tmp_Split_Id_Calc_User_Access;

    IF ISNULL(v_id_access_level_required) THEN
        SET v_id_access_level_required = v_id_access_level_view;
    END IF;
    
    -- Permission IDs
	IF v_has_filter_permission = 1 THEN
		CALL fetchmetrics.p_core_split(a_guid, a_ids_permission_required, ',', a_debug);
		
		INSERT INTO tmp_Split_Id_Calc_User_Access (
			  substring
			, as_int
		)
		SELECT 
			  SPLIT_T.substring
			, CONVERT(SPLIT_T.substring, DECIMAL(10,0)) AS as_int
		FROM fetchmetrics.CORE_Split_Temp SPLIT_T
		WHERE 
			    GUID = a_guid
			AND IFNULL(SPLIT_T.substring, '') != ''
		;

        IF a_debug = 1 THEN
            SELECT 'Permissions split', a_ids_permission_required;
            SELECT *
            FROM tmp_Split_Id_Calc_User_Access;
        END IF;
		
		CALL fetchmetrics.p_core_clear_split( a_guid );
		
		# Invalid or inactive
		IF EXISTS (SELECT PERMISSION.id_permission FROM tmp_Split_Id_Calc_User_Access t_SPLIT LEFT JOIN fetchmetrics.DOG_Permission PERMISSION ON t_SPLIT.as_int = PERMISSION.id_permission WHERE ISNULL(t_SPLIT.as_int) OR ISNULL(PERMISSION.id_permission) OR PERMISSION.active = 0) THEN
			INSERT INTO tmp_Msg_Error_Calc_User_Access (
				  id_type
				, code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
				, v_code_type_error_bad_data
				, CONCAT('Invalid or inactive permission IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT.substring SEPARATOR ','), 'NULL'))
			FROM tmp_Split_Id_Calc_User_Access t_SPLIT
			LEFT JOIN fetchmetrics.DOG_Permission PERMISSION ON t_SPLIT.as_int = PERMISSION.id_permission 
			WHERE 
				    ISNULL(t_SPLIT.as_int)
				OR  ISNULL(PERMISSION.id_permission)
				OR  PERMISSION.active = 0
			;
		ELSE 
			SET v_id_permission_required := (
				SELECT PERMISSION.id_permission
				FROM tmp_Split_Id_Calc_User_Access t_SPLIT
				INNER JOIN fetchmetrics.DOG_Permission PERMISSION ON t_SPLIT.as_int = PERMISSION.id_permission
                INNER JOIN fetchmetrics.DOG_Access_Level ACCESS_LEVEL ON PERMISSION.id_access_level_required = ACCESS_LEVEL.id_access_level
				ORDER BY ACCESS_LEVEL.priority ASC
				LIMIT 1
			);
		END IF;
	END IF;
    DELETE FROM tmp_Split_Id_Calc_User_Access;

    SET v_priority_access_level_required := (
        SELECT ACCESS_LEVEL.priority
        FROM fetchmetrics.DOG_Access_Level ACCESS_LEVEL
        LEFT JOIN fetchmetrics.DOG_Permission PERMISSION ON ACCESS_LEVEL.id_access_level = PERMISSION.id_access_level_required
        WHERE 
                ACCESS_LEVEL.id_access_level = v_id_access_level_required 
            OR  PERMISSION.id_permission = v_id_permission_required
        ORDER BY ACCESS_LEVEL.priority
        LIMIT 1
    );

	# Users
    # Ids
    IF v_has_filter_user_id = 1 THEN
        CALL fetchmetrics.p_core_split(a_guid, a_ids_user, ',', a_debug);
        
        INSERT INTO tmp_Split_Id_Calc_User_Access (
              substring
            , as_int
        )
        SELECT 
              SPLIT_T.substring
            , CONVERT(SPLIT_T.substring, DECIMAL(10,0)) AS as_int
        FROM fetchmetrics.CORE_Split_Temp SPLIT_T
        WHERE
                SPLIT_T.GUID = a_guid
            AND IFNULL(SPLIT_T.substring, '') != ''
        ;

        IF a_debug = 1 THEN
            SELECT 'User Id split', a_ids_user;
            SELECT *
            FROM tmp_Split_Id_Calc_User_Access;
        END IF;
        
        CALL fetchmetrics.p_core_clear_split( a_guid );
        
        # Invalid or inactive
        IF EXISTS (
            SELECT USER.id_user 
            FROM tmp_Split_Id_Calc_User_Access t_SPLIT 
            LEFT JOIN fetchmetrics.DOG_User USER ON t_SPLIT.as_int = USER.id_user 
            WHERE 
                    ISNULL(t_SPLIT.as_int) 
                OR  ISNULL(USER.id_user) 
                OR  (
                        a_get_inactive_user = 0 
                    AND USER.active = 0
                )
            ) 
        THEN
            INSERT INTO tmp_Msg_Error_Calc_User_Access (
                  id_type
                , code
                , msg
            )
            SELECT
                  v_id_type_error_bad_data
                , v_code_type_error_bad_data
                , CONCAT('Invalid or inactive user IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT.substring SEPARATOR ','), 'NULL'))
            FROM tmp_Split_Id_Calc_User_Access t_SPLIT
            LEFT JOIN fetchmetrics.DOG_User USER ON t_SPLIT.as_int = USER.id_user 
            WHERE 
                    ISNULL(t_SPLIT.as_int) 
                OR  ISNULL(USER.id_user)
                OR  (
                        a_get_inactive_user = 0
                    AND USER.active = 0
                )
            ;
        END IF;
    END IF;

    # Auth0 Ids
    IF v_has_filter_user_auth0_id = 1 THEN
        CALL fetchmetrics.p_core_split(a_guid, a_auth0_ids_user, ',', a_debug);
        
        INSERT INTO tmp_Split_Auth0_Id_Calc_User_Access ( substring )
        SELECT SPLIT_T.substring
        FROM fetchmetrics.CORE_Split_Temp SPLIT_T
        WHERE
                SPLIT_T.GUID = a_guid
            AND IFNULL(SPLIT_T.substring, '') != ''
        ;

        IF a_debug = 1 THEN
            SELECT 'User Auth0 Id split', a_auth0_ids_user;
            SELECT *
            FROM tmp_Split_Auth0_Id_Calc_User_Access;
        END IF;
        
        CALL fetchmetrics.p_core_clear_split( a_guid );
        
        # Invalid or inactive
        IF EXISTS (
            SELECT USER.id_user 
            FROM tmp_Split_Auth0_Id_Calc_User_Access t_SPLIT 
            LEFT JOIN fetchmetrics.DOG_User USER ON t_SPLIT.substring = USER.id_user_auth0
            WHERE 
                    ISNULL(USER.id_user) 
                OR  (
                        a_get_inactive_user = 0 
                    AND USER.active = 0
                )
            ) 
        THEN
            INSERT INTO tmp_Msg_Error_Calc_User_Access (
                  id_type
                , code
                , msg
            )
            SELECT
                  v_id_type_error_bad_data
                , v_code_type_error_bad_data
                , CONCAT('Invalid or inactive user Auth0 IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT.substring SEPARATOR ','), 'NULL'))
            FROM tmp_Split_Auth0_Id_Calc_User_Access t_SPLIT
            LEFT JOIN fetchmetrics.DOG_User USER ON t_SPLIT.substring = USER.id_user_auth0
            WHERE 
                    ISNULL(USER.id_user)
                OR  (
                        a_get_inactive_user = 0
                    AND USER.active = 0
                )
            ;
        END IF;
    END IF;
    
    # Names
    IF v_has_filter_user_name = 1 THEN
        CALL fetchmetrics.p_core_split(a_guid, a_names_user, ',', a_debug);
        
        INSERT INTO tmp_Split_Name_Calc_User_Access ( substring )
        SELECT SPLIT_T.substring
        FROM fetchmetrics.CORE_Split_Temp SPLIT_T
        WHERE
                SPLIT_T.GUID = a_guid
            AND IFNULL(SPLIT_T.substring, '') != ''
        ;

        IF a_debug = 1 THEN
            SELECT 'User Name split', a_names_user;
            SELECT *
            FROM tmp_Split_Name_Calc_User_Access;
        END IF;
        
        CALL fetchmetrics.p_core_clear_split( a_guid );
    END IF;
    
    # Emails
    IF v_has_filter_user_email = 1 THEN
        CALL fetchmetrics.p_core_split(a_guid, a_emails_user, ',', a_debug);
        
        INSERT INTO tmp_Split_Email_Calc_User_Access ( substring )
        SELECT SPLIT_T.substring
        FROM fetchmetrics.CORE_Split_Temp SPLIT_T
        WHERE
                SPLIT_T.GUID = a_guid
            AND IFNULL(SPLIT_T.substring, '') != ''
        ;

        IF a_debug = 1 THEN
            SELECT 'User Email split', a_emails_user;
            SELECT *
            FROM tmp_Split_Email_Calc_User_Access;
        END IF;
        
        CALL fetchmetrics.p_core_clear_split( a_guid );
    END IF;
    
    -- Get all users
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_User_Access t_ERROR INNER JOIN fetchmetrics.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
        INSERT INTO tmp_Calc_User_Access_Calc_User_Access (
              id_user
            , id_permission_required
            , priority_access_level_required
            , is_super_user
            /*
            , priority_access_level_user
            , can_view
            , can_edit
            , can_admin
            */
            , does_meet_id_filters
            , does_meet_non_id_filters
        )
        WITH 
              User_Id_Filter AS (
                SELECT USER.id_user
                FROM tmp_Split_Id_Calc_User_Access t_SPLIT_ID
                INNER JOIN fetchmetrics.DOG_User USER ON t_SPLIT_ID.as_int = USER.id_user
            )
            , User_Auth0_Id_Filter AS (
                SELECT USER.id_user
                FROM tmp_Split_Auth0_Id_Calc_User_Access t_SPLIT_AUTH0_ID
                INNER JOIN fetchmetrics.DOG_User USER ON t_SPLIT_AUTH0_ID.substring = USER.id_user_auth0
            )
            , User_Name_Filter AS (
                SELECT USER.id_user
                FROM tmp_Split_Name_Calc_User_Access t_SPLIT_NAME
                INNER JOIN fetchmetrics.DOG_User USER ON CONCAT(USER.firstname, ' ', USER.surname) LIKE CONCAT('%', t_SPLIT_NAME.substring, '%')
                WHERE IFNULL(t_SPLIT_NAME.substring, '') <> ''
            )
            , User_Email_Filter AS (
                SELECT USER.id_user
                FROM tmp_Split_Email_Calc_User_Access t_SPLIT_EMAIL
                INNER JOIN demo.DOG_User USER ON USER.email LIKE CONCAT('%', t_SPLIT_EMAIL.substring, '%')
                WHERE IFNULL(t_SPLIT_EMAIL.substring, '') <> ''
            )
            , User_Filters AS (
                SELECT 
                        USER_COMBINED.id_user
                    , MAX(USER_COMBINED.does_meet_id_filter) AS does_meet_id_filter
                    , MAX(USER_COMBINED.does_meet_auth0_id_filter) AS does_meet_auth0_id_filter
                    , MAX(USER_COMBINED.does_meet_name_filter) AS does_meet_name_filter
                    , MAX(USER_COMBINED.does_meet_email_filter) AS does_meet_email_filter
                FROM (
                    SELECT 
                            USER_ID_FILTER.id_user 
                        , 1 AS does_meet_id_filter
                        , 0 AS does_meet_auth0_id_filter
                        , 0 AS does_meet_name_filter
                        , 0 AS does_meet_email_filter
                    FROM User_Id_Filter USER_ID_FILTER
                    UNION
                    SELECT 
                            USER_AUTH0_ID_FILTER.id_user 
                        , 0 AS does_meet_id_filter
                        , 1 AS does_meet_auth0_id_filter
                        , 0 AS does_meet_name_filter
                        , 0 AS does_meet_email_filter
                    FROM User_Auth0_Id_Filter USER_AUTH0_ID_FILTER
                    UNION
                    SELECT 
                            USER_NAME_FILTER.id_user 
                        , 0 AS does_meet_id_filter
                        , 0 AS does_meet_auth0_id_filter
                        , 1 AS does_meet_name_filter
                        , 0 AS does_meet_email_filter
                    FROM User_Name_Filter USER_NAME_FILTER
                    UNION
                    SELECT 
                            USER_EMAIL_FILTER.id_user 
                        , 0 AS does_meet_id_filter
                        , 0 AS does_meet_auth0_id_filter
                        , 0 AS does_meet_name_filter
                        , 1 AS does_meet_email_filter
                    FROM User_Email_Filter USER_EMAIL_FILTER
                ) USER_COMBINED
                GROUP BY USER_COMBINED.id_user
            )
        SELECT 
              USER.id_user -- id_user

            , v_id_permission_required -- id_permission_required
            , v_priority_access_level_required -- priority_access_level_required
            , IFNULL(USER.is_super_user, 0) AS is_super_user

            , CASE WHEN 
                    (
                        v_has_filter_user_id = 0
                    AND v_has_filter_user_auth0_id = 0
                )
                OR  IFNULL(USER_FILTERS.does_meet_id_filter, 0) = 1
                OR  IFNULL(USER_FILTERS.does_meet_auth0_id_filter, 0) = 1
            THEN 1 ELSE 0 END AS does_meet_id_filters
            , CASE WHEN 
                    (
                        v_has_filter_user_name = 0
                    AND v_has_filter_user_email = 0
                )
                OR  IFNULL(USER_FILTERS.does_meet_name_filter, 0) = 1
                OR  IFNULL(USER_FILTERS.does_meet_email_filter, 0) = 1
            THEN 1 ELSE 0 END AS does_meet_non_id_filters
        FROM fetchmetrics.DOG_User USER
        LEFT JOIN User_Filters USER_FILTERS ON USER.id_user = USER_FILTERS.id_user
        WHERE 
            (
                    a_get_all_user = 1
                OR  (
                        v_has_filter_user_id = 1
                    AND USER_FILTERS.does_meet_id_filter = 1
                )
                OR  (
                        v_has_filter_user_auth0_id = 1
                    AND USER_FILTERS.does_meet_auth0_id_filter = 1
                )
                OR  (
                        v_has_filter_user_name = 1
                    AND USER_FILTERS.does_meet_name_filter = 1
                )
                OR  (
                        v_has_filter_user_email = 1
                    AND USER_FILTERS.does_meet_email_filter = 1
                )
            )
            AND (
                    a_get_inactive_user = 1
                OR  USER.active = 1
            )
        ;
	END IF;
    
    DELETE FROM tmp_Split_Id_Calc_User_Access;
    DELETE FROM tmp_Split_Auth0_Id_Calc_User_Access;
    DELETE FROM tmp_Split_Name_Calc_User_Access;
    DELETE FROM tmp_Split_Email_Calc_User_Access;

    IF a_debug = 1 THEN
        SELECT 'After get Users';
        SELECT * FROM tmp_Calc_User_Access_Calc_User_Access;
    END IF;
    
    -- Filter records
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_User_Access t_ERROR INNER JOIN fetchmetrics.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
        DELETE t_CALC_USER_ACCESS
        FROM tmp_Calc_User_Access_Calc_User_Access t_CALC_USER_ACCESS
        /*
        LEFT JOIN fetchmetrics.DOG_User_Company_Link USER_COMPANY_LINK ON t_CALC_USER_ACCESS.id_user = USER_COMPANY_LINK.id_user
        LEFT JOIN tmp_Company_Calc_User_Access t_COMPANY ON t_COMPANY.id_company
        */
        WHERE
                (
                    a_require_all_id_search_filters_met = 1
                AND t_CALC_USER_ACCESS.does_meet_id_filters = 0
            )
            OR  (
                    a_require_all_non_id_search_filters_met = 1
                AND t_CALC_USER_ACCESS.does_meet_non_id_filters = 0
            )
            OR  (
                a_require_any_id_search_filters_met = 1
                AND t_CALC_USER_ACCESS.does_meet_id_filters = 0
            )
            OR  (
                a_require_any_non_id_search_filters_met = 1
                AND t_CALC_USER_ACCESS.does_meet_non_id_filters = 0
            )
        ;
    END IF;

    IF a_debug = 1 THEN
        SELECT 'After filter Users';
        SELECT * FROM tmp_Calc_User_Access_Calc_User_Access;
    END IF;
    
    -- Calculated fields
    -- Priority Access Level User
    WITH User_Access_Level AS (
        SELECT
              USER.id_user 
            , MIN(IFNULL(ACCESS_LEVEL.priority, v_priority_access_level_none)) AS priority_access_level
        FROM fetchmetrics.DOG_User USER -- tmp_Calc_User_Access_Calc_User_Access t_CALC_USER_ACCESS
        LEFT JOIN fetchmetrics.DOG_User_Role_Link USER_ROLE_LINK
            ON  USER.id_user = USER_ROLE_LINK.id_user
            AND USER_ROLE_LINK.active = 1
        LEFT JOIN fetchmetrics.DOG_Role_Permission_Link ROLE_PERMISSION_LINK
            ON  USER_ROLE_LINK.id_role = ROLE_PERMISSION_LINK.id_role
            AND ROLE_PERMISSION_LINK.active = 1
        LEFT JOIN fetchmetrics.DOG_Access_Level ACCESS_LEVEL
            ON  ROLE_PERMISSION_LINK.id_access_level = ACCESS_LEVEL.id_access_level
            AND ACCESS_LEVEL.active = 1
        GROUP BY USER.id_user
    )
	UPDATE tmp_Calc_User_Access_Calc_User_Access t_CALC_USER_ACCESS
    INNER JOIN User_Access_Level USER_ACCESS_LEVEL ON t_CALC_USER_ACCESS.id_user = USER_ACCESS_LEVEL.id_user
	SET
		  t_CALC_USER_ACCESS.priority_access_level_user = USER_ACCESS_LEVEL.priority_access_level
        , t_CALC_USER_ACCESS.has_access = CASE WHEN USER_ACCESS_LEVEL.priority_access_level <= v_priority_access_level_required THEN 1 ELSE 0 END
	;
    
    -- Has access
	UPDATE tmp_Calc_User_Access_Calc_User_Access t_CALC_USER_ACCESS
	SET
          t_CALC_USER_ACCESS.can_view = CASE WHEN 
                t_CALC_USER_ACCESS.is_super_user = 1 
            OR (
                    t_CALC_USER_ACCESS.priority_access_level_user <= v_priority_access_level_view 
                AND t_CALC_USER_ACCESS.has_access = 1
            )
        THEN 1 ELSE 0 END
		, t_CALC_USER_ACCESS.can_edit = CASE WHEN 
                t_CALC_USER_ACCESS.is_super_user = 1 
            OR  (
                    t_CALC_USER_ACCESS.priority_access_level_user <= v_priority_access_level_edit 
                AND t_CALC_USER_ACCESS.has_access = 1
            ) 
        THEN 1 ELSE 0 END
		, t_CALC_USER_ACCESS.can_admin = CASE WHEN 
                t_CALC_USER_ACCESS.is_super_user = 1 
            OR  (
                    t_CALC_USER_ACCESS.priority_access_level_user <= v_priority_access_level_admin 
                AND t_CALC_USER_ACCESS.has_access = 1
            ) 
        THEN 1 ELSE 0 END
	;
    
    -- Export data to staging table
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_User_Access) THEN
        START TRANSACTION;
			INSERT INTO fetchmetrics.DOG_Calc_User_Access_Temp (
				  guid
				, id_user
				, id_permission_required
				, priority_access_level_required
				, is_super_user
				, priority_access_level_user
                , has_access
				, can_view
				, can_edit
				, can_admin

                , does_meet_id_filters
                , does_meet_non_id_filters
			)
			SELECT
				  a_guid
				, t_CALC_USER_ACCESS.id_user
				, t_CALC_USER_ACCESS.id_permission_required
				, t_CALC_USER_ACCESS.priority_access_level_required
				, t_CALC_USER_ACCESS.is_super_user
				, t_CALC_USER_ACCESS.priority_access_level_user
                , t_CALC_USER_ACCESS.has_access
				, t_CALC_USER_ACCESS.can_view
				, t_CALC_USER_ACCESS.can_edit
				, t_CALC_USER_ACCESS.can_admin

				, t_CALC_USER_ACCESS.does_meet_id_filters
				, t_CALC_USER_ACCESS.does_meet_non_id_filters
			FROM tmp_Calc_User_Access_Calc_User_Access t_CALC_USER_ACCESS
			;
		COMMIT;
    END IF;
    
    -- Errors
    IF a_show_errors = 1 THEN
        SELECT 
            t_ERROR.id_error
            , t_ERROR.id_type
            , t_ERROR.code
            , ERROR_TYPE.name
            , ERROR_TYPE.description
            , ERROR_TYPE.is_breaking_error
            , ERROR_TYPE.background_colour
            , ERROR_TYPE.text_colour
            , t_ERROR.msg
        FROM tmp_Msg_Error_Calc_User_Access t_ERROR
        INNER JOIN fetchmetrics.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
        ;
    END IF;
    
    IF a_debug = 1 THEN
        SELECT 'End';
		SELECT * FROM tmp_Msg_Error_Calc_User_Access;
		SELECT * FROM tmp_Calc_User_Access_Calc_User_Access;
		SELECT * FROM fetchmetrics.DOG_Calc_User_Access_Temp WHERE GUID = a_guid;
		CALL fetchmetrics.p_dog_clear_calc_user_access ( a_guid, a_debug );
    END IF;
    
    -- Clean up
	DROP TABLE IF EXISTS tmp_Split_Email_Calc_User_Access;
	DROP TABLE IF EXISTS tmp_Split_Name_Calc_User_Access;
	DROP TABLE IF EXISTS tmp_Split_Auth0_Id_Calc_User_Access;
	DROP TABLE IF EXISTS tmp_Split_Id_Calc_User_Access;
	DROP TABLE IF EXISTS tmp_Msg_Error_Calc_User_Access;
	DROP TABLE IF EXISTS tmp_Calc_User_Access_Calc_User_Access;
    
    IF a_debug = 1 THEN
        CALL fetchmetrics.p_debug_timing_reporting( v_time_start );
    END IF;
END //
DELIMITER ;


/*
	  IN a_guid BINARY(36)
    , IN a_get_all_user BIT
    , IN a_get_inactive_user BIT
	, IN a_ids_user TEXT
    , IN a_auth0_ids_user TEXT
    , IN a_names_user TEXT
    , IN a_emails_user TEXT
    , IN a_require_all_id_search_filters_met BIT
    , IN a_require_any_id_search_filters_met BIT
    , IN a_require_all_non_id_search_filters_met BIT
    , IN a_require_any_non_id_search_filters_met BIT
    , IN a_ids_permission_required TEXT
    , IN a_ids_access_level_required TEXT
    , IN a_show_errors BIT
    , IN a_debug BIT

        
-- SELECT * FROM fetchmetrics.DOG_Calc_User_Access_Temp;
SELECT * FROM fetchmetrics.DOG_Calc_User_Access_Temp WHERE GUID = 'chips                               ';
CALL fetchmetrics.p_dog_clear_calc_user_access ( 'chips                               ', 0 );
-- SELECT * FROM fetchmetrics.DOG_Calc_User_Access_Temp;
DROP TABLE IF EXISTS tmp_Msg_Error_Calc_User_Access;

DELETE FROM fetchmetrics.DOG_Calc_User_Access_Temp;

CALL fetchmetrics.p_dog_calc_user_access(
      'chips                               '-- a_guid
    , 0                                     -- a_get_all_user
    , 0                                     -- a_get_inactive_user
    , '1'                                     -- a_ids_user
    , ''                                     -- a_auth0_ids_user
    , ''                                     -- a_names_user
    , ''                                     -- a_emails_user
    , 1                                     -- a_require_all_id_search_filters_met
    , 1                                     -- a_require_any_id_search_filters_met
    , 0                                     -- a_require_all_non_id_search_filters_met
    , 1                                     -- a_require_any_non_id_search_filters_met
    , '8'                                   -- a_ids_permission_required
    , '1'                                   -- a_ids_access_level_required
    , 1                                     -- a_show_errors
    , 0                                     -- a_debug
);
SELECT * FROM fetchmetrics.DOG_Calc_User_Access_Temp WHERE GUID = 'chips                               ';
CALL fetchmetrics.p_dog_clear_calc_user_access ( 'chips                               ', 0 );
DROP TABLE IF EXISTS tmp_Msg_Error_Calc_User_Access;


*/
