
USE partsltd_prod;

DROP TRIGGER IF EXISTS partsltd_prod.before_insert_PH_Contact_Form;
DROP TRIGGER IF EXISTS partsltd_prod.before_update_PH_Contact_Form;

DELIMITER //
CREATE TRIGGER partsltd_prod.before_insert_PH_Contact_Form
BEFORE INSERT ON partsltd_prod.PH_Contact_Form
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER partsltd_prod.before_update_PH_Contact_Form
BEFORE UPDATE ON partsltd_prod.PH_Contact_Form
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO partsltd_prod.PH_Contact_Form_Audit (
		id_contact_form,
        name_field,
        value_prev,
        value_new,
        id_change_set
    )
    -- Changed email
	SELECT NEW.id_contact_form, 'email', OLD.email, NEW.email, NEW.id_change_set
		WHERE NOT OLD.email <=> NEW.email
	UNION
    -- Changed name_contact
	SELECT NEW.id_contact_form, 'name_contact', OLD.name_contact, NEW.name_contact, NEW.id_change_set
		WHERE NOT OLD.name_contact <=> NEW.name_contact
	UNION
    -- Changed name_company
	SELECT NEW.id_contact_form, 'name_company', OLD.name_company, NEW.name_company, NEW.id_change_set
		WHERE NOT OLD.name_company <=> NEW.name_company
	UNION
	-- Changed message
	SELECT NEW.id_contact_form, 'message', OLD.message, NEW.message, NEW.id_change_set
		WHERE NOT OLD.message <=> NEW.message
	UNION
	-- Changed receive_marketing_communications
	SELECT NEW.id_contact_form, 'receive_marketing_communications', CONVERT(CONVERT(OLD.receive_marketing_communications, SIGNED), CHAR), CONVERT(CONVERT(NEW.receive_marketing_communications, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.receive_marketing_communications <=> NEW.receive_marketing_communications)
	UNION
	-- Changed active
	SELECT NEW.id_contact_form, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;
