DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clientCreate`(
	vFirstname VARCHAR(50),
    vSurnames VARCHAR(50), 
    vFi VARCHAR(9), 
    vAddress TEXT, 
    vPostcode CHAR(5),
    vCity VARCHAR(25),
    vProvinceFk SMALLINT(5),
    vCompanyFk SMALLINT(5),
    vPhone VARCHAR(11),
    vEmail VARCHAR(255),
    vUserFk INT)
BEGIN
/**
 * Create new client
 *
 */
    DECLARE vPayMethodFk INT DEFAULT 4;
    DECLARE vDueDay INT DEFAULT 5;
    DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00;
    DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1;
	DECLARE vHasCoreVnl BOOLEAN DEFAULT TRUE;
    DECLARE vMandateTypeFk INT DEFAULT 2;
    
	INSERT INTO `client` (
			id,
			name,
			street,
			fi,
			phone,
			email,
			provinceFk,
			city,
			postcode,
			socialName,
			payMethodFk,
			dueDay,
			credit,
			isTaxDataChecked,
			hasCoreVnl,
			isEqualizated)
		VALUES (
			vUserFk,
			CONCAT(vFirstname, ' ', vSurnames),
			vAddress,
			TRIM(vFi),
			vPhone,
			vEmail,
			vProvinceFk,
			vCity,
			vPostcode,
			CONCAT(vSurnames, ' ', vFirstname), 
			vPayMethodFk,
			vDueDay,
			vDefaultCredit,
			vIsTaxDataChecked,
			vHasCoreVnl,
			FALSE
		) ON duplicate key update  
            payMethodFk = vPayMethodFk,
			dueDay = vDueDay,
			credit = vDefaultCredit,
			isTaxDataChecked = vIsTaxDataChecked,
			hasCoreVnl = vHasCoreVnl,
            isActive = TRUE;
	
    IF (SELECT COUNT(*) FROM mandate WHERE clientFk = vUserFk AND companyFk = vCompanyFk AND mandateTypeFk = vMandateTypeFk) = 0 THEN
		INSERT INTO mandate (clientFk, companyFk, mandateTypeFk)
			VALUES (vUserFk, vCompanyFk, vMandateTypeFk);
	END IF;
END$$
DELIMITER ;