
USE demo;

DROP PROCEDURE IF EXISTS demo.p_ph_save_contact_form;

DELIMITER //
CREATE PROCEDURE demo.p_ph_save_contact_form (
    IN a_comment VARCHAR(500),
	IN a_guid BINARY(36),
    IN a_id_user INT,
    IN a_debug BIT
)
BEGIN
	DECLARE v_code_type_error_bad_data VARCHAR(100);
    DECLARE v_id_access_level_view INT;
    DECLARE v_id_access_level_edit INT;
    DECLARE v_id_change_set INT;
    DECLARE v_id_permission_contact_form_admin INT;
    DECLARE v_id_permission_contact_form_new INT;
    DECLARE v_id_type_error_bad_data INT;
    DECLARE v_time_start TIMESTAMP(6);
    DECLARE v_can_admin BIT;
    DECLARE v_can_create BIT;
    
    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 (
			  display_order INT NOT NULL PRIMARY KEY AUTO_INCREMENT
			, id_type INT NULL
			, code VARCHAR(50) NOT NULL
			, msg VARCHAR(4000) NOT NULL
		);

        INSERT INTO tmp_Msg_Error (
			  id_type
            , code
            , msg
		)
        SELECT 
			  MET.id_type
            , @errno
            , @text
		FROM demo.CORE_Msg_Error_Type MET
        WHERE MET.code = 'MYSQL_ERROR'
		;
        
        SELECT *
        FROM tmp_Msg_Error;
		DROP TABLE IF EXISTS tmp_Msg_Error
        ;
    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 demo.CORE_Msg_Error_Type WHERE code = v_code_type_error_bad_data LIMIT 1);
    SET v_id_permission_contact_form_admin := (SELECT id_permission FROM demo.DOG_Permission P WHERE P.code = 'CONTACT_FORM_ADMIN' LIMIT 1);
    SET v_id_permission_contact_form_new := (SELECT id_permission FROM demo.DOG_Permission P WHERE P.code = 'CONTACT_FORM_CREATE' LIMIT 1);
    
    CALL demo.p_core_validate_guid ( a_guid );
    
    DROP TABLE IF EXISTS tmp_Contact_Form;
    
    CREATE TEMPORARY TABLE tmp_Contact_Form (
		  id_contact_form INT NOT NULL
        , email VARCHAR(255) NOT NULL
        , name_contact VARCHAR(255) NOT NULL
        , name_company VARCHAR(255) NOT NULL
        , message TEXT NOT NULL
        , receive_marketing_communications BIT NOT NULL
        , active BIT NOT NULL
        , name_error VARCHAR(255)
        , is_new BIT NOT NULL
    );
        
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error (
		  display_order INT NOT NULL PRIMARY KEY AUTO_INCREMENT
		, id_type INT NULL
        , code VARCHAR(50) NOT NULL
        , msg VARCHAR(4000) NOT NULL
	);
        
    
    -- Get data from Temp table
    INSERT INTO tmp_Contact_Form (
		  id_contact_form
        , email
        , name_contact
        , name_company
        , message
        , receive_marketing_communications
        , active
        , is_new
	)
    SELECT 
		  CF_T.id_contact_form AS id_contact_form
        , IFNULL(CF_T.email, CF.email) AS code
        , IFNULL(CF_T.name_contact, CF.name_contact) AS name_contact
        , IFNULL(CF_T.name_company, CF.name_company) AS name_company
        , IFNULL(CF_T.message, CF.message) AS message
        , COALESCE(CF_T.receive_marketing_communications, CF.receive_marketing_communications, 0) AS receive_marketing_communications
        , COALESCE(CF_T.active, CF.active, 1) AS active
        , CASE WHEN IFNULL(CF_T.id_contact_form, 0) < 1 THEN 1 ELSE 0 END AS is_new
	FROM demo.PH_Contact_Form_Temp CF_T
    LEFT JOIN demo.PH_Contact_Form CF ON CF_T.id_contact_form = CF.id_contact_form
    WHERE CF_T.guid = a_guid
    ;

    UPDATE tmp_Contact_Form t_CF
    SET name_error = COALESCE(t_CF.email, t_CF.name_company, t_CF.name_contact, t_CF.message, '(No Contact Form)')
    ;
    
    -- Validation
    -- Missing mandatory fields
    -- email
    IF EXISTS (SELECT * FROM tmp_Contact_Form t_CF WHERE ISNULL(t_CF.email) LIMIT 1) THEN
		INSERT INTO tmp_Msg_Error (
			  id_type
			, code
			, msg
		)
		SELECT
			  v_id_type_error_bad_data
			, v_code_type_error_bad_data
			, CONCAT('The following Contact Form(s) do not have an Email: ', GROUP_CONCAT(t_CF.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Contact_Form t_CF
		WHERE ISNULL(t_CF.email)
		;
    END IF;
    -- name_contact
    IF EXISTS (SELECT * FROM tmp_Contact_Form t_CF WHERE ISNULL(t_CF.name_contact) LIMIT 1) THEN
		INSERT INTO tmp_Msg_Error (
			  id_type
			, code
			, msg
		)
		SELECT
			  v_id_type_error_bad_data
			, v_code_type_error_bad_data
			, CONCAT('The following Contact Form(s) do not have a Contact Name: ', GROUP_CONCAT(t_CF.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Contact_Form t_CF
		WHERE ISNULL(t_CF.name_contact)
		;
    END IF;
    -- name_company
    IF EXISTS (SELECT * FROM tmp_Contact_Form t_CF WHERE ISNULL(t_CF.name_company) LIMIT 1) THEN
		INSERT INTO tmp_Msg_Error (
			  id_type
			, code
			, msg
		)
		SELECT
			  v_id_type_error_bad_data
			, v_code_type_error_bad_data
			, CONCAT('The following Contact Form(s) do not have a Company Name: ', GROUP_CONCAT(t_CF.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Contact_Form t_CF
		WHERE ISNULL(t_CF.name)
		;
    END IF;
    -- message
    IF EXISTS (SELECT * FROM tmp_Contact_Form t_CF WHERE ISNULL(t_CF.message) LIMIT 1) THEN
		INSERT INTO tmp_Msg_Error (
			  id_type
			, code
			, msg
		)
		SELECT
			  v_id_type_error_bad_data
			, v_code_type_error_bad_data
			, CONCAT('The following Contact Form(s) do not have a Message: ', GROUP_CONCAT(t_CF.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Contact_Form t_CF
		WHERE ISNULL(t_CF.message)
		;
    END IF;
    
    -- Permissions
    IF a_debug = 1 THEN
		SELECT 
			  a_guid
            , 0 -- get_all_user
            , 0 -- get_inactive_user
            , a_id_user -- 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
            , 0 -- a_require_any_non_id_search_filters_met
            , v_id_permission_contact_form_admin -- ids_permission
            , v_id_access_level_view -- ids_access_level
            , 0 -- a_show_errors
			, 0 -- a_debug
        ;
    END IF;
    
	CALL demo.p_dog_calc_user(
          a_guid
        , 0 -- get_all_user
        , 0 -- get_inactive_user
        , a_id_user -- 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
        , 0 -- a_require_any_non_id_search_filters_met
        , v_id_permission_contact_form_admin -- ids_permission
        , v_id_access_level_view -- ids_access_level
        , 0 -- a_show_errors
        , 0 -- a_debug
    );
	
    SELECT
          IFNULL(CALC_USER_T.has_access, 0)
    INTO
          v_can_admin
    FROM demo.DOG_Calc_User_Temp CALC_USER_T
    WHERE CALC_USER_T.GUID = a_guid
    LIMIT 1
    ;
    
    IF a_debug = 1 THEN
        SELECT v_can_admin;
        SELECT COUNT(*) AS Count_Errors FROM tmp_Msg_Error t_ERROR;
        SELECT * FROM tmp_Msg_Error t_ERROR;
    END IF;
	
	CALL demo.p_dog_clear_calc_user(
		  a_guid
        , 0 -- a_debug
	);


    IF a_debug = 1 THEN
		SELECT 
			  a_guid
            , 0 -- get_all_user
            , 0 -- get_inactive_user
            , a_id_user -- 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
            , 0 -- a_require_any_non_id_search_filters_met
            , v_id_permission_contact_form_new -- ids_permission
            , v_id_access_level_view -- ids_access_level
            , 0 -- a_show_errors
			, 0 -- a_debug
        ;
    END IF;
    
	CALL demo.p_dog_calc_user(
          a_guid
        , 0 -- get_all_user
        , 0 -- get_inactive_user
        , a_id_user -- 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
        , 0 -- a_require_any_non_id_search_filters_met
        , v_id_permission_contact_form_new -- ids_permission
        , v_id_access_level_view -- ids_access_level
        , 0 -- a_show_errors
        , 0 -- a_debug
    );
	
    SELECT
          IFNULL(CALC_USER_T.has_access, 0)
    INTO
          v_can_create
    FROM demo.DOG_Calc_User_Temp CALC_USER_T
    WHERE CALC_USER_T.GUID = a_guid
    LIMIT 1
    ;
    
    IF a_debug = 1 THEN
        SELECT v_can_create;
        SELECT COUNT(*) AS Count_Errors FROM tmp_Msg_Error t_ERROR;
        SELECT * FROM tmp_Msg_Error t_ERROR;
    END IF;
	
	CALL demo.p_dog_clear_calc_user(
		  a_guid
        , 0 -- a_debug
	);
    
    IF (v_can_admin = 0 AND EXISTS(SELECT * FROM tmp_Contact_Form WHERE is_new = 0)) THEN
		DELETE t_ME
        FROM tmp_Msg_Error t_ME
        WHERE t_ME.id_type <> v_id_type_error_no_permission
        ;
		INSERT INTO tmp_Msg_Error (
			  id_type
			, code
			, msg
		)
		VALUES (
			  v_id_type_error_no_permission
			, v_code_type_error_no_permission
			, 'You do not have permission to admin Contact Forms.'
		)
        ;
    END IF;
    
    IF EXISTS (SELECT * FROM tmp_Msg_Error LIMIT 1) THEN
    	IF a_debug = 1 THEN
	    	SELECT * from tmp_Contact_Form;
	    END IF;

        DELETE FROM tmp_Contact_Form;
    END IF;

    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error LIMIT 1) THEN
		START TRANSACTION;
		
			INSERT INTO demo.PH_Contact_Form_Change_Set ( 
                  comment
                , id_user_updated_last_by
                , updated_last_on
            )
			VALUES ( 
                  a_comment
                , a_id_user
                , v_time_start
            )
			;
			
			SET v_id_change_set := LAST_INSERT_ID();
			
			UPDATE demo.PH_Contact_Form CF
			INNER JOIN tmp_Contact_Form t_CF 
				ON  CF.id_contact_form = t_CF.id_contact_form
				AND t_CF.is_new = 0
			SET 
				  CF.email = t_CF.email
				, CF.name_contact = t_CF.name_contact
				, CF.name_company = t_CF.name_company
				, CF.message = t_CF.message
                , CF.receive_marketing_communications = t_CF.receive_marketing_communications
				, CF.active = t_CF.active
				, CF.id_change_set = v_id_change_set
			;
			
			INSERT INTO demo.PH_Contact_Form (
				  email
				, name_contact
				, name_company
				, message
                , receive_marketing_communications
				, active
				, id_user_created_by
				, created_on
			)
			SELECT
				  t_CF.email                            AS email
				, t_CF.name_contact                     AS name_contact
				, t_CF.name_company                     AS name_company
				, t_CF.message                          AS message
                , t_CF.receive_marketing_communications AS receive_marketing_communications
				, t_CF.active                           AS active
				, a_id_user                             AS created_by
				, v_time_start                          AS created_on
			FROM tmp_Contact_Form t_CF
			WHERE 
				    t_CF.is_new = 1
				AND t_CF.active = 1
			;
			
		COMMIT;
    END IF;
	
	START TRANSACTION;

		DELETE FROM demo.PH_Contact_Form_Temp
		WHERE GUID = a_guid
        ;
		
	COMMIT;
    
    -- Errors
    SELECT *
    FROM tmp_Msg_Error t_ME
	INNER JOIN demo.CORE_Msg_Error_Type MET ON t_ME.id_type = MET.id_type
	;
    
	IF a_debug = 1 THEN
		SELECT * from tmp_Contact_Form;
	END IF;

    DROP TEMPORARY TABLE tmp_Contact_Form;
    DROP TEMPORARY TABLE tmp_Msg_Error;
    
	IF a_debug = 1 THEN
		CALL demo.p_core_debug_timing_reporting ( v_time_start );
	END IF;
END //
DELIMITER ;


select 
	*
    -- COUNT(*)
-- delete
from demo.PH_Contact_Form_Temp
;


CALL demo.p_ph_save_contact_form (
	'nipples'
    , (SELECT GUID FROM demo.PH_Contact_Form_Temp ORDER BY id_temp DESC LIMIT 1)
    , 1
    , 1
);

select 
	*
    -- COUNT(*)
-- delete
from demo.PH_Contact_Form_Temp
;


