-- Table structure for table `shippingGroup`
--

CREATE TABLE `shippingGroup` (
  `SGRPNAME` varchar(50) COLLATE utf8mb3_unicode_ci NOT NULL,
  `SGRPPIECES` int NOT NULL,
  `SGRPBOXTYPE` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL,
  `SGRPWEIGHTPIECE` decimal(19,4) NOT NULL,
  PRIMARY KEY (`SGRPNAME`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;

--
-- Dumping data for table `shippingGroup`
--


--
-- Table structure for table `shippingGroupItems`
--

CREATE TABLE `shippingGroupItems` (
  `SGRPNAME` varchar(50) COLLATE utf8mb3_unicode_ci NOT NULL,
  `ITEMID` int NOT NULL,
  PRIMARY KEY (`ITEMID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;

--
-- Dumping data for table `shippingGroupItems`
--


--
-- Table structure for table `subcategories`
--

CREATE TABLE `subcategories` (
  `SUBCATID` int NOT NULL AUTO_INCREMENT,
  `CATID` int NOT NULL,
  `NAME` varchar(50) COLLATE utf8mb3_unicode_ci NOT NULL,
  `DESCRIPTION` varchar(200) COLLATE utf8mb3_unicode_ci NOT NULL,
  `PARENTSUBCATID` int NOT NULL DEFAULT '-1',
  `ICONURL` varchar(200) COLLATE utf8mb3_unicode_ci DEFAULT '',
  `USERLEVEL` int NOT NULL DEFAULT '0',
  PRIMARY KEY (`SUBCATID`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;

--
-- Dumping data for table `subcategories`
--

INSERT INTO `subcategories` VALUES (1,2,'Pafco Envelopes','Pafco Envelopes',-1,'',0),(2,2,'Pembridge Envelopes','Pembridge Envelopes',-1,'',0),(3,3,'Pafco Letterheads','Pafco Letterheads',-1,'',0),(4,3,'Pembridge Letterheads','Pembridge Letterhead',-1,'',0),(5,1,'English','Policy Booklets',-1,'',0),(6,1,'French','French Policy Booklets',-1,'',0),(7,3,'Letters','Letters and Notices',-1,'',0),(11,4,'Folder','Folder',-1,'',0);

--
-- Table structure for table `taxes`
--

CREATE TABLE `taxes` (
  `TAXCODE` varchar(6) COLLATE utf8mb3_unicode_ci NOT NULL,
  `TAXGROUPNAME` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL,
  `TAXNAME1` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT '',
  `TAXNAME2` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT '',
  `TAXNAME3` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT '',
  `TAXNAME4` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT '',
  `TAXNAME5` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT '',
  `TAXRATE1` decimal(19,5) NOT NULL DEFAULT '0.00000',
  `TAXRATE2` decimal(19,5) NOT NULL DEFAULT '0.00000',
  `TAXRATE3` decimal(19,5) NOT NULL DEFAULT '0.00000',
  `TAXRATE4` decimal(19,5) NOT NULL DEFAULT '0.00000',
  `TAXRATE5` decimal(19,5) NOT NULL DEFAULT '0.00000',
  PRIMARY KEY (`TAXCODE`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;

--
-- Dumping data for table `taxes`
--

INSERT INTO `taxes` VALUES ('AB','AB','GST','','','','',0.05000,0.00000,0.00000,0.00000,0.00000),('BC','BC','GST','PST','','','',0.05000,0.07000,0.00000,0.00000,0.00000),('MB','MB','GST','PST','','','',0.05000,0.07000,0.00000,0.00000,0.00000),('NB','NB','HST','','','','',0.15000,0.00000,0.00000,0.00000,0.00000),('NL','NL','HST','','','','',0.15000,0.00000,0.00000,0.00000,0.00000),('NS','NS','HST','','','','',0.14000,0.00000,0.00000,0.00000,0.00000),('NT','NT','GST','','','','',0.05000,0.00000,0.00000,0.00000,0.00000),('NU','NU','GST','','','','',0.05000,0.00000,0.00000,0.00000,0.00000),('ON','ON','HST','','','','',0.13000,0.00000,0.00000,0.00000,0.00000),('PE','PE','HST','','','','',0.15000,0.00000,0.00000,0.00000,0.00000),('QC','QC','GST','QST','','','',0.05000,0.09975,0.00000,0.00000,0.00000),('SK','SK','GST','PST','','','',0.05000,0.06000,0.00000,0.00000,0.00000),('YT','YT','GST','','','','',0.05000,0.00000,0.00000,0.00000,0.00000);

--
-- Table structure for table `ticketAttachment`
--

CREATE TABLE `ticketAttachment` (
  `ID` int NOT NULL AUTO_INCREMENT,
  `TICKETID` int DEFAULT NULL,
  `MESSAGEID` int DEFAULT NULL,
  `STOREFILENAME` varchar(200) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
  `ORIGFILENAME` varchar(200) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;

--
-- Dumping data for table `ticketAttachment`
--


--
-- Table structure for table `ticketDetail`
--

CREATE TABLE `ticketDetail` (
  `MESSAGEID` int NOT NULL AUTO_INCREMENT,
  `TICKETID` int NOT NULL,
  `DATEENTERED` datetime NOT NULL,
  `ENTEREDBY` varchar(50) COLLATE utf8mb3_unicode_ci NOT NULL,
  `CLIENTMESSAGE` int NOT NULL,
  `MESSAGE` varchar(1000) COLLATE utf8mb3_unicode_ci NOT NULL,
  PRIMARY KEY (`MESSAGEID`,`TICKETID`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;

--
-- Dumping data for table `ticketDetail`
--

INSERT INTO `ticketDetail` VALUES (1,1,'2016-03-14 23:54:53','dlabbe',1,'Ignore this, I\'m testing out the support ticket section.'),(2,1,'2016-03-15 00:01:16','dlabbe',0,'Testing email reply, please ignore. '),(3,2,'2016-03-16 22:25:45','patrick',1,'Hi,\n\nI would like to test the support system, please reply so I can see how this works.  BTW, it looks great.\n\nWhat does it mean by overwrite entered by means?'),(4,2,'2016-03-21 22:53:51','dlabbe',0,'Hi Patrick, \n\nOverwrite entered by only appears when an administrator entered a new ticket. It allows them to enter a ticket as other person, in case a support issue comes in by phone or email and they want to track it in the ticket system.\n\nDan'),(5,2,'2016-03-22 13:34:09','patrick',0,'After a ticket is closed what happens to the history?'),(6,3,'2016-04-01 16:16:49','Menei',1,'What\'s up???'),(7,3,'2016-04-01 16:17:29','patrick',0,'Everything is good, what\'s up with you??');

--
-- Table structure for table `ticketHeader`
--

CREATE TABLE `ticketHeader` (
  `ID` int NOT NULL AUTO_INCREMENT,
  `ENTEREDBY` varchar(50) COLLATE utf8mb3_unicode_ci NOT NULL,
  `DATEENTERED` datetime NOT NULL,
  `STATUS` int NOT NULL,
  `TITLE` varchar(1000) COLLATE utf8mb3_unicode_ci NOT NULL,
  `DATECLOSED` datetime DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;

--
-- Dumping data for table `ticketHeader`
--

INSERT INTO `ticketHeader` VALUES (1,'dlabbe','2016-03-14 23:54:53',0,'Test Ticket','2016-03-15 00:01:45'),(2,'patrick','2016-03-16 22:25:45',0,'Patrick Test the Support system','2024-12-18 19:44:34'),(3,'Menei','2016-04-01 16:16:49',0,'What\'s up??','2024-12-18 19:44:31');

--
-- Table structure for table `user`
--

CREATE TABLE `user` (
  `USERNAME` varchar(50) COLLATE utf8mb3_unicode_ci NOT NULL,
  `BRANCH` varchar(20) COLLATE utf8mb3_unicode_ci NOT NULL,
  `PASSWORD` varchar(50) COLLATE utf8mb3_unicode_ci NOT NULL,
  `PLAINPASSWORD` varchar(50) COLLATE utf8mb3_unicode_ci NOT NULL,
  `FIRSTNAME` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL,
  `LASTNAME` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL,
  `EMAIL` varchar(100) COLLATE utf8mb3_unicode_ci NOT NULL,
  `LANGUAGE` varchar(2) COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT 'EN',
  `USERLEVEL` int NOT NULL DEFAULT '0',
  `CREATEDDATE` datetime DEFAULT NULL,
  `MODIFIEDDATE` datetime DEFAULT NULL,
  `STATUS` int NOT NULL,
  `COMMENTS` varchar(1000) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`USERNAME`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;

--
-- Dumping data for table `user`
--

INSERT INTO `user` VALUES ('aguillermo','HO','*31EC1E82A5B4636896C2F9A95CF2247272B0A960','pbowes@27','Aris','Guillermo','aguillermo@allstate.ca','EN',10,'2009-10-26 00:00:00','2009-10-30 00:00:00',1,''),('atam','HO','*BE4533A05EB758E57C6B617DBE93947153613703','at822','Ada','Tam','ada.tam@pembridge.com','EN',10,'2009-10-26 00:00:00','2013-11-12 00:00:00',1,''),('brenda','Claims Mississauga','*266DE2D54DCC6C1F14EA84139AEA973F34C09C55','itlb26','Brenda','Oliveira','boliveira@assistplus.ca','EN',10,'2016-04-29 23:02:34','2016-04-29 23:02:34',1,''),('cheryl','Claims Markham','*54F5DD0FE3753A0E7EDD67C9C1DD34D25907040B','p2at3p','Cheryl','Campbell','ccampbell@assistplus.ca','EN',10,'2016-04-29 23:02:34','2016-04-29 23:02:34',1,''),('eceniti','HO','*C26722B24D52A6CE43916555DAA84857C7F1F35F','c7h3a','Elizabeth','Ceniti ','eceniti@allstate.ca','EN',10,'2012-08-27 00:00:00','2012-08-27 00:00:00',1,''),('eric','HO','*C5EC559C0EA7C49430B0006B94ACD3B9DD1D4F9D','E6359S','Eric','Sin','erics@cpfulfillment.com','EN',81,'2019-05-15 20:21:46','2021-04-15 13:48:23',1,''),('jen','HO','*1B971235F80D472237329258498BAF8F1D43BE0D','Hl5982','jen','Lor','jennifer@cpfulfillment.com','EN',81,'2022-04-22 12:45:41','2022-04-22 12:46:29',1,''),('joet','HO','*530EE1B8D9D0171195D8FCF1637CE9D5B25DA782','jt4980','Joe ','Tommasone','jtommasone@allstate.ca','EN',10,'2024-01-09 15:23:14','2024-01-09 15:23:18',1,''),('lmilkis','HO','*581A57A82CD9F598C262E7B0F966F7BDC68EBBD9','lm4597','Lori','Mikis','lmilkis@allstate.ca','EN',10,'2009-10-26 00:00:00','2009-10-30 00:00:00',1,''),('lynn','Claims Moncton','*E3F1F9EE7ABC4E612BD2DB9265611F232F37B158','t6vng6','Lynn','Coates','lcoates@assistpluc.ca','EN',10,'2016-04-29 23:02:34','2016-04-29 23:02:34',1,''),('marryanne','Claims Calgary','*7EE5299D9F07874FC7A923762A3B35296DCB69D8','f160lu','Mary Anne','Johnston','maryanne.johnston@assistplus.ca','EN',10,NULL,NULL,1,''),('mary','Claims Markham','*9ABF462CA47ED26D2AA9BC7A447296113D9388C7','q4ngzx','Mary','Lattion-Wells','mlattionwells@assistplus.ca','EN',10,'2016-04-29 23:02:34','2016-04-29 23:02:34',1,''),('Menei','HO','*257BF5AF615ACA5392D42DEAD63F7E06227C3A75','menei227','Menei','Ho','menei@creativepath.com','EN',9,'2011-08-23 00:00:00','2022-09-02 12:10:52',1,''),('miir','HO','*3B06CA329998DCF7B3AD9E850D9D3F120B0AC356','miir2280','Miranda','Lee','miranda@creativepath.com','EN',81,'2024-07-24 15:37:34','2024-07-24 15:37:51',1,''),('mike','Claims Mississauga','*2601C1BCC10E512110A9CAE97859B2D3A2F61A76','w2qogw','Mike','Brunski','mbrunski@assistplus.ca','EN',10,'2016-04-29 23:02:34','2016-04-29 23:02:34',1,''),('patrick','HO','*04AE7ABE88B8C7F153AD654C1410AFFC6072339B','cpdi905711','Patrick','Sinn','patrick@creativepath.com','EN',99,'2009-09-01 00:00:00','2021-04-15 14:00:10',1,''),('Peggy','HO','*A45967DAC55BE870539FA0BA1B8AF799AD65EBB8','momo73449','Peggy','Cheng','peggy@creativepath.com','EN',99,'2018-03-07 21:06:35','2024-05-27 13:43:35',1,''),('Randolph','HO','*7DF18F1557CD49DB0E02A9F83F00B0B76505D291','rc4646','Randolph','Crossley','rcrossley@assistplus.ca','EN',10,'2021-08-17 19:24:35','2021-08-17 19:25:32',1,''),('rbaldacchino','HO','*F9C586B6C7B889DAC54FBCB8461ED5983868F790','rb4442','Rachel','Baldacchino','rbaldacchino@allstate.ca','EN',10,'2011-01-10 00:00:00','2014-04-15 00:00:00',1,''),('Sam','HO','*48910925EF9C280FA11348D3968E9F9B2E98E539','sam8500','Sam','Stratigeas','sam@samstratigeas.ca','EN',99,'2022-04-18 14:39:26','2022-04-18 14:39:42',1,''),('savitri','HO','*2F5D27851400C846CF1CB2964C35D0FB33A57E0C','sp946','Savitri','Pamaya','spamayah@pembridge.com','EN',10,'2020-04-17 16:12:52','2020-04-17 16:14:53',1,''),('serafina','Claims Montreal','*540B3A9EE66F61F1075A7597310DE1E1118FBFF6','n9azj2','Serafina','Kondarinis','skondarinis@assistplus.ca','EN',10,'2016-04-29 23:02:34','2016-04-29 23:02:34',1,''),('sylvia','Claims Markham','*980555A1FF7B2167AA9D105E0DEB3C51461CCB05','w0wb06','Sylvia','Parrott','sparrott@allstate.ca','EN',10,'2016-04-29 23:02:34','2016-04-29 23:02:34',1,''),('teresa','Claims Calgary','*B19AA2348B76EDA0AEB3F673352FD3D8D7071EE2','hfwz5r','Teresa','Oliverio','toliverio@assistplus.ca','EN',10,'2016-04-29 23:02:34','2016-04-29 23:02:34',1,''),('tlangridge','HO','*6A10AFDBC734A2EF0DE65B4E7B87CB92826B9A6D','t2g4e','Tina    ','Langridge','tlangridge@pembridge.com  ','EN',10,'2012-08-27 00:00:00','2012-08-27 00:00:00',1,''),('winnie','HO','*C73E4236C7E560BC595364AE42A790AC5A9166A9','cpdi236','Winnie','Wu','winnie@creativepath.com','EN',81,'2021-12-17 12:20:47','2024-09-18 11:10:43',1,''),('zoeyc','HO','*C7C2E49F12068D26F3FB0709B11EBB4516B3BE98','zc5689','Zoey','C','zoeyc@cpfulfillment.com','EN',99,'2023-06-26 13:26:36','2023-06-26 13:26:54',1,'');

--
-- Dumping routines for database 'cpfulfillment_PrintOS_Pembridge'
--
/*!50003 DROP PROCEDURE IF EXISTS `AddDownloadLogEntry` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `AddDownloadLogEntry`(__USERNAME VARCHAR(50), __ITEMID INT)
BEGIN
	INSERT INTO 
		downloadLog
        (USERNAME,BRANCHCODE,ITEMID,LOGTIME)
	SELECT
		USERNAME,
        BRANCH,
        __ITEMID,
        CURRENT_TIMESTAMP
	FROM
		user
	WHERE
		USERNAME = __USERNAME;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `AddItemToCart` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `AddItemToCart`(__USERNAME VARCHAR(50), __ITEMID INT, __PROOF VARCHAR(200), __QTY INT, __ITEMOPTION VARCHAR(30), __ADDCOST DECIMAL)
BEGIN



SELECT @ORDERNUM := COUNT(*) FROM orderHeader WHERE USERNAME = __USERNAME AND ORDERSTATUS = 'CART';


SELECT @LOTPRICE := COUNT(*) FROM itemPricing WHERE ITEMID = __ITEMID AND QTY = __QTY AND ITEMOPTION = __ITEMOPTION;
SELECT @VARPRICE := COUNT(*) FROM itemPricing WHERE ITEMID = __ITEMID AND QTY = -1 AND ITEMOPTION = __ITEMOPTION;


IF @ORDERNUM = 0 THEN
 INSERT INTO
 orderHeader
 (USERNAME,ORDERDATE,ORDERMODIFIED,PONUMBER,SHIPCONTACTFIRSTNAME,SHIPCONTACTLASTNAME,SHIPCONTACTPHONE,SHIPCONTACTFAX,SHIPCONTACTEMAIL,
 SHIPNAME,SHIPADDRESS,SHIPADDRESS2,SHIPCITY,SHIPPROVINCE,SHIPCOUNTRY,SHIPPOSTAL,SHIPTAXGROUP,ORDERSTATUS,SHIPSTOREID,
 REQCONTACTFIRSTNAME,REQCONTACTLASTNAME,REQCONTACTPHONE,REQCONTACTFAX,
 REQNAME,REQADDRESS,REQADDRESS2,REQCITY,REQPROVINCE,REQCOUNTRY,REQPOSTAL)
 SELECT
 __USERNAME AS USERNAME ,
 CURRENT_TIMESTAMP AS ORDERDATE,
 CURRENT_TIMESTAMP AS ORDERMODIFIED,
 '' AS PONUMBER,
 USER.FIRSTNAME AS SHIPCONTACTFIRSTNAME,
 USER.LASTNAME AS SHIPCONTACTLASTNAME,
 BADDR.PHONE AS SHIPCONTACTPHONE,
 BADDR.FAX AS SHIPCONTACTFAX,
 USER.EMAIL AS SHIPCONTACTEMAIL,
 BINFO.NAME AS SHIPNAME,
 BADDR.ADDRESS AS SHIPADDRESS,
 BADDR.ADDRESS2 AS SHIPADDRESS2,
 BADDR.CITY AS SHIPCITY,
 BADDR.PROVINCE AS SHIPPROVINCE,
 BADDR.COUNTRY AS SHIPCOUNTRY,
 BADDR.POSTALCODE AS SHIPPOSTAL,
 BINFO.TAXGROUP AS SHIPTAXGROUP,
        'CART' AS ORDERSTATUS,
        BINFO.CODE AS SHIPSTOREID,
		USER.FIRSTNAME AS REQCONTACTFIRSTNAME,
        USER.LASTNAME AS REQCONTACTLASTNAME,
        BADDR.PHONE AS REQCONTACTPHONE,
        BADDR.FAX AS REQCONTACTFAX,
		BINFO.NAME AS REQNAME,
        BADDR.ADDRESS AS REQADDRESS,
        BADDR.ADDRESS2 AS REQADDRESS2,
        BADDR.CITY AS REQCITY,
        BADDR.PROVINCE AS REQPROVINCE,
        BADDR.COUNTRY AS REQCOUNTRY,
        BADDR.POSTALCODE AS REQPOSTAL        
	FROM
		user USER
	INNER JOIN
		branches BINFO ON 
			USER.BRANCH = BINFO.CODE
	INNER JOIN
		branchesAddresses BADDR ON 
			USER.BRANCH = BADDR.CODE 
	WHERE
		USER.USERNAME  = __USERNAME AND
        BADDR.ISMAIN = 1
    ;
END IF;


SELECT @ORDERID := ORDERID FROM orderHeader WHERE USERNAME = __USERNAME AND ORDERSTATUS = 'CART';


IF @LOTPRICE > 0 THEN

	INSERT INTO
		orderDetail
			(ORDERID,ITEMID,ITEMCODE,ITEMDESC,ORDERQTY,SHIPTODATEQTY,UNITPRICE,EXTPRICE,
             TAXAMT1,TAXAMT2,TAXAMT3,TAXAMT4,TAXAMT5,ITEMLENGTH,ITEMWIDTH,ITEMHEIGHT,ITEMWEIGHT,ITEMPIECES,PROOFCONFIRMATION,ITEMOPTION)
	SELECT
		@ORDERID AS ORDERID,
        ITEM.ID AS ITEMID,
        ITEM.CODE AS ITEMCODE,
        ITEM.DESCRIPTION AS ITEMDESC,
        ITEMPRICE.QTY AS ORDERQTY,
        0 AS SHIPTODATEQTY,
        (ITEMPRICE.PRICE / ITEMPRICE.QTY) + (__ADDCOST / ITEMPRICE.QTY) AS UNITPRICE,
        ITEMPRICE.PRICE + __ADDCOST AS EXTPRICE,
		0 AS TAXAMT1,
        0 AS TAXAMT2,
        0 AS TAXAMT3,
        0 AS TAXAMT4,
        0 AS TAXAMT5,
        ITEMPRICE.LENGTH AS ITEMLENGTH,
        ITEMPRICE.WIDTH AS ITEMWIDTH,
        ITEMPRICE.HEIGHT AS ITEMHEIGHT,
        ITEMPRICE.WEIGHT AS ITEMWEIGHT,
        ITEMPRICE.PIECES AS ITEMPIECES,
        __PROOF AS PROOFCONFIRMATION,
        ITEMPRICE.ITEMOPTION AS ITEMOPTION
	FROM
		items ITEM
	INNER JOIN
		itemPricing ITEMPRICE ON 
			ITEM.ID = ITEMPRICE.ITEMID
	WHERE
		ITEM.ID = __ITEMID AND
        ITEMPRICE.QTY = __QTY AND
        ITEMPRICE.ITEMOPTION = __ITEMOPTION;
        
ELSEIF @VARPRICE > 0 AND @LOTPRICE = 0 THEN

INSERT INTO
		orderDetail
			(ORDERID,ITEMID,ITEMCODE,ITEMDESC,ORDERQTY,SHIPTODATEQTY,UNITPRICE,EXTPRICE,
             TAXAMT1,TAXAMT2,TAXAMT3,TAXAMT4,TAXAMT5,ITEMLENGTH,ITEMWIDTH,ITEMHEIGHT,ITEMWEIGHT,ITEMPIECES,PROOFCONFIRMATION,ITEMOPTION)
	SELECT
		@ORDERID AS ORDERID,
        ITEM.ID AS ITEMID,
        ITEM.CODE AS ITEMCODE,
        ITEM.DESCRIPTION AS ITEMDESC,
        __QTY AS ORDERQTY,
        0 AS SHIPTODATEQTY,
        ITEMPRICE.PRICE + __ADDCOST AS UNITPRICE,
        (ITEMPRICE.PRICE + __ADDCOST) * __QTY AS EXTPRICE,
		0 AS TAXAMT1,
        0 AS TAXAMT2,
        0 AS TAXAMT3,
        0 AS TAXAMT4,
        0 AS TAXAMT5,
        ITEMPRICE.LENGTH AS ITEMLENGTH,
        ITEMPRICE.WIDTH AS ITEMWIDTH,
        ITEMPRICE.HEIGHT AS ITEMHEIGHT,
        ITEMPRICE.WEIGHT * __QTY AS ITEMWEIGHT,
        ITEMPRICE.PIECES AS ITEMPIECES,
        __PROOF AS PROOFCONFIRMATION,
        ITEMPRICE.ITEMOPTION AS ITEMOPTION
	FROM
		items ITEM
	INNER JOIN
		itemPricing ITEMPRICE ON 
			ITEM.ID = ITEMPRICE.ITEMID
	WHERE
		ITEM.ID = __ITEMID AND
        ITEMPRICE.QTY = -1 AND 
        ITEMPRICE.ITEMOPTION = __ITEMOPTION;

ELSE 
	SIGNAL SQLSTATE '45000'
		SET MESSAGE_TEXT = 'Invalid Pricing Found For Item';
END IF;  

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `AddReportingExtraData` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `AddReportingExtraData`(__USERNAME VARCHAR(20), __EXTRADATA VARCHAR(100))
BEGIN

SET SQL_SAFE_UPDATES = 0;

UPDATE
	orderHeader
SET
	EXTRADATA1 = __EXTRADATA
WHERE 
	USERNAME  = __USERNAME AND 
    ORDERSTATUS = 'CART';

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `AddShipmentCostEntry` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `AddShipmentCostEntry`(__CARRIER VARCHAR(100), __METHOD VARCHAR(100),
__SHIPFROM_NAME VARCHAR(100), __SHIPFROM_STREETNUM VARCHAR(100), __SHIPFROM_STREET VARCHAR(100),
__SHIPFROM_CITY VARCHAR(100), __SHIPFROM_PROVINCE VARCHAR(100), __SHIPFROM_COUNTRY VARCHAR(100),
__SHIPFROM_POSTAL VARCHAR(100), __TOTALWEIGHT DECIMAL(19,4), __TOTALBOXES DECIMAL(19,4),
__SHIPTO_PROVINCE VARCHAR(100), __SHIPTO_POSTAL VARCHAR(100), __SHIPTO_CITY VARCHAR(100),
__TOTALPRICE DECIMAL(19,4), __OURMARUP DECIMAL(19,4), __OURSLEEVECHARGE DECIMAL(19,4),
__ORDERID INT)
BEGIN
INSERT INTO `shipmentCostLog`
(
`CARRIER`,
`METHOD`,
`SHIPFROM_NAME`,
`SHIPFROM_STREETNUM`,
`SHIPFROM_STREET`,
`SHIPFROM_CITY`,
`SHIPFROM_PROVINCE`,
`SHIPFROM_COUNTRY`,
`SHIPFROM_POSTAL`,
`TOTALWEIGHT`,
`TOTALBOXES`,
`SHIPTO_PROVINCE`,
`SHIPTO_POSTAL`,
`SHIPTO_CITY`,
`TOTALPRICE`,
`OURMARKUP`,
`OURSLEEVECHARGE`,
`ORDERID`,
`CREATEDATETIME`)
VALUES
(
__CARRIER,
__METHOD,
__SHIPFROM_NAME,
__SHIPFROM_STREETNUM,
__SHIPFROM_STREET,
__SHIPFROM_CITY,
__SHIPFROM_PROVINCE,
__SHIPFROM_COUNTRY,
__SHIPFROM_POSTAL,
__TOTALWEIGHT,
__TOTALBOXES,
__SHIPTO_PROVINCE,
__SHIPTO_POSTAL,
__SHIPTO_CITY,
__TOTALPRICE,
__OURMARUP,
__OURSLEEVECHARGE,
__ORDERID,
CURRENT_TIMESTAMP);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `AdjustItemQty` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `AdjustItemQty`(__ITEMID INT, __QTY INT, __REASON VARCHAR(200))
BEGIN
	UPDATE 
		itemsInventory
	SET
		QTYONHAND = QTYONHAND + __QTY
	WHERE
		ITEMID = __ITEMID;
            
	INSERT INTO 
		itemsAdjustmentLog
       (ITEMID,QTY,ADJDATE,REASON)
	VALUES 
		(__ITEMID,__QTY,CURRENT_TIMESTAMP,__REASON);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ApplyPromoCode` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `ApplyPromoCode`(__USERNAME VARCHAR(50), __PROMO VARCHAR(50))
BEGIN
 SET @RESULT = '';
 
 SET @ORDERID = (SELECT ORDERID FROM orderHeader WHERE ORDERSTATUS = 'CART' AND USERNAME = __USERNAME);
 SET @PROMOTYPE= (SELECT CODETYPE FROM promos WHERE CODE = __PROMO);
 SET @CHKCOUNT= (SELECT COUNT(*) FROM promos WHERE CODE = __PROMO);
 SET @CHKREDEEMED= (SELECT COUNT(*) FROM promos WHERE CODE = __PROMO AND REDEEMED = 0);
 SET @CHKDATES= (SELECT COUNT(*) FROM promos WHERE CODE = __PROMO AND STARTDATE <= CURRENT_TIMESTAMP AND ENDDATE >= CURRENT_TIMESTAMP);
 SET @CHKPROMOCOUNT= (SELECT COUNT(*) FROM orderPromos WHERE ORDERID = @ORDERID);
 SET @CHKITEMCOUNT= (SELECT COUNT(*) 
 FROM orderDetail D 
 INNER JOIN items I ON D.ITEMID = I.ID 
 INNER JOIN promosItems PI ON (PI.ITEMID = I.ID OR PI.ITEMID = I.PARENTITEM) 
 INNER JOIN promos PIHDR ON PI.CODE = PIHDR.CODE
 WHERE 
 ORDERID = @ORDERID AND 
 PI.CODE = __PROMO AND
 ((PIHDR.QTYTYPE = '' AND (PIHDR.MAXQTY = 0 OR ORDERQTY <= PIHDR.MAXQTY)) OR PIHDR.QTYTYPE = 'NOLIMIT' OR (PIHDR.QTYTYPE = 'EXACT' AND ORDERQTY = PIHDR.EXACTQTY) OR (PIHDR.QTYTYPE = 'RANGE' AND PIHDR.MINQTY <= ORDERQTY AND ORDERQTY <= PIHDR.MAXQTY))
 ); 
SET @CHKALLCATCOUNT= (SELECT
COUNT(*)
FROM orderDetail D 
INNER JOIN items I ON D.ITEMID = I.ID 
INNER JOIN itemsSubcategoryLink ISL ON I.ID = ISL.ITEMID
INNER JOIN subcategories SUBCATS ON ISL.SUBCATID = SUBCATS.SUBCATID
CROSS JOIN (SELECT * FROM promos WHERE CODE = __PROMO) PROMO 
WHERE
D.ORDERID = @ORDERID AND 
SUBCATS.CATID NOT IN (SELECT CATID FROM promos PIHDR INNER JOIN promosCategories PC ON PC.CODE = PIHDR.CODE WHERE PC.CODE = __PROMO) AND
((PROMO.QTYTYPE = '' AND (PROMO.MAXQTY = 0 OR ORDERQTY <= PROMO.MAXQTY)) OR PROMO.QTYTYPE = 'NOLIMIT' OR (PROMO.QTYTYPE = 'EXACT' AND ORDERQTY = PROMO.EXACTQTY) OR (PROMO.QTYTYPE = 'RANGE' AND PROMO.MINQTY <= ORDERQTY AND ORDERQTY <= PROMO.MAXQTY))
);
SET @CHKNOTITEMCOUNT= (SELECT COUNT(*)
 FROM orderDetail D 
 INNER JOIN items I ON D.ITEMID = I.ID 
 INNER JOIN promos PIHDR ON PIHDR.CODE = __PROMO
 LEFT OUTER JOIN promosItems PI ON (PI.ITEMID = I.ID OR PI.ITEMID = I.PARENTITEM) 
 WHERE 
 ORDERID = @ORDERID AND 
 PI.ITEMID IS NULL AND 
 ((PIHDR.QTYTYPE = '' AND (PIHDR.MAXQTY = 0 OR ORDERQTY <= PIHDR.MAXQTY)) OR PIHDR.QTYTYPE = 'NOLIMIT' OR (PIHDR.QTYTYPE = 'EXACT' AND ORDERQTY = PIHDR.EXACTQTY) OR (PIHDR.QTYTYPE = 'RANGE' AND PIHDR.MINQTY <= ORDERQTY AND ORDERQTY <= PIHDR.MAXQTY))
 ); 

  IF @CHKCOUNT=0 THEN
    SET @RESULT = 'NOEXIST';
  ELSEIF @CHKDATES = 0 THEN 
    SET @RESULT = 'NOTACTIVEDATE';
  ELSEIF @CHKREDEEMED = 0 THEN 
    SET @RESULT = 'ALREADYREDEEMED';        
  ELSEIF @CHKPROMOCOUNT > 0 THEN 
    SET @RESULT = 'ALREADYPROMO';   
  ELSEIF @CHKITEMCOUNT = 0 AND (@PROMOTYPE = 'ITM$DISC' OR @PROMOTYPE = 'ITM%DISC') THEN
    SET @RESULT = 'NOVALIDITEMS';
  ELSEIF @CHKALLCATCOUNT = 0 AND (@PROMOTYPE = 'ALLCAT$DISC' OR @PROMOTYPE = 'ALLCAT%DISC') THEN
    SET @RESULT = 'NOVALIDITEMS'; 
  ELSEIF @CHKNOTITEMCOUNT = 0 AND (@PROMOTYPE = 'ALLITM$DISC' OR @PROMOTYPE = 'ALLITM%DISC') THEN
    SET @RESULT = 'NOVALIDITEMS';
  ELSE
    SET @RESULT = 'OK';
        INSERT INTO orderPromos
        (ORDERID,PROMOCODE,PROMONAME,SINGLEITEM,PROMOTYPE,PROMOVALUE,CALCDISCOUNT,
         TAXAMT1,TAXAMT2,TAXAMT3,TAXAMT4,TAXAMT5)
    SELECT
      @ORDERID,CODE,NAME,SINGLEITEM,CODETYPE,PROMOVALUE,0.00,0.00,0.00,0.00,0.00,0.00
    FROM
      promos
    WHERE 
      CODE = __PROMO;
        
        UPDATE promos SET REDEEMED = 1 WHERE CODE = __PROMO AND SINGLEUSE = 1;
        
  END IF;

  SELECT @RESULT AS RESULT;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ApproveItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ApproveItem`(__CODE VARCHAR(200))
BEGIN

	SELECT
		ITEM.ID AS ITEMID,
        USERS.EMAIL AS USEREMAIL,
        ITEM.DISPLAYIMAGEPATH
	FROM
		items ITEM 
	INNER JOIN
		user USERS ON 
			USERS.USERNAME = ITEM.GENERATEDBY
	WHERE 
		APPROVALLINK = __CODE;

	UPDATE
		items
	SET
		ASSETAPPROVED = 1,
        APPROVALLINK = NULL
	WHERE
		APPROVALLINK = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ApproveOrder` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `ApproveOrder`(__APPROVALLINK NVARCHAR(100))
BEGIN

SET @ORDERREF = IFNULL((SELECT MAX(ORDERREF)+1 FROM orderHeader),10000);
UPDATE orderDetail
    SET 
        SHIPTODATEQTY = ORDERQTY,
        DOWNLOADLINK = CONCAT(ORDERID,'-',ITEMLINE,'-',MD5(MD5(MD5(NOW())+ORDERID)+ITEMLINE))
  WHERE
    ORDERQTY = -2 AND
        ORDERID IN (SELECT ORDERID FROM orderHeader WHERE APPROVALLINK  COLLATE utf8_unicode_ci = __APPROVALLINK AND APPROVALLINK IS NOT NULL);    

UPDATE
  orderHeader
SET
  ORDERREF = @ORDERREF
WHERE
  APPROVALLINK  COLLATE utf8_unicode_ci = __APPROVALLINK AND
    APPROVALLINK IS NOT NULL;


SELECT
  HDR.*,
    DTL.*,
    ITEM.TYPE,
    USER.FIRSTNAME AS USER_FIRSTNAME,
    USER.LASTNAME AS USER_LASTNAME,
    USER.EMAIL AS USER_EMAIL,
    USER.LANGUAGE AS USER_LANGUAGE,
    BRANCH.NAME AS BRANCH_NAME,
    BRANCH.MANAGEMENTEMAIL AS BRANCH_MANAGEMENTEMAIL,
    COALESCE(BRANCHADDRESS.LANGUAGE,'EN') AS BRANCH_LANGUAGE,
    'ACTIVE' AS REALSTATUS,
    COALESCE(ITEM.DLSUGGESTIONS,'') AS DLSUGGESTIONS
FROM
  orderHeader HDR
INNER JOIN
  orderDetail DTL ON 
    HDR.ORDERID = DTL.ORDERID
INNER JOIN
  items ITEM ON 
    DTL.ITEMID = ITEM.ID        
INNER JOIN
  user USER ON 
    HDR.USERNAME = USER.USERNAME
INNER JOIN
  branches BRANCH ON 
    USER.BRANCH = BRANCH.CODE
LEFT OUTER JOIN
  (SELECT * FROM branchesAddresses WHERE ISMAIN = 1) BRANCHADDRESS ON 
    BRANCH.CODE = BRANCHADDRESS.CODE
WHERE
  HDR.APPROVALLINK  COLLATE utf8_unicode_ci = __APPROVALLINK AND
    HDR.APPROVALLINK IS NOT NULL;
      
SELECT @SHIPLINECOUNT := COUNT(*) FROM orderDetail 
    WHERE ORDERQTY <> -2 AND
        ORDERID IN (SELECT ORDERID FROM orderHeader WHERE APPROVALLINK  COLLATE utf8_unicode_ci = __APPROVALLINK AND APPROVALLINK IS NOT NULL);
      
      
UPDATE
  orderHeader
SET
  APPROVALLINK = NULL,
    ORDERSTATUS = CASE WHEN @SHIPLINECOUNT = 0 THEN 'SHIPPED' ELSE 'ACTIVE' END,
    ORDERMODIFIED = CURRENT_TIMESTAMP,
    APPROVALDATE = CURRENT_TIMESTAMP
WHERE
  APPROVALLINK  COLLATE utf8_unicode_ci = __APPROVALLINK AND
    APPROVALLINK IS NOT NULL; 

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ArchiveItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ArchiveItem`(__ITEMID INT, __USERNAME VARCHAR(50))
BEGIN

	UPDATE
		items
	SET
		ARCHIVED = 1
	WHERE
		ID = __ITEMID AND
        ID IN (SELECT ITEMID FROM itemsBranchesLink LINK INNER JOIN user USR ON LINK.BRANCHCODE = USR.BRANCH WHERE USR.USERNAME = __USERNAME);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CancelRemaindingOrder` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CancelRemaindingOrder`(__ORDERID INT)
BEGIN

UPDATE
	orderHeader
SET
	ORDERSTATUS = 'CANCELLED',
    SPECIALINSTRUCTIONS = 'Order Cancelled on ' + CURRENT_TIMESTAMP
    
WHERE
	ORDERID = __ORDERID;

UPDATE
	orderDetail
SET
	ORDERQTY = SHIPTODATEQTY
WHERE
	ORDERID = __ORDERID;
    
SELECT * FROM orderHeader WHERE ORDERID = __ORDERID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ChangeAccountTicketStatus` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ChangeAccountTicketStatus`(__TICKETID INT, __STATUS INT)
BEGIN

	UPDATE
		accountMgrHeader
	SET
		STATUS = __STATUS,
        DATECLOSED = CURRENT_TIMESTAMP
	WHERE
		ID = __TICKETID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ChangeOrderShipToAddress` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ChangeOrderShipToAddress`(__USERNAME VARCHAR(50), __ID VARCHAR(50))
BEGIN


SET SQL_SAFE_UPDATES = 0;

UPDATE
	orderHeader
SET
	SHIPNAME = ( SELECT NAME FROM ( SELECT 'S' AS RC, ID,NAME FROM shipToAddresses UNION ALL SELECT 'B' AS RC,B.CODE,NAME FROM branches B INNER JOIN branchesAddresses BB ON B.CODE = BB.CODE WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID ),
    SHIPADDRESS = ( SELECT ADDRESS FROM ( SELECT 'S' AS RC, ID,ADDRESS FROM shipToAddresses UNION ALL SELECT 'B' AS RC,CODE,ADDRESS FROM branchesAddresses WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID ),
    SHIPADDRESS2 = ( SELECT ADDRESS2 FROM ( SELECT 'S' AS RC, ID,ADDRESS2 FROM shipToAddresses UNION ALL SELECT 'B' AS RC,CODE,ADDRESS2 FROM branchesAddresses WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID ),
    SHIPCITY = ( SELECT CITY FROM ( SELECT 'S' AS RC, ID,CITY FROM shipToAddresses UNION ALL SELECT 'B' AS RC,CODE,CITY FROM branchesAddresses WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID ),
	SHIPPROVINCE = ( SELECT PROVINCE FROM ( SELECT 'S' AS RC, ID,PROVINCE FROM shipToAddresses UNION ALL SELECT 'B' AS RC,CODE,PROVINCE FROM branchesAddresses WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID ),
    SHIPCOUNTRY = ( SELECT COUNTRY FROM ( SELECT 'S' AS RC, ID,COUNTRY FROM shipToAddresses UNION ALL SELECT 'B' AS RC,CODE,COUNTRY FROM branchesAddresses WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID ),
    SHIPPOSTAL = ( SELECT POSTAL FROM ( SELECT 'S' AS RC, ID,POSTAL FROM shipToAddresses UNION ALL SELECT 'B' AS RC,CODE,POSTALCODE FROM branchesAddresses WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID ),
	SHIPCONTACTPHONE = ( SELECT PHONE FROM ( SELECT 'S' AS RC, ID,PHONE FROM shipToAddresses UNION ALL SELECT 'B' AS RC,CODE,PHONE FROM branchesAddresses WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID ),
    SHIPCONTACTFAX = ( SELECT FAX FROM ( SELECT 'S' AS RC, ID,FAX FROM shipToAddresses UNION ALL SELECT 'B' AS RC,CODE,FAX FROM branchesAddresses WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID ),
    SHIPTAXGROUP = ( SELECT TAXGROUP FROM ( SELECT 'S' AS RC, ID,TAXGROUP FROM shipToAddresses UNION ALL SELECT 'B' AS RC,B.CODE,TAXGROUP FROM branches B INNER JOIN branchesAddresses BB ON B.CODE = BB.CODE WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID ),
    SHIPSTOREID = ( SELECT STOREID FROM ( SELECT 'S' AS RC, ID,STOREID FROM shipToAddresses UNION ALL SELECT 'B' AS RC,B.CODE,B.CODE AS STOREID FROM branches B INNER JOIN branchesAddresses BB ON B.CODE = BB.CODE WHERE ISMAIN = 1) ADDR WHERE CONCAT(ADDR.RC,'-',ADDR.ID) = __ID )
WHERE 
	USERNAME  = __USERNAME AND 
    ORDERSTATUS = 'CART';


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ChangeTicketStatus` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ChangeTicketStatus`(__TICKETID INT, __STATUS INT)
BEGIN

	UPDATE
		ticketHeader
	SET
		STATUS = __STATUS,
        DATECLOSED = CURRENT_TIMESTAMP
	WHERE
		ID = __TICKETID;

	
    SELECT 
		HDR.*,
        USR.EMAIL,
        USR.LANGUAGE
	FROM 
		ticketHeader HDR 
	LEFT OUTER JOIN
		user USR ON 
			HDR.ENTEREDBY = USR.USERNAME
	WHERE 
    ID = __TICKETID; 

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CheckCartItemDuplicates` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CheckCartItemDuplicates`(__USERNAME VARCHAR(50), __ITEMID INT)
BEGIN

SET @RECCNT := (SELECT 
					COUNT(*) 
				FROM 
					orderHeader HDR 
				INNER JOIN 
					orderDetail DTL ON 
						HDR.ORDERID = DTL.ORDERID 
				WHERE 
					HDR.USERNAME = __USERNAME AND
                    HDR.ORDERSTATUS = 'CART' AND
                    DTL.ITEMID = __ITEMID
				);

IF @RECCNT > 0 THEN
	SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot add the same item to the cart.';
END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CheckCartItemLowInventory` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CheckCartItemLowInventory`(__USERNAME VARCHAR(50), __ITEMID INT, __QTY INT)
BEGIN

	SELECT
		ITM.ID,
        IFNULL(ITMINV.QTYONHAND,0) AS INVQTY,
        IFNULL(ONORDER.ONORDER,0) AS ALLOCATEDQTY,
        CASE 
			WHEN 
				ITM.TYPE <> 0 THEN 1
			ELSE
				CASE WHEN __QTY <= IFNULL(ITMINV.QTYONHAND,0) - IFNULL(ONORDER.ONORDER,0) THEN 1 ELSE 0 END
		END AS ENOUGHQTY
	FROM
		items ITM
	LEFT OUTER JOIN
		itemsInventory ITMINV ON 
			ITM.ID = ITMINV.ITEMID
	LEFT OUTER JOIN
		( SELECT ITEMID,SUM(ORDERQTY-SHIPTODATEQTY) AS ONORDER FROM orderDetail
		  WHERE ORDERID IN (SELECT ORDERID FROM orderHeader WHERE ORDERSTATUS IN ('ACTIVE'))
          GROUP BY ITEMID) ONORDER ON
			ITM.ID = ONORDER.ITEMID
	WHERE
		ITM.ID = __ITEMID;


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CheckForLowLevelItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CheckForLowLevelItems`(__ORDERID INT)
BEGIN
	SELECT
		THISORDER.ORDERID,
        THISORDER.ORDERREF,
		ITEM.ID,
		ITEM.CODE,
        ITEM.DESCRIPTION,
        THISORDER.REMQTY AS ORDERQTY,
        COALESCE(OTHORDER.REMQTY,0) AS OTHQTY,
        ITEM.TYPE,
        COALESCE(ITEM.MINLEVEL,0) AS MINLEVEL,
        COALESCE(INV.QTYONHAND,0) AS QTYONHAND
	FROM
		( SELECT H.ORDERID, H.ORDERREF, ITEMID,SUM(ORDERQTY-SHIPTODATEQTY) AS REMQTY FROM orderHeader H INNER JOIN orderDetail D ON H.ORDERID = D.ORDERID WHERE  H.ORDERID = __ORDERID GROUP BY H.ORDERID, H.ORDERREF, D.ITEMID) THISORDER  
	INNER JOIN
		items ITEM ON 
			THISORDER.ITEMID = ITEM.ID
	LEFT OUTER JOIN
		itemsInventory INV ON 
			THISORDER.ITEMID = INV.ITEMID
	LEFT OUTER JOIN
		( SELECT ITEMID,SUM(ORDERQTY-SHIPTODATEQTY) AS REMQTY FROM orderHeader H INNER JOIN orderDetail D ON H.ORDERID = D.ORDERID WHERE ORDERSTATUS = 'ACTIVE' AND H.ORDERID <> __ORDERID GROUP BY D.ITEMID) OTHORDER ON 
			OTHORDER.ITEMID = THISORDER.ITEMID
	WHERE
		COALESCE(INV.QTYONHAND,0) - COALESCE(ITEM.MINLEVEL,0) - COALESCE(OTHORDER.REMQTY,0) - THISORDER.REMQTY <= 0
	ORDER BY
		ITEM.TYPE,
		ITEM.CODE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CheckIfItemAppliesPromo` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CheckIfItemAppliesPromo`(__ORDERID INT, __PROMO VARCHAR(50), __ITEMID INT)
BEGIN

SELECT 
 PI.* 
FROM 
 orderDetail D 
INNER JOIN 
 items I ON D.ITEMID = I.ID 
INNER JOIN 
 promosItems PI ON (PI.ITEMID = I.ID OR PI.ITEMID = I.PARENTITEM)
INNER JOIN 
	promos PIHDR ON PI.CODE = PIHDR.CODE AND (PIHDR.MAXQTY = 0 OR D.ORDERQTY <= PIHDR.MAXQTY)
WHERE 
	ORDERID = __ORDERID AND PI.CODE = __PROMO AND D.ITEMID = __ITEMID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CheckIfItemAppliesPromoCat` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `CheckIfItemAppliesPromoCat`(__ORDERID INT, __PROMO VARCHAR(50), __ITEMID INT)
BEGIN

SELECT
 D.*
FROM orderDetail D 
INNER JOIN items I ON D.ITEMID = I.ID 
INNER JOIN itemsSubcategoryLink ISL ON I.ID = ISL.ITEMID
INNER JOIN subcategories SUBCATS ON ISL.SUBCATID = SUBCATS.SUBCATID
CROSS JOIN (SELECT * FROM promos WHERE CODE = __PROMO) PROMO 
WHERE
D.ORDERID = __ORDERID AND 
D.ITEMID = __ITEMID AND
SUBCATS.CATID NOT IN (SELECT CATID FROM promos PIHDR INNER JOIN promosCategories PC ON PC.CODE = PIHDR.CODE WHERE PC.CODE = __PROMO) AND
(PROMO.MAXQTY = 0 OR ORDERQTY <= PROMO.MAXQTY);


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CheckIfItemAppliesPromoExceptionList` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `CheckIfItemAppliesPromoExceptionList`(__ORDERID INT, __PROMO VARCHAR(50), __ITEMID INT)
BEGIN

SELECT 
 PIHDR.* 
FROM 
 orderDetail D 
INNER JOIN 
 items I ON D.ITEMID = I.ID 
INNER JOIN 
  promos PIHDR ON PIHDR.CODE = __PROMO AND (PIHDR.MAXQTY = 0 OR D.ORDERQTY <= PIHDR.MAXQTY)
LEFT OUTER JOIN 
  promosItems PI ON (PI.ITEMID = I.ID OR PI.ITEMID = I.PARENTITEM)
WHERE 
  ORDERID = __ORDERID AND D.ITEMID = __ITEMID AND PI.ITEMID IS NULL;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CheckUserAccount` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CheckUserAccount`(IN `UNAME` VARCHAR(50), IN `PASS` VARCHAR(50))
BEGIN
	SELECT 
		USERS.*,
        COALESCE(SKINDEF.STYLEFILENAME,'DEFAULT') AS SKIN,
        COALESCE(BRANCH.SKIN,'DEFAULT') AS BANNER
	FROM 
		user USERS
	LEFT OUTER JOIN
		branches BRANCH ON 
			USERS.BRANCH = BRANCH.CODE
	LEFT OUTER JOIN
		branchSkinDefinition SKINDEF ON 
			BRANCH.SKIN = SKINDEF.SKINNAME
	WHERE USERNAME=UNAME AND PASSWORD=CONCAT('*', UPPER(SHA1(UNHEX(SHA1(PASS))))) AND USERS.STATUS=1;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CheckUserAccount_ByIdBranch` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CheckUserAccount_ByIdBranch`(__USERNAME VARCHAR(50), __BRANCHNAME VARCHAR(100))
BEGIN

	SELECT 
		USERS.*,
        COALESCE(SKINDEF.STYLEFILENAME,'DEFAULT') AS SKIN,
        COALESCE(BRANCH.SKIN,'DEFAULT') AS BANNER
	FROM 
		user USERS
	LEFT OUTER JOIN
		branches BRANCH ON 
			USERS.BRANCH = BRANCH.CODE
	LEFT OUTER JOIN
		branchSkinDefinition SKINDEF ON 
			BRANCH.SKIN = SKINDEF.SKINNAME
	WHERE 
        USERNAME=__USERNAME AND 
        USERS.STATUS=1 AND 
        USERS.USERLEVEL < 90;
    
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ClearAllAdBrandLink` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ClearAllAdBrandLink`(__ID INT)
BEGIN
	DELETE FROM AdItemsBrand WHERE ID = __ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ClearAllCategoryBrandLink` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ClearAllCategoryBrandLink`(__CATID INT)
BEGIN
	DELETE FROM categoriesBrand WHERE CATID = __CATID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateAccountTicket` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateAccountTicket`(__ENTEREDBY VARCHAR(50), __LANGUAGE VARCHAR(20), __ACCOUNT VARCHAR(20), __BANNER VARCHAR(20),
__BRANCHNUMBER VARCHAR(20), __BRANCHNAME VARCHAR(100), __ADDRESS VARCHAR(1000), __CITY VARCHAR(100), __PROVINCE VARCHAR(100),
__POSTAL VARCHAR(100), __COUNTRY VARCHAR(100), __PHONE VARCHAR(100), __FAX VARCHAR(100), __APPOINTMENTPHONE VARCHAR(100),
__CONTACTFIRST VARCHAR(100), __CONTACTLAST VARCHAR(100), __EMAIL VARCHAR(100), __NOTE VARCHAR(1000),
__BOUTIQUEFIRST VARCHAR(100), __BOUTIQUELAST VARCHAR(100), __TAGLINENAME VARCHAR(100), __AFFILIATEDNAME VARCHAR(100),
__PHARMLEGALNAME VARCHAR(100), __PHARMPHOTONAME VARCHAR(100))
BEGIN

DECLARE __TICKETID INT;

INSERT INTO accountMgrHeader
(ENTEREDBY,DATEENTERED,STATUS,TITLE,DATECLOSED,LANGUAGE,ACCOUNT,BANNER,BRANCHNUMBER,ADDRESS,CITY,PROVINCE,COUNTRY,POSTAL,
PHONE,FAX,APPOINTMENTPHONE,CONTACTFIRST,CONTACTLAST,EMAIL,NOTE,BOUTIQUEFIRST,BOUTIQUELAST,TAGLINENAME,AFFILIATEDNAME,PHARMLEGALNAME,PHARMPHOTONAME)
VALUES
(__ENTEREDBY,CURRENT_TIMESTAMP,1,__BRANCHNAME,NULL,__LANGUAGE,__ACCOUNT,__BANNER,__BRANCHNUMBER,
__ADDRESS,__CITY,__PROVINCE,__COUNTRY,__POSTAL,__PHONE,__FAX,__APPOINTMENTPHONE,__CONTACTFIRST,__CONTACTLAST,__EMAIL,__NOTE,
__BOUTIQUEFIRST,__BOUTIQUELAST,__TAGLINENAME,__AFFILIATEDNAME, __PHARMLEGALNAME, __PHARMPHOTONAME);

SET __TICKETID = LAST_INSERT_ID();

SELECT *,UNIX_TIMESTAMP(DATEENTERED) AS UNIX_DATEENTERED FROM accountMgrHeader WHERE ID = __TICKETID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateAccountTicketReply` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateAccountTicketReply`(__TICKETID INT, __MESSAGE VARCHAR(1000), __ENTEREDBY VARCHAR(50))
BEGIN

 DECLARE __TICCHECK INT;
 SELECT COUNT(*) INTO __TICCHECK FROM accountMgrHeader WHERE ( ENTEREDBY = __ENTEREDBY OR __ENTEREDBY IN (SELECT USERNAME FROM user WHERE USERLEVEL >= 99)) AND ID = __TICKETID;
 
 IF __TICCHECK > 0 THEN

 INSERT INTO
 accountMgrMessages
 (TICKETID,DATEENTERED,ENTEREDBY,CLIENTMESSAGE,MESSAGE)
 VALUES
 (
 __TICKETID,
 CURRENT_TIMESTAMP,
 __ENTEREDBY,
 CASE WHEN __ENTEREDBY IN (SELECT USERNAME FROM user WHERE USERLEVEL >= 99) THEN 0 ELSE 1 END,
 __MESSAGE
 );
 
 SELECT 
 HDR.*,
 DTL.MESSAGE,
 DTL.DATEENTERED AS RDATEENTERED,
 USR.FIRSTNAME,
 USR.LASTNAME,
 USR.EMAIL,
 USR.LANGUAGE,
 USR2.FIRSTNAME AS RFIRSTNAME, 
 USR2.LASTNAME AS RLASTNAME,
 USR2.EMAIL AS REMAIL 
 FROM 
 accountMgrHeader HDR 
 LEFT OUTER JOIN
 accountMgrMessages DTL ON 
 HDR.ID = DTL.TICKETID
 LEFT OUTER JOIN
 user USR ON 
 HDR.ENTEREDBY = USR.USERNAME
 LEFT OUTER JOIN
 user USR2 ON 
 DTL.ENTEREDBY = USR2.USERNAME                
		WHERE 
		ID = __TICKETID AND
        DTL.MESSAGEID = LAST_INSERT_ID();
        
	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateAdBrandLink` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateAdBrandLink`(__ADID INT, __BRANDNAME VARCHAR(20))
BEGIN
	INSERT INTO AdItemsBrand (ID,BRANDNAME)
    VALUES (__ADID,__BRANDNAME);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateCategoryBrandLink` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateCategoryBrandLink`(__CATID INT, __BRANDNAME VARCHAR(20))
BEGIN
	INSERT INTO categoriesBrand (CATID,BRANDNAME)
    VALUES (__CATID,__BRANDNAME);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateItemBranchLink` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateItemBranchLink`(__ITEMID INT, __BRANCHCODE VARCHAR(20))
BEGIN
	INSERT INTO
		itemsBranchesLink
		(ITEMID,BRANCHCODE)
	VALUES
		(__ITEMID,__BRANCHCODE);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateItemCategoryLink` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateItemCategoryLink`(__ITEMID INT, __SUBCATID INT)
BEGIN
	INSERT INTO 
		itemsSubcategoryLink
		(ITEMID,SUBCATID)
	VALUES
		(__ITEMID,__SUBCATID);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateItemPricing` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateItemPricing`(__ITEMID INT, __QTY INT, __ITEMOPTION VARCHAR(30), __PRICE DECIMAL(19,4), __LENGTH DECIMAL(19,4), __WIDTH DECIMAL(19,4), __HEIGHT DECIMAL(19,4), __WEIGHT DECIMAL(19,4), __PIECES INT)
BEGIN
	INSERT INTO
		itemPricing
		(ITEMID,QTY,PRICE,LENGTH,WIDTH,HEIGHT,WEIGHT,PIECES,ITEMOPTION)
	VALUES
		(__ITEMID,__QTY,__PRICE,__LENGTH,__WIDTH,__HEIGHT,__WEIGHT,__PIECES,__ITEMOPTION);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateNewAd` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateNewAd`(__NAME VARCHAR(1000), __STARTDATE DATE, __ENDDATE DATE, __LANGUAGE VARCHAR(2), __SORTORDER INT, __URL VARCHAR(500), __ADPATH VARCHAR(200))
BEGIN

	INSERT INTO 
		AdItems
        (`NAME`,STARTDATE,ENDDATE,`LANGUAGE`,SORTORDER,IMAGEPATH,URL)
	VALUES
		(__NAME,__STARTDATE,__ENDDATE,__LANGUAGE,__SORTORDER,__ADPATH,__URL);

	SELECT LAST_INSERT_ID() AS ADID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateNewBranch` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateNewBranch`(__CODE VARCHAR(20), __NAME VARCHAR(100), __MGREMAIL VARCHAR(100), __TREEMAIL VARCHAR(100), __TAXGROUP VARCHAR(6), __SKIN VARCHAR(20), __STATUS INTEGER, __COMMENTS VARCHAR(1000), __SHIPZONE VARCHAR(20))
BEGIN
INSERT INTO
	branches (CODE,NAME,MANAGEMENTEMAIL,TREASUREREMAIL,TAXGROUP,SKIN,STATUS,COMMENTS,SHIPZONE)
VALUES
	(__CODE, __NAME, __MGREMAIL, __TREEMAIL,__TAXGROUP,__SKIN, __STATUS, __COMMENTS, __SHIPZONE);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateNewBranchAddress` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateNewBranchAddress`(__CODE VARCHAR(20), __LANG VARCHAR(2), __ISMAIN INTEGER, __ADDRESS VARCHAR(1000), __ADDRESS2 VARCHAR(1000), __CITY VARCHAR(100), __PROVINCE VARCHAR(100), __COUNTRY VARCHAR(100), __POSTALCODE VARCHAR(20), __PHONE VARCHAR(20), __FAX VARCHAR(20))
BEGIN

INSERT INTO
	branchesAddresses
		(CODE, LANGUAGE, ISMAIN, ADDRESS, ADDRESS2, CITY, PROVINCE, COUNTRY, POSTALCODE, PHONE, FAX)
VALUES
	(__CODE, __LANG, __ISMAIN, __ADDRESS, __ADDRESS2, __CITY, __PROVINCE, __COUNTRY, __POSTALCODE, __PHONE, __FAX);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateNewCategory` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateNewCategory`(__NAME VARCHAR(50), __DESCRIPTION VARCHAR(200), __LANGUAGE VARCHAR(2), __ICON VARCHAR(200), __USERLEVEL INTEGER, __COMMENTS VARCHAR(1000))
BEGIN

	INSERT	INTO
		categories
        (NAME,DESCRIPTION,ICONURL,LANGUAGE,USERLEVEL,COMMENTS,CREATEDDATE,MODIFIEDDATE)
	VALUES
		(__NAME,__DESCRIPTION,__ICON,__LANGUAGE,__USERLEVEL,__COMMENTS,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP);

	SELECT LAST_INSERT_ID() AS CATID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateNewItem` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `CreateNewItem`(IN `__TYPE` INT, IN `__CODE` VARCHAR(50), IN `__DESCRIPTION` VARCHAR(200), IN `__PRODUCEDETAIL` VARCHAR(1000), IN `__SIZE` VARCHAR(50), IN `__NUMPAGES` VARCHAR(50), IN `__PRINTINGTYPE` VARCHAR(50), IN `__STOCK` VARCHAR(50), IN `__STATUS` INT, IN `__MINLEVEL` INT, IN `__LEADTIME` INT, IN `__INITIALQTY` INT, IN `__DISPLAYNAME` VARCHAR(1000), IN `__PROOFNAME` VARCHAR(1000), IN `__PARAMETERSNAME` VARCHAR(1000), IN `__UPLOADDIR` VARCHAR(1000), IN `__PREVIEWNAME` VARCHAR(1000), IN `__SHIPBOXINSLEEVE` INT, IN `__SKIPPDFPERMISSIONCHECK` INT, IN `__DLSUGGESTIONS` VARCHAR(1000))
BEGIN
        INSERT INTO 
                items
                (TYPE,CODE,DESCRIPTION,PRODUCEDETAIL,SIZE,NUMPAGES,PRINTINGTYPE,STOCK,STATUS,MINLEVEL,LEADTIME,DISPLAYIMAGENAME,PROOFPDFNAME,PARAMETERSFILENAME,PREVIEWIMAGENAME,DISPLAYIMAGEPATH,PROOFPDFPATH,PARAMETERSFILEPATH,PREVIEWIMAGEPATH,SHIPBOXINSLEEVE,SKIPPDFPERMISSIONCHECK,DLSUGGESTIONS)
        VALUES
                (__TYPE,__CODE,__DESCRIPTION,__PRODUCEDETAIL,__SIZE,__NUMPAGES,__PRINTINGTYPE,__STOCK,__STATUS,__MINLEVEL,__LEADTIME,__DISPLAYNAME,__PROOFNAME,__PARAMETERSNAME,__PREVIEWNAME,
         CASE WHEN LENGTH(__DISPLAYNAME) > 0 THEN CONCAT(__UPLOADDIR,__DISPLAYNAME) ELSE '' END,
         CASE WHEN LENGTH(__PROOFNAME) > 0 THEN CONCAT(__UPLOADDIR,__PROOFNAME) ELSE '' END,
         CASE WHEN LENGTH(__PARAMETERSNAME) > 0 THEN CONCAT(__UPLOADDIR,__PARAMETERSNAME) ELSE '' END,
         CASE WHEN LENGTH(__PREVIEWNAME) > 0 THEN CONCAT(__UPLOADDIR,__PREVIEWNAME) ELSE '' END,
         __SHIPBOXINSLEEVE,
         __SKIPPDFPERMISSIONCHECK,
         __DLSUGGESTIONS
                );
 
        SELECT LAST_INSERT_ID() AS ITEMID;
           
        IF __TYPE = 0 THEN
                INSERT INTO 
                        itemsInventory
                        (ITEMID,QTYONHAND)
                VALUES (LAST_INSERT_ID(),0);
        END IF;
 
        IF __INITIALQTY > 0 THEN
                UPDATE 
                        itemsInventory
                SET
                        QTYONHAND = __INITIALQTY
                WHERE
                        ITEMID = LAST_INSERT_ID();
            
                INSERT INTO 
                        itemsAdjustmentLog
            (ITEMID,QTY,ADJDATE,REASON)
                VALUES (LAST_INSERT_ID(),__INITIALQTY,CURRENT_TIMESTAMP,'Initial Inventory');
    END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateNewNewsItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateNewNewsItem`(__STARTDATE DATE, __ENDDATE DATE, __LANGUAGE VARCHAR(2), __TITLE VARCHAR(1000), __MESSAGE VARCHAR(1000))
BEGIN
	INSERT INTO 
		newsItems
		(STARTDATE,ENDDATE,LANGUAGE,TITLE,MESSAGE)
	VALUES
		(__STARTDATE,__ENDDATE,__LANGUAGE,__TITLE,__MESSAGE);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateNewPromo` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `CreateNewPromo`(__NAME VARCHAR(100), __CODE VARCHAR(50), __CODETYPE VARCHAR(12), __PROMOVALUE DECIMAL(19,2), __QTYTYPE VARCHAR(12), __MAXQTY INT, __MINQTY INT, __EXACTQTY INT, __STARTDATE DATE, __ENDDATE DATE, __SINGLEUSE INT, __REDEEMED INT, __SINGLEITEM INT)
BEGIN

 INSERT INTO 
 promos
 (NAME,CODE,CODETYPE,PROMOVALUE,QTYTYPE,MAXQTY,MINQTY,EXACTQTY,STARTDATE,ENDDATE,SINGLEUSE,REDEEMED,SINGLEITEM)
 VALUES
 (__NAME,__CODE,__CODETYPE,__PROMOVALUE,__QTYTYPE,__MAXQTY,__MINQTY,__EXACTQTY,__STARTDATE,__ENDDATE,__SINGLEUSE,__REDEEMED,__SINGLEITEM);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateNewShipToAddress` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `CreateNewShipToAddress`(__NAME VARCHAR(100), __STOREID VARCHAR(20), __ADDRESS VARCHAR(1000), __ADDRESS2 VARCHAR(1000), __CITY VARCHAR(100),
__PROVINCE VARCHAR(100), __COUNTRY VARCHAR(100), __POSTAL VARCHAR(20), __PHONE VARCHAR(20), __FAX VARCHAR(20),
__TAXGROUP VARCHAR(6), __SHIPZONE VARCHAR(6))
BEGIN

INSERT INTO
	shipToAddresses
    (NAME,STOREID,ADDRESS,ADDRESS2,CITY,PROVINCE,COUNTRY,POSTAL,PHONE,FAX,TAXGROUP,SHIPZONE)
VALUES
	(__NAME,__STOREID,__ADDRESS,__ADDRESS2,__CITY,__PROVINCE,__COUNTRY,__POSTAL,__PHONE,__FAX,__TAXGROUP,__SHIPZONE);

SELECT LAST_INSERT_ID() AS SHIPID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateNewSubCategory` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `CreateNewSubCategory`(__CATID INTEGER, __PARENTSUBCATID INTEGER, __NAME VARCHAR(50), __DESCRIPTION VARCHAR(200), __ICONURL VARCHAR(200), __USERLEVEL INT)
BEGIN
    INSERT INTO subcategories (CATID,PARENTSUBCATID,NAME,DESCRIPTION,ICONURL,USERLEVEL)
    VALUES (__CATID,__PARENTSUBCATID,__NAME,__DESCRIPTION, __ICONURL, __USERLEVEL);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateNewUser` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateNewUser`(IN `UNAME` VARCHAR(50), IN `__BRANCH` VARCHAR(20), IN `PASS` VARCHAR(50), IN `FNAME` VARCHAR(50), IN `LNAME` VARCHAR(50), IN `LANG` VARCHAR(2), IN `STAT` INT, IN `USERLVL` INT, IN `COMMENTS` VARCHAR(1000), IN `EMAIL` VARCHAR(100))
BEGIN

INSERT INTO 
	`user` (`USERNAME`,`BRANCH`,`PASSWORD`,`PLAINPASSWORD`,`FIRSTNAME`,`LASTNAME`,`LANGUAGE`,`STATUS`,`USERLEVEL`,`COMMENTS`,`EMAIL`) 
VALUES 
  (UNAME,__BRANCH,CONCAT('*', UPPER(SHA1(UNHEX(SHA1(PASS))))),PASS,FNAME,LNAME,LANG,STAT,USERLVL,COMMENTS,EMAIL);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateShipmentHeader` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateShipmentHeader`(__ORDERID INT, __TRACKNUM VARCHAR(100), __METHOD VARCHAR(100), __AMOUNT DECIMAL(16,2), __WEIGHT DECIMAL(16,2), __PIECES INT, __INSTRUCTIONS VARCHAR(1000))
BEGIN

	INSERT INTO 
		shipmentHeader
        (ORDERID,TRACKNUM,SHIPDATE,SHIPMETHOD,SHIPAMOUNT,SHIPWEIGHT,SHIPPIECES,SHIPINSTRUCTIONS)
	VALUES
		(__ORDERID,__TRACKNUM,CURRENT_TIMESTAMP,__METHOD,__AMOUNT,__WEIGHT,__PIECES,__INSTRUCTIONS);
    
    SELECT
		SHIPID,
        ORDERID
	FROM
		shipmentHeader
	WHERE
		SHIPID = LAST_INSERT_ID();
    
    
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateShipmentLine` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateShipmentLine`(__SHIPID INT, __ORDERID INT, __ORDERLINE INT, __SHIPQTY INT)
BEGIN

	INSERT INTO
		shipmentDetail
		(SHIPID,ORDERID,ORDERLINE,SHIPQTY)
	VALUES
		(__SHIPID,__ORDERID,__ORDERLINE,__SHIPQTY);
        
	UPDATE
		orderDetail
	SET
		SHIPTODATEQTY = SHIPTODATEQTY + __SHIPQTY
	WHERE
		ORDERID = __ORDERID AND
        ITEMLINE = __ORDERLINE;
        
	UPDATE
		itemsInventory
	SET
		QTYONHAND = QTYONHAND - __SHIPQTY
	WHERE
		ITEMID IN (SELECT ITEMID FROM orderDetail WHERE ORDERID = __ORDERID AND ITEMLINE = __ORDERLINE);
        
	INSERT INTO 
		itemsAdjustmentLog
			(ITEMID,QTY,ADJDATE,REASON)
	SELECT
		ITEMID,
        __SHIPQTY * -1 AS QTY,
        CURRENT_TIMESTAMP AS ADJDATE,
        CONCAT('Shipment for Order# ', ORDERID, ' Ship# ', __SHIPID) AS REASON
	FROM
		orderDetail
	WHERE
		ORDERID = __ORDERID AND
        ITEMLINE = __ORDERLINE;  
        
	UPDATE
		orderHeader
	SET
		ORDERSTATUS = 'SHIPPED'
	WHERE
		ORDERID = __ORDERID AND
        ORDERID IN (SELECT ORDERID FROM orderDetail WHERE ORDERID = __ORDERID GROUP BY ORDERID HAVING SUM(ORDERQTY) = SUM(SHIPTODATEQTY));

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateShipToAddressUserLink` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `CreateShipToAddressUserLink`(__shipid INT, __username VARCHAR(30))
BEGIN

	INSERT INTO shipToAddressesUserList (ID,USERNAME) VALUES (__shipid, __username); 

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateSupportTicket` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateSupportTicket`(__TITLE VARCHAR(1000), __MESSAGE VARCHAR(1000), __ENTEREDBY VARCHAR(50))
BEGIN
 
 DECLARE __TICKETID INT;

 
 INSERT INTO ticketHeader
 (ENTEREDBY,DATEENTERED,STATUS,TITLE,DATECLOSED)
 VALUES
 (__ENTEREDBY,CURRENT_TIMESTAMP,1,__TITLE,NULL);
 
 
 SET __TICKETID = LAST_INSERT_ID();
 
 
 INSERT INTO ticketDetail
 (TICKETID,DATEENTERED,ENTEREDBY,CLIENTMESSAGE,MESSAGE)
 VALUES
 (__TICKETID,CURRENT_TIMESTAMP,__ENTEREDBY,1,__MESSAGE);
 
 
 SELECT 
 HDR.*,
 DTL.MESSAGEID,
 DTL.MESSAGE,
 USR.FIRSTNAME,
 USR.LASTNAME,
 USR.EMAIL,
 USR.LANGUAGE,
 UNIX_TIMESTAMP(DTL.DATEENTERED) AS UNIX_DATEENTERED
 FROM 
 ticketHeader HDR 
 LEFT OUTER JOIN
 ticketDetail DTL ON 
 HDR.ID = DTL.TICKETID
 LEFT OUTER JOIN
 user USR ON 
 HDR.ENTEREDBY = USR.USERNAME
 WHERE 
 ID = __TICKETID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateSupportTicketAttachment` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `CreateSupportTicketAttachment`(__TICKETID INT, __MESSAGEID INT, __STORENAME VARCHAR(200), __FILENAME VARCHAR(200))
BEGIN

INSERT INTO ticketAttachment (TICKETID,MESSAGEID, STOREFILENAME,ORIGFILENAME)
VALUES (__TICKETID, __MESSAGEID, __STORENAME,__FILENAME);
	

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `CreateSupportTicketReply` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `CreateSupportTicketReply`(__TICKETID INT, __MESSAGE VARCHAR(1000), __ENTEREDBY VARCHAR(50))
BEGIN

DECLARE __TICCHECK INT;
 SELECT COUNT(*) INTO __TICCHECK FROM ticketHeader WHERE ( ENTEREDBY = __ENTEREDBY OR __ENTEREDBY IN (SELECT USERNAME FROM user WHERE USERLEVEL >= 81)) AND ID = __TICKETID;
 
 IF __TICCHECK > 0 THEN

		INSERT INTO
			ticketDetail
			(TICKETID,DATEENTERED,ENTEREDBY,CLIENTMESSAGE,MESSAGE)
		VALUES
			(
				__TICKETID,
				CURRENT_TIMESTAMP,
				__ENTEREDBY,
				CASE WHEN __ENTEREDBY IN (SELECT USERNAME FROM user WHERE USERLEVEL >= 81) THEN 0 ELSE 1 END,
				__MESSAGE
			);
            
		SELECT 
			HDR.*,
			DTL.MESSAGE,
			DTL.DATEENTERED AS RDATEENTERED,
			USR.FIRSTNAME,
			USR.LASTNAME,
			USR.EMAIL,
            USR.LANGUAGE,
			USR2.FIRSTNAME AS RFIRSTNAME, 
			USR2.LASTNAME AS RLASTNAME,
			USR2.EMAIL AS REMAIL            
		FROM 
			ticketHeader HDR 
		LEFT OUTER JOIN
			ticketDetail DTL ON 
				HDR.ID = DTL.TICKETID
		LEFT OUTER JOIN
			user USR ON 
				HDR.ENTEREDBY = USR.USERNAME
		LEFT OUTER JOIN
			user USR2 ON 
				DTL.ENTEREDBY = USR2.USERNAME                
		WHERE 
		ID = __TICKETID AND
        DTL.MESSAGEID = LAST_INSERT_ID();
        
	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteAdItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteAdItem`(__ID INT)
BEGIN
	DELETE FROM AdItems WHERE ID = __ID;
    DELETE FROM AdItemsBrand WHERE ID = __ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteAllBranchLinks` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteAllBranchLinks`(__ITEMID INT)
BEGIN
	DELETE FROM itemsBranchesLink WHERE ITEMID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteAllItemCategoryLinks` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteAllItemCategoryLinks`(__ITEMID INT)
BEGIN
	DELETE FROM itemsSubcategoryLink WHERE ITEMID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteAllPricingLinks` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteAllPricingLinks`(__ITEMID INT)
BEGIN
	DELETE FROM itemPricing WHERE ITEMID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteAllShipToAddressUserLinks` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `DeleteAllShipToAddressUserLinks`(__shipid INT)
BEGIN
	DELETE FROM shipToAddressesUserList WHERE ID = __shipid; 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteBranchAddress` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteBranchAddress`(__CODE VARCHAR(20), __LANG VARCHAR(2))
BEGIN
	DELETE FROM branchesAddresses WHERE CODE = __CODE AND LANGUAGE = __LANG;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteBranchProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteBranchProfile`(__CODE VARCHAR(20))
BEGIN
	DELETE FROM branches WHERE CODE = __CODE;
    DELETE FROM branchesAddresses WHERE CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteCategoryProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteCategoryProfile`(__CATID INTEGER)
BEGIN
	DELETE FROM categories WHERE CATID = __CATID;
    DELETE FROM subcategories WHERE CATID = __CATID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteItem`(__ITEMID INT)
BEGIN
  DELETE FROM items WHERE ID = __ITEMID;
    DELETE FROM itemPricing WHERE ITEMID = __ITEMID;
    DELETE FROM itemsBranchesLink WHERE ITEMID = __ITEMID;
    DELETE FROM itemsSubcategoryLink WHERE ITEMID = __ITEMID;
    DELETE FROM itemsInventory WHERE ITEMID = __ITEMID;
    DELETE FROM itemsPrintDefinition WHERE ID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteNewsItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteNewsItem`(__ID INTEGER)
BEGIN
	DELETE FROM newsItems WHERE ID = __ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeletePromoCategories` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `DeletePromoCategories`(__CODE VARCHAR(50))
BEGIN
  DELETE FROM promosCategories WHERE CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeletePromoItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeletePromoItems`(__CODE VARCHAR(50))
BEGIN
	DELETE FROM promosItems WHERE CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeletePromoProfile` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `DeletePromoProfile`(__CODE VARCHAR(50))
BEGIN
  DELETE FROM promosCategories WHERE CODE = __CODE;
    DELETE FROM promosItems WHERE CODE = __CODE;
  DELETE FROM promos WHERE CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteShipToAddress` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `DeleteShipToAddress`(__ID INT)
BEGIN

DELETE FROM shipToAddressesUserList WHERE ID = __ID;
DELETE FROM shipToAddresses WHERE ID = __ID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteSubCategoryProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteSubCategoryProfile`(__SUBCATID INTEGER)
BEGIN
	DELETE FROM subcategories WHERE SUBCATID = __SUBCATID;
    DELETE FROM subcategories WHERE PARENTSUBCATID = __SUBCATID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DeleteUserProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DeleteUserProfile`(UNAME VARCHAR(100))
BEGIN

DELETE FROM user WHERE USERNAME = UNAME;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DuplicateBranchProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DuplicateBranchProfile`(__CODE VARCHAR(20), __NEWCODE VARCHAR(20))
BEGIN

	INSERT INTO
		branches
        (CODE,NAME,MANAGEMENTEMAIL,TREASUREREMAIL,TAXGROUP,STATUS,COMMENTS,CREATEDDATE,MODIFIEDDATE,SHIPZONE)
	SELECT
		__NEWCODE AS CODE,
        NAME,
        MANAGEMENTEMAIL,
        TREASUREREMAIL,
        TAXGROUP,
        STATUS,
        COMMENTS,
        CURRENT_TIMESTAMP AS CREATEDDATE,
        CURRENT_TIMESTAMP AS MODIFIEDDATE,
        SHIPZONE
	FROM
		branches
	WHERE
		CODE = __CODE;
        
	INSERT INTO
		branchesAddresses
        (CODE,LANGUAGE,ISMAIN,ADDRESS,CITY,PROVINCE,COUNTRY,POSTALCODE,PHONE,FAX)
	SELECT
		__NEWCODE AS CODE,
        LANGUAGE,
        ISMAIN,
        ADDRESS,
        CITY,
        PROVINCE,
        COUNTRY,
        POSTALCODE,
        PHONE,
        FAX
	FROM
		branchesAddresses
	WHERE
		CODE = __CODE;

	INSERT INTO
		branchesAssetData
        (BRANCHCODE,TAG,VALUE)
    SELECT
		__NEWCODE AS BRANCHCODE,
        TAG,
        VALUE
	FROM
		branchesAssetData
	WHERE
		BRANCHCODE = __CODE;

	INSERT INTO
		itemsBranchesLink
        (ITEMID,BRANCHCODE)
	SELECT
		ITEMID,
        __NEWCODE AS BRANCHCODE
	FROM
		itemsBranchesLink
	WHERE
		BRANCHCODE = __CODE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DuplicateCategoryProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DuplicateCategoryProfile`(__CATID INT)
BEGIN

INSERT INTO
	categories
	(NAME,DESCRIPTION,ICONURL,LANGUAGE,USERLEVEL,COMMENTS,CREATEDDATE,MODIFIEDDATE)
SELECT
	CONCAT(NAME,' **DUP**') AS NAME,
    DESCRIPTION,
    ICONURL,
    LANGUAGE,
    USERLEVEL,
    COMMENTS,
    CURRENT_TIMESTAMP AS CREATEDDATE,
    CURRENT_TIMESTAMP AS MODIFIEDDATE
FROM
	categories
WHERE
	CATID = __CATID;
    
SET @CATID = LAST_INSERT_ID();    
   
INSERT INTO categoriesBrand (CATID,BRANDNAME)
SELECT @CATID,BRANDNAME FROM categoriesBrand WHERE CATID = __CATID;
    
SELECT @CATID AS CATID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DuplicateItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DuplicateItem`(__ITEMID INT)
BEGIN

  INSERT INTO
    items
        (TYPE,CODE,DESCRIPTION,SIZE,NUMPAGES,STATUS,MINLEVEL,LEADTIME,PARENTITEM,
         ARCHIVED,GENERATEDBY,ASSETAPPROVED,SHIPBOXINSLEEVE,PRINTINGTYPE,STOCK) 
  SELECT
    TYPE,
        CONCAT(CODE,' **DUP**'), 
        DESCRIPTION,
        SIZE,
        NUMPAGES,
        STATUS,
        MINLEVEL,
        LEADTIME,
        PARENTITEM,
        ARCHIVED,
        GENERATEDBY,
        ASSETAPPROVED,
        SHIPBOXINSLEEVE,
        PRINTINGTYPE,
        STOCK
  FROM
    items
  WHERE
    ID = __ITEMID;
        
  SET @ITEMID = LAST_INSERT_ID();
 
  INSERT INTO
    itemPricing
        (ITEMID,QTY,PRICE,LENGTH,WIDTH,HEIGHT,WEIGHT,PIECES,ITEMOPTION)
  SELECT
    @ITEMID AS ITEMID,
        QTY,
        PRICE,
        LENGTH,
        WIDTH,
        HEIGHT,
        WEIGHT,
        PIECES,
        ITEMOPTION
  FROM
    itemPricing
  WHERE
    ITEMID = __ITEMID;
 
  INSERT INTO
    itemsBranchesLink
        (ITEMID,BRANCHCODE)
  SELECT
    @ITEMID AS ITEMID,
        BRANCHCODE
  FROM
    itemsBranchesLink
  WHERE
    ITEMID = __ITEMID;
        
  INSERT INTO
    itemsInventory
        (ITEMID,QTYONHAND)
  SELECT
    @ITEMID AS ITEMID,
        0 AS QTYONHAND
  FROM
    itemsInventory
  WHERE
    ITEMID = __ITEMID;
        
  INSERT INTO
    itemsSubcategoryLink
        (ITEMID,SUBCATID)
  SELECT
    @ITEMID AS ITEMID,
        SUBCATID
  FROM
    itemsSubcategoryLink
  WHERE
    ITEMID = __ITEMID;
        
  INSERT INTO
    itemsPrintDefinition
        (ID,PRESS,NUMPAGES,BLEEDS,COLOURS,FLATSIZE,FINISHSIZE,STOCK,PARENTSHEETSIZE,
         PRESSSHEETSIZE,NUMUP,LAYOUTORIENTATION,COATING,CONTOURCUT,LAMINATION,FINISHING,
         ACCESSORY,SPECIALINSTRUCTIONS,PACKAGELOCATION)
  SELECT
    @ITEMID AS ID,
        PRESS,NUMPAGES,BLEEDS,COLOURS,FLATSIZE,FINISHSIZE,STOCK,PARENTSHEETSIZE,
    PRESSSHEETSIZE,NUMUP,LAYOUTORIENTATION,COATING,CONTOURCUT,LAMINATION,FINISHING,
    ACCESSORY,SPECIALINSTRUCTIONS,PACKAGELOCATION
  FROM
    itemsPrintDefinition
  WHERE
    ID = __ITEMID;        
  
        
  SELECT @ITEMID AS ID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DuplicateShipToAddress` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `DuplicateShipToAddress`(__ID INT)
BEGIN

	INSERT INTO
		shipToAddresses
		(NAME,ADDRESS,CITY,PROVINCE,COUNTRY,POSTAL,PHONE,FAX,TAXGROUP,SHIPZONE)
	SELECT
		NAME,
        ADDRESS,
        CITY,
        PROVINCE,
        COUNTRY,
        POSTAL,
        PHONE,
        FAX,
        TAXGROUP,
        SHIPZONE
	FROM
		shipToAddresses
	WHERE
		ID = __ID;
        
	SELECT @SHIPID := LAST_INSERT_ID() AS ID;
    
    INSERT INTO 
		shipToAddressesUserList
        (ID,USERNAME)
	SELECT
		@SHIPID,
        USERNAME
	FROM
		shipToAddressesUserList
	WHERE
		ID = __ID;
    

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `DuplicateUserProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `DuplicateUserProfile`(__USERNAME VARCHAR(50), __NEWUSERNAME VARCHAR(50))
BEGIN

	INSERT INTO
		user
        (USERNAME,BRANCH,PASSWORD,PLAINPASSWORD,FIRSTNAME,LASTNAME,EMAIL,LANGUAGE,USERLEVEL,CREATEDDATE,MODIFIEDDATE,STATUS,COMMENTS)
	SELECT
		__NEWUSERNAME AS USERNAME,
        BRANCH,
        PASSWORD,
        PLAINPASSWORD,
        FIRSTNAME,
        LASTNAME,
        EMAIL,
        LANGUAGE,
        USERLEVEL,
        CURRENT_TIMESTAMP AS CREATEDDATE,
        CURRENT_TIMESTAMP AS MODIFIEDDATE,
        STATUS,
        COMMENTS
	FROM
		user
	WHERE
		USERNAME = __USERNAME;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ExpireDownloadLinks` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ExpireDownloadLinks`()
BEGIN

UPDATE
	orderDetail
SET
	DOWNLOADLINK = NULL
WHERE
	DOWNLOADLINK IS NOT NULL AND
    ORDERID IN (SELECT ORDERID FROM orderHeader WHERE ORDERDATE < DATE_ADD(CURRENT_TIMESTAMP,INTERVAL -30 DAY));



END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_branchAssetDefinition` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_branchAssetDefinition`()
BEGIN
	SELECT * FROM branchAssetDefinition;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_branches` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_branches`()
BEGIN
	SELECT
		*
	FROM
		branches;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_branchesAddresses` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_branchesAddresses`()
BEGIN
	SELECT
		*
	FROM
		branchesAddresses;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_branchesAssetData` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_branchesAssetData`()
BEGIN
	SELECT
		*
	FROM
		branchesAssetData;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_branchesFixtures` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `extractTableData_branchesFixtures`()
BEGIN
	SELECT * FROM branchesFixtures ORDER BY BRANCHCODE,FIXTURECODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_branchSkinDefinition` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_branchSkinDefinition`()
BEGIN

	SELECT
		*
	FROM
		branchSkinDefinition;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_campaign_fixtures` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `extractTableData_campaign_fixtures`()
BEGIN
	SELECT * FROM campaign_fixtures;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_categories` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_categories`()
BEGIN
	SELECT
		*
	FROM
		categories;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_itemPricing` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_itemPricing`()
BEGIN
SELECT * FROM itemPricing left outer join items on itemPricing.ITEMID = items.ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_items` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_items`()
BEGIN
SELECT
		*
	FROM
		items;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_itemsBranchesLink` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_itemsBranchesLink`()
BEGIN
SELECT
		*
	FROM
		itemsBranchesLink;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_itemsInventory` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_itemsInventory`()
BEGIN
SELECT
		*
	FROM
		itemsInventory;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_itemsPrintDefinition` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_itemsPrintDefinition`()
BEGIN 
  SELECT items.CODE, items.DESCRIPTION, itemsPrintDefinition.* from itemsPrintDefinition left join items on itemsPrintDefinition.ID = items.ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_itemsSubcategoryLink` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_itemsSubcategoryLink`()
BEGIN
SELECT
		*
	FROM
		itemsSubcategoryLink;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_newsItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_newsItems`()
BEGIN
SELECT
		*
	FROM
		newsItems;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_promos` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_promos`()
BEGIN
	SELECT * FROM promos;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_promosCategories` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `extractTableData_promosCategories`()
BEGIN
SELECT * FROM promosCategories;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_promosItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_promosItems`()
BEGIN
	SELECT * FROM promosItems;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_shipToAddresses` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_shipToAddresses`()
BEGIN
	SELECT
		*
	FROM
		shipToAddresses;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_shipToAddressesUserList` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `extractTableData_shipToAddressesUserList`()
BEGIN
SELECT * FROM shipToAddressesUserList;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_shipZoneCosts` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_shipZoneCosts`()
BEGIN
SELECT
		*
	FROM
		shipZoneCosts;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_subcategories` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_subcategories`()
BEGIN
SELECT
		*
	FROM
		subcategories;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_taxes` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_taxes`()
BEGIN
SELECT
		*
	FROM
		taxes;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extractTableData_user` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extractTableData_user`()
BEGIN
SELECT
		*
	FROM
		user;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `extract_TableData_branchAssetDefinition` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `extract_TableData_branchAssetDefinition`()
BEGIN
	SELECT * FROM branchAssetDefinition;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetAccountTicket` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetAccountTicket`(__TICKETID INT)
BEGIN

SELECT 
 HDR.*,
 DTL.*,
 USR.FIRSTNAME,
 USR.LASTNAME,
 UNIX_TIMESTAMP(DTL.DATEENTERED) AS UNIX_DATEENTERED 
FROM 
 accountMgrHeader HDR
LEFT OUTER JOIN
 accountMgrMessages DTL ON 
 HDR.ID = DTL.TICKETID
LEFT OUTER JOIN
user USR ON 
 DTL.ENTEREDBY = USR.USERNAME 
WHERE 
 ID = __TICKETID
ORDER BY
 DTL.DATEENTERED DESC;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetAccountTicketList` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetAccountTicketList`(__USERNAME VARCHAR(50))
BEGIN

	SELECT
		*,
        UNIX_TIMESTAMP(HDR.DATEENTERED) AS UNIX_DATEENTERED
	FROM
		accountMgrHeader HDR
	WHERE
		( HDR.STATUS = 1 OR (HDR.STATUS = 0 AND DATECLOSED >= DATE_ADD(NOW(), INTERVAL -14 DAY)) ) AND
        ( HDR.ENTEREDBY = __USERNAME OR __USERNAME IN (SELECT USERNAME FROM user WHERE USERLEVEL >= 99))
	ORDER BY
		HDR.STATUS DESC,
		HDR.DATEENTERED DESC;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetActiveAdItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetActiveAdItems`(__LANGUAGE VARCHAR(2), __SKIN VARCHAR(20))
BEGIN
	SELECT DISTINCT
		ADS.*
	FROM
		AdItems ADS
	INNER JOIN
		AdItemsBrand ADSBRAND ON 
			ADS.ID = ADSBRAND.ID
	WHERE
		(LANGUAGE = '--' OR LANGUAGE = __LANGUAGE) AND
        (ADSBRAND.BRANDNAME = 'ALL' OR ADSBRAND.BRANDNAME = __SKIN) AND
        CURRENT_TIMESTAMP >= STARTDATE AND CURRENT_TIMESTAMP <= ENDDATE
	ORDER BY
		COALESCE(SORTORDER,999);        
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetActiveNewsItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetActiveNewsItems`(__LANGUAGE VARCHAR(2))
BEGIN
	SELECT
		*
	FROM
		newsItems
	WHERE
		(LANGUAGE = '--' OR LANGUAGE = __LANGUAGE) AND
        CURRENT_TIMESTAMP >= STARTDATE AND CURRENT_TIMESTAMP <= ENDDATE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetAdBrandInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetAdBrandInformation`(__ID INT)
BEGIN

SELECT 
	BSD.SKINNAME AS BRANDNAME,
    CASE WHEN ADB.BRANDNAME IS NOT NULL THEN 1 ELSE 0 END AS SELECTED
FROM
	(
		SELECT SKINNAME FROM branchSkinDefinition UNION ALL
        SELECT 'ALL' UNION ALL
        SELECT ''
	) BSD
LEFT OUTER JOIN
	(SELECT * FROM AdItemsBrand WHERE ID = __ID ) ADB ON 
		BSD.SKINNAME = ADB.BRANDNAME
ORDER BY 
	BSD.SKINNAME;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetAdItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetAdItem`(__ID INT)
BEGIN
	SELECT * FROM AdItems WHERE ID = __ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetAllAdItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetAllAdItems`()
BEGIN
	SELECT 
		*
	FROM	
		AdItems;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetAllNewsItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetAllNewsItems`()
BEGIN
	SELECT
		*
	FROM
		newsItems;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetAllShipToAddresses` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetAllShipToAddresses`(__USEBRANCHES BOOLEAN, __USERNAME VARCHAR(30))
BEGIN

  SELECT
    RECTYPE,ID,NAME,ADDRESS,STOREID
  FROM
    (
  SELECT
    'S' AS RECTYPE,SADDR.ID, SADDR.NAME,SADDR.ADDRESS,CASE WHEN IFNULL(SADDR.STOREID,'') = '' THEN 'NA' ELSE STOREID END AS STOREID
  FROM
    shipToAddresses SADDR
  WHERE
    SADDR.ID IN (SELECT ID FROM shipToAddressesUserList WHERE USERNAME = '**ALL**' OR USERNAME = 'ALL' OR USERNAME = __USERNAME) 
        
  UNION ALL
    
    SELECT
    'B' AS RECTYPE,BRANCH.CODE,BRANCH.NAME,BADDR.ADDRESS,BRANCH.CODE AS STOREID
    FROM
    branches BRANCH
  INNER JOIN
    branchesAddresses BADDR ON 
      BRANCH.CODE = BADDR.CODE
  WHERE
    __USEBRANCHES = 1 AND
        BRANCH.STATUS = 1 AND
        BADDR.ISMAIN = 1
    ) ADDR
    ORDER BY
    NAME;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetAvailableShippingZones` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetAvailableShippingZones`()
BEGIN
	SELECT  * FROM shipZoneCosts LIMIT 1;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetBranchAddressInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetBranchAddressInformation`(__CODE VARCHAR(20))
BEGIN
	SELECT
		*
	FROM
		branchesAddresses
	WHERE
		CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetBranchAssets` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetBranchAssets`(__CODE VARCHAR(20))
BEGIN

	SELECT
		BAD.TAG,
        BAD.TYPE,
        BAD.NAME,
	IFNULL(BAD.VALIDATEPATTERN,'') AS VALIDATEPATTERN,
	IFNULL(BAD.VALIDATEERRORMSG,'') AS VALIDATEERRORMSG,
        IFNULL(BDATA.VALUE,'') AS VALUE
	FROM
		branchAssetDefinition BAD
	LEFT OUTER JOIN
		(SELECT * FROM branchesAssetData WHERE BRANCHCODE = __CODE) BDATA ON 
			BAD.TAG = BDATA.TAG
	ORDER BY
		BAD.DISPLAYORDER;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetBranchDropDown` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetBranchDropDown`()
BEGIN
	SELECT CODE,NAME FROM branches WHERE STATUS = 1 ORDER BY NAME;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetBranchInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetBranchInformation`(__CODE VARCHAR(20))
BEGIN
	SELECT * FROM branches WHERE CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetBranchProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetBranchProfile`(IN `__USERNAME` VARCHAR(50))
    NO SQL
SELECT
		BRANCH.NAME,
		BADDR.*
	FROM
		branches BRANCH
	INNER JOIN
		branchesAddresses BADDR ON 
			BRANCH.CODE = BADDR.CODE
	WHERE
		ISMAIN = 1 AND
		BRANCH.CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetCartCheckoutInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetCartCheckoutInformation`(__USERNAME VARCHAR(20))
BEGIN

SET SQL_SAFE_UPDATES = 0;

UPDATE
	orderHeader
SET
	ORDERDATE = CURRENT_TIMESTAMP,
    ORDERMODIFIED = CURRENT_TIMESTAMP,
    EXPDATE = DATE_ADD(CURRENT_TIMESTAMP,INTERVAL 8 DAY),
    TAXNAME1 = (SELECT TAXNAME1 FROM taxes TAXES  WHERE SHIPTAXGROUP = TAXES.TAXCODE),
    TAXNAME2 = (SELECT TAXNAME2 FROM taxes TAXES  WHERE SHIPTAXGROUP = TAXES.TAXCODE),
    TAXNAME3 = (SELECT TAXNAME3 FROM taxes TAXES  WHERE SHIPTAXGROUP = TAXES.TAXCODE),
    TAXNAME4 = (SELECT TAXNAME4 FROM taxes TAXES  WHERE SHIPTAXGROUP = TAXES.TAXCODE),
    TAXNAME5 = (SELECT TAXNAME5 FROM taxes TAXES  WHERE SHIPTAXGROUP = TAXES.TAXCODE),
    TAXRATE1 = (SELECT TAXRATE1 FROM taxes TAXES  WHERE SHIPTAXGROUP = TAXES.TAXCODE),
    TAXRATE2 = (SELECT TAXRATE2 FROM taxes TAXES  WHERE SHIPTAXGROUP = TAXES.TAXCODE),
    TAXRATE3 = (SELECT TAXRATE3 FROM taxes TAXES  WHERE SHIPTAXGROUP = TAXES.TAXCODE),
    TAXRATE4 = (SELECT TAXRATE4 FROM taxes TAXES  WHERE SHIPTAXGROUP = TAXES.TAXCODE),
    TAXRATE5 = (SELECT TAXRATE5 FROM taxes TAXES  WHERE SHIPTAXGROUP = TAXES.TAXCODE)
WHERE 
	USERNAME  = __USERNAME AND 
    ORDERSTATUS = 'CART';

UPDATE 
	orderDetail I 
INNER JOIN 
(
	SELECT
		DTL.ITEMLINE,
        DTL.EXTPRICE * HDR.TAXRATE1 AS TAXAMT1,
        DTL.EXTPRICE * HDR.TAXRATE2 AS TAXAMT2,
        DTL.EXTPRICE * HDR.TAXRATE3 AS TAXAMT3,
        DTL.EXTPRICE * HDR.TAXRATE4 AS TAXAMT4,
        DTL.EXTPRICE * HDR.TAXRATE5 AS TAXAMT5
	FROM
		orderHeader HDR
	INNER JOIN
		orderDetail DTL ON
			HDR.ORDERID = DTL.ORDERID
	WHERE
		USERNAME = __USERNAME AND 
		ORDERSTATUS = 'CART'		
) II ON 
	I.ITEMLINE = II.ITEMLINE
SET
	I.TAXAMT1 = II.TAXAMT1,
    I.TAXAMT2 = II.TAXAMT2,
    I.TAXAMT3 = II.TAXAMT3,
    I.TAXAMT4 = II.TAXAMT4,
    I.TAXAMT5 = II.TAXAMT5
;

SELECT
	HDR.*,
    DTL.*,
    ITEM.*,
    COALESCE(SGROUP.SGRPNAME,'') AS SGRPNAME,
    COALESCE(SGROUP.SGRPPIECES,1) AS SGRPPIECES,
    COALESCE(SGROUP.SGRPBOXTYPE,'') AS SGRPBOXTYPE,
    COALESCE(SGROUP.SGRPWEIGHTPIECE,1.0) AS SGRPWEIGHTPIECE
FROM
	orderHeader HDR
INNER JOIN
	orderDetail DTL ON 
		HDR.ORDERID = DTL.ORDERID
INNER JOIN
	items ITEM ON 
		DTL.ITEMID = ITEM.ID
LEFT OUTER JOIN
	shippingGroupItems SGROUPITEMS ON 
		ITEM.ID = SGROUPITEMS.ITEMID
LEFT OUTER JOIN 
	shippingGroup SGROUP ON 
		SGROUPITEMS.SGRPNAME = SGROUP.SGRPNAME
WHERE 
	USERNAME  = __USERNAME AND 
    ORDERSTATUS = 'CART';
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetCartDiscountCodes` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetCartDiscountCodes`(__ORDERID INT)
BEGIN
	SELECT * FROM orderPromos WHERE ORDERID = __ORDERID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetCartItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetCartItems`(__USERNAME NVARCHAR(20))
BEGIN

SELECT 
	DTL.*
FROM 
	orderHeader HDR
INNER JOIN
	orderDetail DTL ON 
		HDR.ORDERID = DTL.ORDERID
WHERE 
	USERNAME COLLATE utf8_unicode_ci = __USERNAME AND 
    ORDERSTATUS = 'CART';


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetCategoriesBySearchTerm` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetCategoriesBySearchTerm`(__TERM VARCHAR(50))
BEGIN

SELECT
  CATID,
    CONCAT(NAME, ' - ', DESCRIPTION) AS CATNAME
FROM
  categories
WHERE
  (
  NAME LIKE CONCAT('%',__TERM,'%') OR 
    DESCRIPTION LIKE CONCAT('%',__TERM,'%')
    ) 
ORDER BY 
  NAME,DESCRIPTION
LIMIT 20;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetCategoriesListByUsername` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetCategoriesListByUsername`(__USERNAME VARCHAR(50))
BEGIN
	SELECT
		CATS.*
	FROM
		categories CATS
	CROSS JOIN
		( SELECT * FROM user WHERE USERNAME = __USERNAME) USERS
	WHERE
		USERS.USERLEVEL >= CATS.USERLEVEL AND
        CATS.LANGUAGE IN (SELECT BADDR.LANGUAGE FROM user USERS INNER JOIN branchesAddresses BADDR ON USERS.BRANCH = BADDR.CODE  WHERE USERS.USERNAME = __USERNAME) AND
        CATS.CATID IN (
						SELECT CC.CATID 
						FROM categories CC 
                        INNER JOIN categoriesBrand CCC ON CC.CATID = CCC.CATID
                        INNER JOIN ( SELECT SKIN FROM branches BB INNER JOIN user UU ON BB.CODE = UU.BRANCH WHERE USERNAME = __USERNAME) UBS ON 
							(UBS.SKIN = CCC.BRANDNAME OR CCC.BRANDNAME = 'ALL')
                            )
	ORDER BY
		CATS.NAME
	;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetCategoryAndSubCatDropDown` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetCategoryAndSubCatDropDown`()
BEGIN
	SELECT
		SUBCATS.SUBCATID,
		CASE 
			WHEN SUBCATS_2.SUBCATID IS NOT NULL THEN CONCAT(CATS.NAME," - ", SUBCATS_2.NAME," - ",SUBCATS.NAME)
            ELSE CONCAT(CATS.NAME," - ",SUBCATS.NAME) 
		END AS  NAME
	FROM
		categories CATS
	INNER JOIN
		subcategories SUBCATS ON 
			CATS.CATID = SUBCATS.CATID
	LEFT OUTER JOIN
		subcategories SUBCATS_2 ON 
			SUBCATS.PARENTSUBCATID = SUBCATS_2.SUBCATID
	WHERE
		SUBCATS.SUBCATID NOT IN (SELECT DISTINCT PARENTSUBCATID FROM subcategories)
	ORDER BY
		CATS.NAME,
		SUBCATS_2.NAME,
        SUBCATS.NAME
	;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetCategoryBrandInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetCategoryBrandInformation`(__CATID INT)
BEGIN

SELECT 
	BSD.SKINNAME AS BRANDNAME,
    CASE WHEN CB.BRANDNAME IS NOT NULL THEN 1 ELSE 0 END AS SELECTED
FROM
	(
		SELECT SKINNAME FROM branchSkinDefinition UNION ALL
        SELECT 'ALL' UNION ALL
        SELECT ''
	) BSD
LEFT OUTER JOIN
	(SELECT * FROM categoriesBrand WHERE CATID = __CATID ) CB ON 
		BSD.SKINNAME = CB.BRANDNAME
ORDER BY 
	BSD.SKINNAME;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetCategoryInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetCategoryInformation`(__CATID INTEGER)
BEGIN
	SELECT * FROM categories WHERE CATID = __CATID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetCategoryItems` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetCategoryItems`(__USERNAME VARCHAR(50), __CATID INT, __SUBCATID INT)
BEGIN
    SELECT 
        CATS.NAME AS CATNAME,
        CATS.DESCRIPTION AS CATDESC,
        CASE WHEN ITEMS.TYPE = 2 THEN -99 ELSE SUBCATS.SUBCATID END AS SUBCATID,
        CASE WHEN ITEMS.TYPE = 2 THEN '{{!GENERATE!}}' ELSE SUBCATS.NAME END AS SUBCATNAME,
        CASE WHEN ITEMS.TYPE = 2 THEN CONCAT('{{!CUST_ART!}} ',SUBCATS.NAME) ELSE SUBCATS.DESCRIPTION END AS SUBCATDESC,
      SUBCATS.SUBCATID AS REALSUBCATID,
        ITEMS.ID AS ITEMID,
        ITEMS.CODE AS ITEMCODE,
        ITEMS.DESCRIPTION AS ITEMDESC,
        ITEMS.DISPLAYIMAGEPATH,
        ITEMS.PROOFPDFNAME,
        ITEMS.SIZE,
        ITEMS.NUMPAGES,
        ITEMS.MINLEVEL,
        ITEMS.STATUS,
        ITEMS.TYPE AS ITEMTYPE,
        COALESCE(ONORDERSTAT.TOTORDERQTY,0) AS ONORDER, 
        COALESCE(DATE(ONORDERSTAT.ORDERDATE),'') AS LASTORDERED,
        CASE WHEN ITEMS.TYPE = 3 THEN 1 WHEN BRANCHLINK.ITEMID IS NULL THEN 0 ELSE 1 END AS PARTOFBRANCH,
        COALESCE(ITEMINV.QTYONHAND,0) AS INSTOCK,
        ITEMS.ASSETAPPROVED
    FROM
        categories CATS
    LEFT OUTER JOIN
        subcategories SUBCATS ON 
            CATS.CATID = SUBCATS.CATID
    LEFT OUTER JOIN
        itemsSubcategoryLink SCTOI ON
            SCTOI.SUBCATID = SUBCATS.SUBCATID
    LEFT OUTER JOIN
        items ITEMS ON 
            ITEMS.ID = SCTOI.ITEMID
    LEFT OUTER JOIN
    
    (SELECT DISTINCT 
        ITEMID 
     FROM
        (
            SELECT 
                ITOB.ITEMID 
            FROM 
                user USERS 
            INNER JOIN 
                itemsBranchesLink ITOB ON USERS.BRANCH = ITOB.BRANCHCODE 
            WHERE 
                USERS.USERNAME = __USERNAME
                
            UNION ALL 
            SELECT ITOB.ITEMID FROM itemsBranchesLink ITOB WHERE ITOB.BRANCHCODE = 'ALL_BRANCHES'
            
            UNION ALL
            SELECT ITOB.ITEMID FROM user UU INNER JOIN branches BB ON UU.BRANCH = BB.CODE
            INNER JOIN itemsBranchesLink ITOB ON CONCAT('BRN_',BB.SKIN) = ITOB.BRANCHCODE 
            WHERE UU.USERNAME = __USERNAME
        ) LINKS
    )  BRANCHLINK ON 
            BRANCHLINK.ITEMID = ITEMS.ID
    LEFT OUTER JOIN
        (SELECT ITEMID, SUM(CASE WHEN ORDERQTY-SHIPTODATEQTY < 0 THEN 0 ELSE ORDERQTY-SHIPTODATEQTY END) AS TOTORDERQTY, MAX(ORDERDATE) AS ORDERDATE FROM orderHeader HDR INNER JOIN orderDetail DTL ON HDR.ORDERID = DTL.ORDERID WHERE ORDERSTATUS NOT IN ('WAITMA','CART', 'CANCELLED') GROUP BY ITEMID) ONORDERSTAT ON
            ONORDERSTAT.ITEMID = SCTOI.ITEMID  
    LEFT OUTER JOIN
        itemsInventory ITEMINV ON 
            ITEMS.ID = ITEMINV.ITEMID
    CROSS JOIN
        ( SELECT * FROM user WHERE USERNAME = __USERNAME) USERS                
    WHERE
        (__SUBCATID = -1 OR __SUBCATID = SUBCATS.SUBCATID OR __SUBCATID = SUBCATS.PARENTSUBCATID) AND
        CATS.CATID = __CATID AND
        IFNULL(ITEMS.ARCHIVED,0) = 0 AND
        (BRANCHLINK.ITEMID IS NOT NULL OR (ITEMS.TYPE = 3 AND __USERNAME IN (SELECT USERNAME FROM user WHERE USERLEVEL >= 99))) AND
        USERS.USERLEVEL >= CATS.USERLEVEL AND
        USERS.USERLEVEL >= SUBCATS.USERLEVEL 
    ORDER BY
        CASE WHEN ITEMS.TYPE = 2 THEN 1 ELSE 99 END, 
        SUBCATS.NAME,
        CASE WHEN PARENTITEM = 0 THEN 1 ELSE 99 END, 
        ITEMS.CODE
    ;
    



END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetCategorySubcategoryTiles` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetCategorySubcategoryTiles`(__USERNAME VARCHAR(50), __CATID INT)
BEGIN

    SELECT
        CATS.CATID,
        CATS.NAME AS CATNAME,
        CATS.DESCRIPTION AS CATDESC,
        SUBCATS.SUBCATID  AS SUBCATID,
        SUBCATS.NAME  AS SUBCATNAME,
        SUBCATS.DESCRIPTION  AS SUBCATDESC,
        SUBCATS.ICONURL AS SUBCATICONURL
    FROM
        categories CATS
    LEFT OUTER JOIN
        subcategories SUBCATS ON 
            CATS.CATID = SUBCATS.CATID  
    CROSS JOIN
        ( SELECT * FROM user WHERE USERNAME = __USERNAME) USERS            
    WHERE
        CATS.CATID = __CATID AND
        SUBCATS.PARENTSUBCATID = -1 AND
        USERS.USERLEVEL >= CATS.USERLEVEL AND
        USERS.USERLEVEL >= SUBCATS.USERLEVEL
    ORDER BY
        SUBCATS.NAME
    ;            

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetDownloadFileData` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetDownloadFileData`(__ID VARCHAR(200))
BEGIN
	SELECT * FROM ticketAttachment WHERE STOREFILENAME = __ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetDownloadItem` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetDownloadItem`(__DOWNLOADLINK VARCHAR(100))
BEGIN

SELECT
  ITEM.*,
    OH.USERNAME
FROM
  orderDetail OD
INNER JOIN
  items ITEM ON 
    ITEM.ID = OD.ITEMID
INNER JOIN 
  orderHeader OH ON OD.ORDERID = OH.ORDERID
WHERE
  OD.DOWNLOADLINK = __DOWNLOADLINK;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetDownloadLog` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetDownloadLog`()
BEGIN
	SELECT 
		LOG.*,
        ITEM.CODE AS ITEMCODE,
        ITEM.DESCRIPTION AS ITEMDESCRIPTION
	FROM
		downloadLog LOG
	INNER JOIN
		items ITEM ON 
			LOG.ITEMID = ITEM.ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetFaqBySearchTerm` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetFaqBySearchTerm`(__TERM VARCHAR(50),__LANG VARCHAR(2))
BEGIN

  SELECT 
    ID,
        CASE WHEN __LANG = 'EN' THEN NAMEEN ELSE NAMEFR END AS NAME 
  FROM
    faq 
  WHERE
    (
    ID = __TERM OR 
        ( __LANG = 'EN' AND NAMEEN LIKE CONCAT('%',__TERM,'%')) OR 
        ( __LANG = 'FR' AND NAMEFR LIKE CONCAT('%',__TERM,'%')) OR 
        ( __LANG = 'EN' AND CONTENTEN LIKE CONCAT('%',__TERM,'%')) OR 
        ( __LANG = 'FR' AND CONTENTFR LIKE CONCAT('%',__TERM,'%'))
    )
  ORDER BY 
    NAMEEN
  LIMIT 20;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetGeneratorBranchVariables` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetGeneratorBranchVariables`(__USERNAME VARCHAR(50))
BEGIN

SELECT
	'Param-BranchName' AS TAG,
    NAME AS TAGVALUE
FROM
	branches
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) 

UNION ALL

SELECT
	'Param-Address1' AS TAG,
    ADDRESS AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1
    
UNION ALL

SELECT
	'Param-Address1Ext' AS TAG,
    ADDRESS2 AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1    

UNION ALL

SELECT
	'Param-Address2' AS TAG,
    CONCAT(CITY,', ',PROVINCE,', ', COUNTRY, '  ', POSTALCODE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1

UNION ALL

SELECT
	'Param-City' AS TAG,
    CITY AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1
   
UNION ALL
   
SELECT
	'Param-Prov' AS TAG,
    PROVINCE AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1   
    
UNION ALL
   
SELECT
	'Param-Country' AS TAG,
    COUNTRY AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1      

UNION ALL

SELECT
	'Param-CityProvPostal' AS TAG,
    CONCAT(CITY,', ',PROVINCE,' ', POSTALCODE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1
    
UNION ALL

SELECT
	'Param-CityProv' AS TAG,
    CONCAT(CITY,', ',PROVINCE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1 
    
UNION ALL

SELECT
	'Param-Postal' AS TAG,
    POSTALCODE AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1      

UNION ALL

SELECT
	'Param-AddressAll' AS TAG,
    CONCAT(ADDRESS, ', ', CITY,', ',PROVINCE, '  ', POSTALCODE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1

UNION ALL

SELECT
	'Param-BranchPhone' AS TAG,
    PHONE AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1
    
UNION ALL

SELECT
	'Param-BranchFax' AS TAG,
    FAX AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    ISMAIN = 1    

UNION ALL
   
SELECT
	'Param-Address1EN' AS TAG,
    ADDRESS AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN'
    
UNION ALL
   
SELECT
	'Param-Address1ExtEN' AS TAG,
    ADDRESS2 AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN'    

UNION ALL

SELECT
	'Param-Address2EN' AS TAG,
    CONCAT(CITY,', ',PROVINCE,', ', COUNTRY, '  ', POSTALCODE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN' 
    
UNION ALL

SELECT
	'Param-AddressAllEN' AS TAG,
    CONCAT(ADDRESS, ', ', CITY,', ',PROVINCE, '  ', POSTALCODE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN' 

UNION ALL

SELECT
	'Param-CityEN' AS TAG,
    CITY AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN' 

UNION ALL
   
SELECT
	'Param-ProvEN' AS TAG,
    PROVINCE AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN'   
    
UNION ALL
   
SELECT
	'Param-CountryEN' AS TAG,
    COUNTRY AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN'   

UNION ALL

SELECT
	'Param-CityProvPostalEN' AS TAG,
    CONCAT(CITY,', ',PROVINCE,' ', POSTALCODE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN' 
    
UNION ALL

SELECT
	'Param-CityProvEN' AS TAG,
    CONCAT(CITY,', ',PROVINCE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN'   
    
UNION ALL

SELECT
	'Param-PostalEN' AS TAG,
    POSTALCODE AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN'      

UNION ALL

SELECT
	'Param-BranchPhoneEN' AS TAG,
    PHONE AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN'
    
UNION ALL

SELECT
	'Param-BranchFaxEN' AS TAG,
    FAX AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'EN'    

UNION ALL
   
SELECT
	'Param-Address1FR' AS TAG,
    ADDRESS AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'
    
UNION ALL
   
SELECT
	'Param-Address1ExtFR' AS TAG,
    ADDRESS2 AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'    

UNION ALL

SELECT
	'Param-Address2FR' AS TAG,
    CONCAT(CITY,', ',PROVINCE,', ', COUNTRY, '  ', POSTALCODE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'    
    
UNION ALL

SELECT
	'Param-AddressAllFR' AS TAG,
    CONCAT(ADDRESS, ', ', CITY,', ',PROVINCE, '  ', POSTALCODE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'     
 
UNION ALL

SELECT
	'Param-CityFR' AS TAG,
    CITY AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'  

UNION ALL
   
SELECT
	'Param-ProvFR' AS TAG,
    PROVINCE AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'   
    
UNION ALL
   
SELECT
	'Param-CountryFR' AS TAG,
    COUNTRY AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'   
 
UNION ALL

SELECT
	'Param-CityProvPostalFR' AS TAG,
    CONCAT(CITY,', ',PROVINCE,' ', POSTALCODE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR' 
    
UNION ALL

SELECT
	'Param-CityProvFR' AS TAG,
    CONCAT(CITY,', ',PROVINCE) AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'  
    
UNION ALL

SELECT
	'Param-PostalFR' AS TAG,
    POSTALCODE AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'       
    
UNION ALL

SELECT
	'Param-BranchPhoneFR' AS TAG,
    PHONE AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'
    
UNION ALL

SELECT
	'Param-BranchFaxFR' AS TAG,
    FAX AS TAGVALUE
FROM
	branchesAddresses
WHERE
	CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME) AND
    LANGUAGE = 'FR'    

UNION ALL

SELECT
	CONCAT('Param-',TAG) AS TAG,
	VALUE
FROM
	branchesAssetData
WHERE
	BRANCHCODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME);


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetInventoryData` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetInventoryData`(__INVTYPE INT)
BEGIN

IF __INVTYPE = 1 THEN
	
	SELECT
		ITEMS.ID,
        ITEMS.CODE,
        ITEMS.DESCRIPTION,
        COALESCE(INV.QTYONHAND,0) AS STOCK,
        COALESCE(ONORDERSTAT.TOTORDERQTY,0) AS ONORDER, 
        ITEMS.MINLEVEL,
        COALESCE(DATE(ONORDERSTAT.ORDERDATE),'') AS LASTORDERED,
        COALESCE(DATE(SHIPSTAT.SHIPDATE),'') AS LASTSHIPPED,
        COALESCE(SUBCATNAME.NAME,'') AS L2CAT,
		COALESCE(SUBCATNAME1.NAME,'') AS L1CAT,
		COALESCE(CAT1.NAME,'') AS L0CAT        
	FROM
		items ITEMS
	LEFT OUTER JOIN
		itemsInventory INV ON 
			ITEMS.ID = INV.ITEMID
	LEFT OUTER JOIN
		(SELECT ITEMID, SUM(ORDERQTY-SHIPTODATEQTY) AS TOTORDERQTY, MAX(ORDERDATE) AS ORDERDATE FROM orderHeader HDR INNER JOIN orderDetail DTL ON HDR.ORDERID = DTL.ORDERID WHERE ORDERSTATUS NOT IN ('WAITMA','CART') GROUP BY ITEMID) ONORDERSTAT ON
			ONORDERSTAT.ITEMID = ITEMS.ID
	LEFT OUTER JOIN
		(SELECT ITEMID, MAX(SHIPDATE) AS SHIPDATE FROM orderHeader HDR INNER JOIN orderDetail DTL ON HDR.ORDERID = DTL.ORDERID INNER JOIN shipmentDetail SDTL ON DTL.ORDERID = SDTL.ORDERID AND DTL.ITEMLINE = SDTL.ORDERLINE INNER JOIN shipmentHeader SHDR ON SDTL.SHIPID = SHDR.SHIPID WHERE ORDERSTATUS NOT IN ('WAITMA','CART') GROUP BY ITEMID) SHIPSTAT ON
			SHIPSTAT.ITEMID = ITEMS.ID   
	LEFT OUTER JOIN 
		(SELECT ITEMID,MIN(SUBCATID) AS SUBCATID FROM itemsSubcategoryLink GROUP BY ITEMID) SUBCAT ON 
			ITEMS.ID = SUBCAT.ITEMID
	LEFT OUTER JOIN 
		subcategories SUBCATNAME ON 
			SUBCAT.SUBCATID = SUBCATNAME.SUBCATID
	LEFT OUTER JOIN 
		subcategories SUBCATNAME1 ON 
			SUBCATNAME.PARENTSUBCATID = SUBCATNAME1.SUBCATID            
	LEFT OUTER JOIN 
		categories CAT1 ON 
			SUBCATNAME.CATID = CAT1.CATID 
	;
	
ELSEIF __INVTYPE = 2 THEN 
	
	SELECT
		ITEMS.ID,
        ITEMS.CODE,
        ITEMS.DESCRIPTION,
        COALESCE(INV.QTYONHAND,0) AS STOCK,
        COALESCE(ONORDERSTAT.TOTORDERQTY,0) AS ONORDER, 
        ITEMS.MINLEVEL,
        COALESCE(DATE(ONORDERSTAT.ORDERDATE),'') AS LASTORDERED,
        COALESCE(DATE(SHIPSTAT.SHIPDATE),'') AS LASTSHIPPED,
        COALESCE(SUBCATNAME.NAME,'') AS L2CAT,
		COALESCE(SUBCATNAME1.NAME,'') AS L1CAT,
		COALESCE(CAT1.NAME,'') AS L0CAT        
	FROM
		items ITEMS
	INNER JOIN
		itemsInventory INV ON 
			ITEMS.ID = INV.ITEMID
	LEFT OUTER JOIN
		(SELECT ITEMID, SUM(ORDERQTY-SHIPTODATEQTY) AS TOTORDERQTY, MAX(ORDERDATE) AS ORDERDATE FROM orderHeader HDR INNER JOIN orderDetail DTL ON HDR.ORDERID = DTL.ORDERID WHERE ORDERSTATUS NOT IN ('WAITMA','CART') GROUP BY ITEMID) ONORDERSTAT ON
			ONORDERSTAT.ITEMID = ITEMS.ID 
	LEFT OUTER JOIN
		(SELECT ITEMID, MAX(SHIPDATE) AS SHIPDATE FROM orderHeader HDR INNER JOIN orderDetail DTL ON HDR.ORDERID = DTL.ORDERID INNER JOIN shipmentDetail SDTL ON DTL.ORDERID = SDTL.ORDERID AND DTL.ITEMLINE = SDTL.ORDERLINE INNER JOIN shipmentHeader SHDR ON SDTL.SHIPID = SHDR.SHIPID WHERE ORDERSTATUS NOT IN ('WAITMA','CART') GROUP BY ITEMID) SHIPSTAT ON
			SHIPSTAT.ITEMID = ITEMS.ID
	LEFT OUTER JOIN 
		(SELECT ITEMID,MIN(SUBCATID) AS SUBCATID FROM itemsSubcategoryLink GROUP BY ITEMID) SUBCAT ON 
			ITEMS.ID = SUBCAT.ITEMID
	LEFT OUTER JOIN 
		subcategories SUBCATNAME ON 
			SUBCAT.SUBCATID = SUBCATNAME.SUBCATID
	LEFT OUTER JOIN 
		subcategories SUBCATNAME1 ON 
			SUBCATNAME.PARENTSUBCATID = SUBCATNAME1.SUBCATID            
	LEFT OUTER JOIN 
		categories CAT1 ON 
			SUBCATNAME.CATID = CAT1.CATID             
	WHERE 
		INV.QTYONHAND > 0;
        
        
ELSEIF __INVTYPE = 3 THEN
	
	SELECT
		ITEMS.ID,
        ITEMS.CODE,
        ITEMS.DESCRIPTION,
        COALESCE(INV.QTYONHAND,0) AS STOCK,
        COALESCE(ONORDERSTAT.TOTORDERQTY,0) AS ONORDER, 
        ITEMS.MINLEVEL,
        COALESCE(DATE(ONORDERSTAT.ORDERDATE),'') AS LASTORDERED,
        COALESCE(DATE(SHIPSTAT.SHIPDATE),'') AS LASTSHIPPED,
        COALESCE(SUBCATNAME.NAME,'') AS L2CAT,
		COALESCE(SUBCATNAME1.NAME,'') AS L1CAT,
		COALESCE(CAT1.NAME,'') AS L0CAT        
	FROM
		items ITEMS
	INNER JOIN
		itemsInventory INV ON 
			ITEMS.ID = INV.ITEMID
	LEFT OUTER JOIN
		(SELECT ITEMID, SUM(ORDERQTY-SHIPTODATEQTY) AS TOTORDERQTY, MAX(ORDERDATE) AS ORDERDATE FROM orderHeader HDR INNER JOIN orderDetail DTL ON HDR.ORDERID = DTL.ORDERID WHERE ORDERSTATUS NOT IN ('WAITMA','CART') GROUP BY ITEMID) ONORDERSTAT ON
			ONORDERSTAT.ITEMID = ITEMS.ID  
	LEFT OUTER JOIN
		(SELECT ITEMID, MAX(SHIPDATE) AS SHIPDATE FROM orderHeader HDR INNER JOIN orderDetail DTL ON HDR.ORDERID = DTL.ORDERID INNER JOIN shipmentDetail SDTL ON DTL.ORDERID = SDTL.ORDERID AND DTL.ITEMLINE = SDTL.ORDERLINE INNER JOIN shipmentHeader SHDR ON SDTL.SHIPID = SHDR.SHIPID WHERE ORDERSTATUS NOT IN ('WAITMA','CART') GROUP BY ITEMID) SHIPSTAT ON
			SHIPSTAT.ITEMID = ITEMS.ID
	LEFT OUTER JOIN 
		(SELECT ITEMID,MIN(SUBCATID) AS SUBCATID FROM itemsSubcategoryLink GROUP BY ITEMID) SUBCAT ON 
			ITEMS.ID = SUBCAT.ITEMID
	LEFT OUTER JOIN 
		subcategories SUBCATNAME ON 
			SUBCAT.SUBCATID = SUBCATNAME.SUBCATID
	LEFT OUTER JOIN 
		subcategories SUBCATNAME1 ON 
			SUBCATNAME.PARENTSUBCATID = SUBCATNAME1.SUBCATID            
	LEFT OUTER JOIN 
		categories CAT1 ON 
			SUBCATNAME.CATID = CAT1.CATID             
	WHERE 
		INV.QTYONHAND <= 0;

ELSE

	
	SELECT
		ITEMS.ID,
        ITEMS.CODE,
        ITEMS.DESCRIPTION,
        COALESCE(INV.QTYONHAND,0) AS STOCK,
        COALESCE(ONORDERSTAT.TOTORDERQTY,0) AS ONORDER, 
        ITEMS.MINLEVEL,
        COALESCE(DATE(ONORDERSTAT.ORDERDATE),'') AS LASTORDERED,
        COALESCE(DATE(SHIPSTAT.SHIPDATE),'') AS LASTSHIPPED,
        COALESCE(SUBCATNAME.NAME,'') AS L2CAT,
		COALESCE(SUBCATNAME1.NAME,'') AS L1CAT,
		COALESCE(CAT1.NAME,'') AS L0CAT        
	FROM
		items ITEMS
	INNER JOIN
		itemsInventory INV ON 
			ITEMS.ID = INV.ITEMID
	LEFT OUTER JOIN
		(SELECT ITEMID, SUM(ORDERQTY-SHIPTODATEQTY) AS TOTORDERQTY, MAX(ORDERDATE) AS ORDERDATE FROM orderHeader HDR INNER JOIN orderDetail DTL ON HDR.ORDERID = DTL.ORDERID WHERE ORDERSTATUS NOT IN ('WAITMA','CART') GROUP BY ITEMID) ONORDERSTAT ON
			ONORDERSTAT.ITEMID = ITEMS.ID   
	LEFT OUTER JOIN
		(SELECT ITEMID, MAX(SHIPDATE) AS SHIPDATE FROM orderHeader HDR INNER JOIN orderDetail DTL ON HDR.ORDERID = DTL.ORDERID INNER JOIN shipmentDetail SDTL ON DTL.ORDERID = SDTL.ORDERID AND DTL.ITEMLINE = SDTL.ORDERLINE INNER JOIN shipmentHeader SHDR ON SDTL.SHIPID = SHDR.SHIPID WHERE ORDERSTATUS NOT IN ('WAITMA','CART') GROUP BY ITEMID) SHIPSTAT ON
			SHIPSTAT.ITEMID = ITEMS.ID 
	LEFT OUTER JOIN 
		(SELECT ITEMID,MIN(SUBCATID) AS SUBCATID FROM itemsSubcategoryLink GROUP BY ITEMID) SUBCAT ON 
			ITEMS.ID = SUBCAT.ITEMID
	LEFT OUTER JOIN 
		subcategories SUBCATNAME ON 
			SUBCAT.SUBCATID = SUBCATNAME.SUBCATID
	LEFT OUTER JOIN 
		subcategories SUBCATNAME1 ON 
			SUBCATNAME.PARENTSUBCATID = SUBCATNAME1.SUBCATID            
	LEFT OUTER JOIN 
		categories CAT1 ON 
			SUBCATNAME.CATID = CAT1.CATID             
	WHERE 
		INV.QTYONHAND < ITEMS.MINLEVEL;

END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetInventoryMovementHistory` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetInventoryMovementHistory`(IN `__STARTDATE` DATE, IN `__ENDDATE` DATE)
BEGIN
	SELECT
		ITEM.ID,
        ITEM.CODE,
        ITEM.DESCRIPTION,
        LOG.ADJID,
        LOG.QTY,
        CAST(LOG.ADJDATE AS DATE) AS ADJDATE,
        LOG.REASON
	FROM
		items ITEM
	INNER JOIN
		itemsAdjustmentLog LOG ON 
			ITEM.ID = LOG.ITEMID
	WHERE
		LOG.ADJDATE BETWEEN __STARTDATE AND DATE_ADD(__ENDDATE,INTERVAL 1 DAY) AND
            ITEM.TYPE = 0
	ORDER BY
		ITEM.ID,
        LOG.ADJDATE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetItemBranches` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetItemBranches`(__ITEMID INT)
BEGIN
	SELECT
		*
	FROM
		itemsBranchesLink
	WHERE
		ITEMID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetItemCategories` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetItemCategories`(__ITEMID INT)
BEGIN
	SELECT
		*
	FROM
		itemsSubcategoryLink
	WHERE
		ITEMID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetItemData` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetItemData`(__ITEMID INT)
BEGIN
	SELECT * FROM items WHERE ID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetItemDataByConfirmCode` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetItemDataByConfirmCode`(__CODE VARCHAR(200))
BEGIN
	SELECT * FROM items WHERE APPROVALLINK = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetItemPricing` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetItemPricing`(__ITEMID INT)
BEGIN


	SELECT
		*,
        ROUND((LENGTH*WIDTH*HEIGHT)/172 * PIECES,0) AS DIMWEIGHT
	FROM
		itemPricing
	WHERE
		ITEMID = __ITEMID
	ORDER BY 
		CASE WHEN QTY = -2 THEN 9999 ELSE QTY END;  
        
        
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetItemsBySearchTerm` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetItemsBySearchTerm`(__TERM VARCHAR(50))
BEGIN

SELECT
	ID,
    CONCAT(CODE, ' - ', DESCRIPTION) AS ITEMNAME
FROM
	items
WHERE
	(
	CODE LIKE CONCAT('%',__TERM,'%') OR 
    DESCRIPTION LIKE CONCAT('%',__TERM,'%')
    ) AND
    TYPE NOT IN (3)
ORDER BY 
	CODE,DESCRIPTION
LIMIT 20;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetItemZonePricing` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetItemZonePricing`(__ITEMID INT, __QTY INT, __BRANCH VARCHAR(20), __ITEMOPTION VARCHAR(30))
BEGIN

 SET @BRANCHZONE := (SELECT SHIPZONE FROM branches WHERE CODE = __BRANCH);
 SET @ITEMWEIGHT := (SELECT CASE WHEN ROUND((LENGTH*WIDTH*HEIGHT)/172 * PIECES,0) > WEIGHT THEN ROUND((LENGTH*WIDTH*HEIGHT)/172 * PIECES,0) ELSE WEIGHT END AS WEIGHT FROM itemPricing WHERE ITEMID = __ITEMID AND (QTY = __QTY OR QTY = -1 OR QTY = -2) AND ITEMOPTION = __ITEMOPTION ORDER BY QTY DESC LIMIT 1);

 SELECT
 @BRANCHZONE AS BRANCHZONE,
		ZONECOSTS.*
	FROM
		shipZoneCosts ZONECOSTS
	WHERE
		ZONECOSTS.WEIGHT <= @ITEMWEIGHT
	ORDER BY
		WEIGHT DESC;	

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetNewsItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetNewsItem`(__ID INTEGER)
BEGIN
	SELECT * FROM newsItems WHERE ID = __ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetOrderDataForShipment` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetOrderDataForShipment`(__ORDERID INT)
BEGIN
	SELECT
		HDR.*,
        DTL.*,
        ITEM.*,
        DATE(ORDERDATE) AS FMTORDERDATE,
        DATE(EXPDATE) AS FMTEXPDATE,
		USER.FIRSTNAME AS USER_FIRSTNAME,
		USER.LASTNAME AS USER_LASTNAME,
		USER.EMAIL AS USER_EMAIL,
		USER.LANGUAGE AS USER_LANGUAGE
	FROM
		orderHeader HDR
	INNER JOIN
		orderDetail DTL ON 
			HDR.ORDERID = DTL.ORDERID
	LEFT OUTER JOIN
		items ITEM ON 
			DTL.ITEMID = ITEM.ID
	INNER JOIN
		user USER ON 
			HDR.USERNAME = USER.USERNAME            
	WHERE 
		HDR.ORDERID = __ORDERID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetOrderInformationForEmail` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetOrderInformationForEmail`(__USERNAME VARCHAR(100), __ORDERID INT)
BEGIN

SELECT
	HDR.*,
    DTL.*,
    ITEM.TYPE,
    USER.FIRSTNAME AS USER_FIRSTNAME,
    USER.LASTNAME AS USER_LASTNAME,
    USER.EMAIL AS USER_EMAIL,
    USER.LANGUAGE AS USER_LANGUAGE,
    BRANCH.NAME AS BRANCH_NAME,
    BRANCH.MANAGEMENTEMAIL AS BRANCH_MANAGEMENTEMAIL,
    COALESCE(BRANCHADDRESS.LANGUAGE,'EN') AS BRANCH_LANGUAGE,
    ORDERSTATUS AS REALSTATUS
FROM
	orderHeader HDR
INNER JOIN
	orderDetail DTL ON 
		HDR.ORDERID = DTL.ORDERID
INNER JOIN
	items ITEM ON 
		DTL.ITEMID = ITEM.ID
INNER JOIN
	user USER ON 
		HDR.USERNAME = USER.USERNAME
INNER JOIN
	branches BRANCH ON 
		USER.BRANCH = BRANCH.CODE
LEFT OUTER JOIN
	(SELECT * FROM branchesAddresses WHERE ISMAIN = 1) BRANCHADDRESS ON 
		BRANCH.CODE = BRANCHADDRESS.CODE
WHERE 
	HDR.USERNAME = __USERNAME AND 
    HDR.ORDERID = __ORDERID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetPaypalPaymentInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetPaypalPaymentInformation`(__USERNAME VARCHAR(100))
BEGIN

SELECT
	HDR.ORDERID,
	SHIPCONTACTFIRSTNAME AS FIRSTNAME,
    SHIPCONTACTLASTNAME AS LASTNAME,
    SHIPCONTACTEMAIL AS EMAIL,
    SPECIALINSTRUCTIONS AS SPECINSTR,
    RECEIVERINSTRUCTIONS AS RECINSTR,
    SHIPPINGMETHOD AS SHIPPINGMETHOD,
    SHIPPINGCOST AS SHIPPINGCOST,
	SHIPNAME AS SHIPNAME,
    BILLINGCATEGORY AS BILLINGCATEGORY,
    PONUMBER AS PONUMBER,
    ROUND(COALESCE(PROMODISC,0)+COALESCE(ITEMTOT,0)+SHIPPINGCOST+SHIPPINGCOSTTAXAMT1+SHIPPINGCOSTTAXAMT2+SHIPPINGCOSTTAXAMT3+SHIPPINGCOSTTAXAMT4+SHIPPINGCOSTTAXAMT5,2) AS AMT
FROM
	orderHeader HDR
INNER JOIN
	( SELECT ORDERID,SUM(EXTPRICE+TAXAMT1+TAXAMT2+TAXAMT3+TAXAMT4+TAXAMT5) AS ITEMTOT FROM orderDetail GROUP BY ORDERID) DTL ON 
		HDR.ORDERID = DTL.ORDERID
LEFT OUTER JOIN
	( SELECT ORDERID,SUM(CALCDISCOUNT+TAXAMT1+TAXAMT2+TAXAMT3+TAXAMT4+TAXAMT5) AS PROMODISC FROM 
      orderPromos GROUP BY ORDERID ) PROMOS ON 
		HDR.ORDERID = PROMOS.ORDERID
WHERE 
	USERNAME  = __USERNAME AND 
    ORDERSTATUS = 'CART';
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetPendingOrders` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetPendingOrders`(__USERNAME VARCHAR(20))
BEGIN

	SELECT
		HDR.*,
        CAST(HDR.ORDERDATE AS DATE) AS SHORTDATE,
        DTL.TOTAMT+HDR.SHIPPINGCOST+HDR.SHIPPINGCOSTTAXAMT1+HDR.SHIPPINGCOSTTAXAMT2+HDR.SHIPPINGCOSTTAXAMT3+HDR.SHIPPINGCOSTTAXAMT4+HDR.SHIPPINGCOSTTAXAMT5 AS ORDERAMOUNT
	FROM
		orderHeader HDR
	INNER JOIN
		(SELECT ORDERID, SUM(EXTPRICE+TAXAMT1+TAXAMT2+TAXAMT3+TAXAMT4+TAXAMT5) AS TOTAMT FROM orderDetail GROUP BY ORDERID) DTL ON 
			HDR.ORDERID = DTL.ORDERID
	WHERE
		USERNAME = __USERNAME AND
        ORDERSTATUS IN ('WAITMA');
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetPromoProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetPromoProfile`(__CODE VARCHAR(50))
BEGIN
	SELECT * FROM promos WHERE CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetPromoProfileCategories` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetPromoProfileCategories`(__CODE VARCHAR(50))
BEGIN

  SELECT
    PROMOS.CATID,
        CONCAT(CATS.NAME, ' - ', CATS.DESCRIPTION) AS CATNAME
  FROM
    promosCategories PROMOS
  INNER JOIN 
    categories CATS ON 
      PROMOS.CATID = CATS.CATID
  WHERE
    PROMOS.CODE = __CODE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetPromoProfileItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetPromoProfileItems`(__CODE VARCHAR(50))
BEGIN
	SELECT 
		PROMOS.ITEMID,
		CONCAT(ITEMS.CODE,' - ',DESCRIPTION) AS ITEMNAME
	FROM 
		promosItems PROMOS
	INNER JOIN 
		items ITEMS ON 
			PROMOS.ITEMID = ITEMS.ID
	WHERE 
		PROMOS.CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetSearchItems` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetSearchItems`(__USERNAME VARCHAR(50), __TERM NVARCHAR(200))
BEGIN
    SELECT DISTINCT
        ITEMS.ID AS ITEMID,
        ITEMS.CODE AS ITEMCODE,
        ITEMS.DESCRIPTION AS ITEMDESC,
        ITEMS.DISPLAYIMAGEPATH,
        ITEMS.PROOFPDFNAME,
        ITEMS.SIZE,
        ITEMS.NUMPAGES,
        ITEMS.MINLEVEL,
        ITEMS.STATUS,
        ITEMS.TYPE AS ITEMTYPE,
        COALESCE(ONORDERSTAT.TOTORDERQTY,0) AS ONORDER, 
        COALESCE(DATE(ONORDERSTAT.ORDERDATE),'') AS LASTORDERED,
        COALESCE(ITEMINV.QTYONHAND,0) AS INSTOCK,
        MIN(SUBCATS.CATID) AS CATID,
        MIN(SUBCATS.SUBCATID) AS SUBCATID
    FROM
        categories CATS
    LEFT OUTER JOIN
        subcategories SUBCATS ON 
            CATS.CATID = SUBCATS.CATID
    LEFT OUTER JOIN
        itemsSubcategoryLink SCTOI ON
            SCTOI.SUBCATID = SUBCATS.SUBCATID
    LEFT OUTER JOIN
        items ITEMS ON 
            ITEMS.ID = SCTOI.ITEMID
    LEFT OUTER JOIN
        (SELECT ITEMID, SUM(CASE WHEN ORDERQTY-SHIPTODATEQTY < 0 THEN 0 ELSE ORDERQTY-SHIPTODATEQTY END) AS TOTORDERQTY, MAX(ORDERDATE) AS ORDERDATE FROM orderHeader HDR INNER JOIN orderDetail DTL ON HDR.ORDERID = DTL.ORDERID WHERE ORDERSTATUS NOT IN ('WAITMA','CART','CANCELLED') GROUP BY ITEMID) ONORDERSTAT ON
            ONORDERSTAT.ITEMID = SCTOI.ITEMID  
    LEFT OUTER JOIN
        itemsInventory ITEMINV ON 
            ITEMS.ID = ITEMINV.ITEMID
    INNER JOIN 
        (SELECT DISTINCT 
            ITEMID 
         FROM
            (
                SELECT 
                    ITOB.ITEMID 
                FROM 
                    user USERS 
                INNER JOIN 
                    itemsBranchesLink ITOB ON USERS.BRANCH = ITOB.BRANCHCODE 
                WHERE 
                    USERS.USERNAME = __USERNAME
                    
                UNION ALL 
                SELECT ITOB.ITEMID FROM itemsBranchesLink ITOB WHERE ITOB.BRANCHCODE = 'ALL_BRANCHES'
                
                UNION ALL
                SELECT ITOB.ITEMID FROM user UU INNER JOIN branches BB ON UU.BRANCH = BB.CODE
                INNER JOIN itemsBranchesLink ITOB ON CONCAT('BRN_',BB.SKIN) = ITOB.BRANCHCODE 
                WHERE UU.USERNAME = __USERNAME                
            ) LINKS
        )  BRANCHLINK ON 
                BRANCHLINK.ITEMID = ITEMS.ID  
    CROSS JOIN
        ( SELECT * FROM user WHERE USERNAME = __USERNAME) USERS                        
    WHERE
        (
            ITEMS.CODE COLLATE utf8_unicode_ci LIKE CONCAT('%',__TERM,'%') OR 
            ITEMS.DESCRIPTION COLLATE utf8_unicode_ci LIKE CONCAT('%',__TERM,'%')
        ) AND 
        ITEMS.ARCHIVED = 0 AND
        ITEMS.ASSETAPPROVED = 1 AND
        CATS.CATID IN (
                        SELECT CC.CATID 
                        FROM categories CC 
                        INNER JOIN categoriesBrand CCC ON CC.CATID = CCC.CATID
                        INNER JOIN ( SELECT SKIN FROM branches BB INNER JOIN user UU ON BB.CODE = UU.BRANCH WHERE USERNAME COLLATE utf8_unicode_ci = __USERNAME) UBS ON 
                            (UBS.SKIN = CCC.BRANDNAME OR CCC.BRANDNAME = 'ALL')
                            ) AND
        CATS.USERLEVEL <= COALESCE((SELECT USERLEVEL FROM user WHERE USERNAME = __USERNAME LIMIT 1),0) AND
        USERS.USERLEVEL >= SUBCATS.USERLEVEL
    GROUP BY
        ITEMS.ID ,
        ITEMS.CODE ,
        ITEMS.DESCRIPTION ,
        ITEMS.DISPLAYIMAGEPATH,
        ITEMS.PROOFPDFNAME,
        ITEMS.SIZE,
        ITEMS.NUMPAGES,
        ITEMS.MINLEVEL,
        ITEMS.STATUS,
        ITEMS.TYPE ,
        COALESCE(ONORDERSTAT.TOTORDERQTY,0) , 
        COALESCE(DATE(ONORDERSTAT.ORDERDATE),'') ,
        COALESCE(ITEMINV.QTYONHAND,0) 
    ORDER BY
        ITEMS.CODE
    ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetSettingsValue` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetSettingsValue`(SETTING_KEY VARCHAR(100))
BEGIN
	SELECT 
		*
	FROM
		settings
	WHERE
		`KEY` = SETTING_KEY;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetShipmentInfo` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetShipmentInfo`(__SHIPID INT)
BEGIN

	SELECT
		SHIPHDR.*,
        SHIPDTL.*,
        ORDHDR.*,
        ORDDTL.*,
        ORDDTL.ORDERQTY - ORDDTL.SHIPTODATEQTY AS BOQTY,
		USER.EMAIL AS USER_EMAIL,
		USER.LANGUAGE AS USER_LANGUAGE,
		BRANCH.MANAGEMENTEMAIL AS BRANCH_MANAGEMENTEMAIL,
		COALESCE(BRANCHADDRESS.LANGUAGE,'EN') AS BRANCH_LANGUAGE,
        ITEM.TYPE
	FROM
		shipmentHeader SHIPHDR
	INNER JOIN
		shipmentDetail SHIPDTL ON
			SHIPHDR.SHIPID = SHIPDTL.SHIPID
	INNER JOIN
		orderDetail ORDDTL ON 
			SHIPDTL.ORDERID = ORDDTL.ORDERID AND
            SHIPDTL.ORDERLINE = ORDDTL.ITEMLINE
	INNER JOIN
		items ITEM ON 
			ORDDTL.ITEMID = ITEM.ID
	INNER JOIN
		orderHeader ORDHDR ON 
			SHIPHDR.ORDERID = ORDHDR.ORDERID 
	INNER JOIN
		user USER ON 
			ORDHDR.USERNAME = USER.USERNAME 
	INNER JOIN
		branches BRANCH ON 
			USER.BRANCH = BRANCH.CODE 
	LEFT OUTER JOIN
		(SELECT * FROM branchesAddresses WHERE ISMAIN = 1) BRANCHADDRESS ON 
			BRANCH.CODE = BRANCHADDRESS.CODE
	WHERE
		SHIPHDR.SHIPID = __SHIPID;            

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetShipToAddress` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetShipToAddress`(__ID VARCHAR(50), __USEBRANCHES BOOLEAN)
BEGIN
	SELECT
		NAME,ADDRESS,ADDRESS2,CITY,PROVINCE,COUNTRY,POSTAL,PHONE,FAX
	FROM
    (
	SELECT
		'S' AS RECTYPE,ID,NAME,ADDRESS,ADDRESS2,CITY,PROVINCE,COUNTRY,POSTAL,PHONE,FAX
	FROM
		shipToAddresses
        
	UNION ALL
    
    SELECT
		'B' AS RECTYPE,BRANCH.CODE,NAME,ADDRESS,ADDRESS2,CITY,PROVINCE,COUNTRY,POSTALCODE,PHONE,FAX
    FROM
		branches BRANCH
	INNER JOIN
		branchesAddresses BADDR ON 
			BRANCH.CODE = BADDR.CODE
	WHERE
		__USEBRANCHES = 1 AND
        BRANCH.STATUS = 1 AND
        BADDR.ISMAIN = 1
    ) ADDR
    WHERE
		CONCAT(ADDR.RECTYPE,'-',ADDR.ID) = __ID
    ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetShipToAddressInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetShipToAddressInformation`(__ID INT)
BEGIN

	SELECT
		*
	FROM
		shipToAddresses
	WHERE
		ID = __ID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetShipToAddressUsersList` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetShipToAddressUsersList`(__SHIPTOID INT)
BEGIN
	SELECT 
		USERS.USERNAME,
		USERS.FIRSTNAME,
		USERS.LASTNAME,
		CASE WHEN USERADDR.ID IS NOT NULL THEN 1 ELSE 0 END AS SELECTED
	FROM
		( SELECT 'ALL' AS USERNAME, 'All' AS FIRSTNAME, 'Users' AS LASTNAME UNION ALL
          SELECT USERNAME,FIRSTNAME,LASTNAME FROM user
        ) USERS 
	LEFT OUTER JOIN 
		(SELECT * FROM shipToAddressesUserList WHERE ID = __SHIPTOID) USERADDR ON 
			USERS.USERNAME = USERADDR.USERNAME
	ORDER BY 
		USERS.USERNAME;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetShipTosBySearchTerm` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetShipTosBySearchTerm`(__USEBRANCHES BOOLEAN, __TERM VARCHAR(50), __USERNAME VARCHAR(30))
BEGIN

	SELECT
		CONCAT(RECTYPE,'-',ID) AS ID,
        CONCAT(NAME, ' - ', ADDRESS) AS SHIPDESC
	FROM
    (
	SELECT
		'S' AS RECTYPE,
        ID, 
        NAME,
        ADDRESS,
        ADDRESS2,
        CITY,
        POSTAL AS POSTALCODE,        
        CASE WHEN IFNULL(STOREID,'') = '' THEN 'NA' ELSE STOREID END AS STOREID
	FROM
		shipToAddresses
	WHERE
		ID IN (SELECT ID FROM shipToAddressesUserList WHERE USERNAME = '**ALL**' OR USERNAME = __USERNAME) 
        
	UNION ALL
    
    SELECT
		'B' AS RECTYPE,
        BRANCH.CODE,
        BRANCH.NAME,
        BADDR.ADDRESS,
        BADDR.ADDRESS2,
        BADDR.CITY,
        BADDR.POSTALCODE,
        BRANCH.CODE AS STOREID
    FROM
		branches BRANCH
	INNER JOIN
		branchesAddresses BADDR ON 
			BRANCH.CODE = BADDR.CODE
	WHERE
		__USEBRANCHES = 1 AND
        BRANCH.STATUS = 1 AND
        BADDR.ISMAIN = 1
    ) ADDR
    WHERE
	(
	ADDR.NAME LIKE CONCAT('%',__TERM,'%') OR 
    ADDR.ADDRESS LIKE CONCAT('%',__TERM,'%') OR
    ADDR.ADDRESS2 LIKE CONCAT('%',__TERM,'%') OR
    ADDR.CITY LIKE CONCAT('%',__TERM,'%') OR
    ADDR.POSTALCODE LIKE CONCAT('%',__TERM,'%') OR 
    ADDR.STOREID LIKE CONCAT('%',__TERM,'%')
    ) 
    ORDER BY
		NAME;	

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetSkinOptions` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetSkinOptions`()
BEGIN
	SELECT
		*
	FROM
		branchSkinDefinition
	ORDER BY
		SKINNAME;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetSubCategoryInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetSubCategoryInformation`(__SUBCATID INTEGER)
BEGIN
	SELECT * FROM subcategories WHERE SUBCATID = __SUBCATID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetSupportTicketAttachments` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetSupportTicketAttachments`(__TICKETID INT)
BEGIN
	SELECT * FROM ticketAttachment WHERE TICKETID = __TICKETID ORDER BY
    ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetSupportTicketData` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetSupportTicketData`(__TICKETID INT, __USERNAME VARCHAR(50))
BEGIN

	SELECT
	HDR.TITLE,
	HDR.STATUS,
		DTL.*,
        USR.FIRSTNAME,
        USR.LASTNAME,
        UNIX_TIMESTAMP(DTL.DATEENTERED) AS UNIX_DATEENTERED
	FROM
		ticketHeader HDR
	INNER JOIN
		ticketDetail DTL ON 
			HDR.ID = DTL.TICKETID
	LEFT OUTER JOIN
		user USR ON 
			DTL.ENTEREDBY = USR.USERNAME
	WHERE
        ( HDR.ENTEREDBY = __USERNAME OR __USERNAME IN (SELECT USERNAME FROM user WHERE USERLEVEL >= 81)) AND
        ( DTL.TICKETID = __TICKETID )
	ORDER BY
		DTL.DATEENTERED DESC;
		

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetSupportTicketList` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `GetSupportTicketList`(__USERNAME VARCHAR(50))
BEGIN

	SELECT
		*,
        UNIX_TIMESTAMP(HDR.DATEENTERED) AS UNIX_DATEENTERED
	FROM
		ticketHeader HDR
	WHERE
		( HDR.STATUS = 1 OR (HDR.STATUS = 0 AND DATECLOSED >= DATE_ADD(NOW(), INTERVAL -14 DAY)) ) AND
        ( HDR.ENTEREDBY = __USERNAME OR __USERNAME IN (SELECT USERNAME FROM user WHERE USERLEVEL >= 81))
	ORDER BY
		HDR.STATUS DESC,
		HDR.DATEENTERED DESC;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetTaxRecords` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetTaxRecords`()
BEGIN
	SELECT * FROM taxes;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetUserBranchAssets` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetUserBranchAssets`(__CODE VARCHAR(20))
BEGIN
	SELECT
		BAD.TAG,
        BAD.TYPE,
        BAD.NAME,
	IFNULL(BAD.VALIDATEPATTERN,'') AS VALIDATEPATTERN,
	IFNULL(BAD.VALIDATEERRORMSG,'') AS VALIDATEERRORMSG,
        IFNULL(BDATA.VALUE,'') AS VALUE
	FROM
		branchAssetDefinition BAD
	LEFT OUTER JOIN
		(SELECT * FROM branchesAssetData WHERE BRANCHCODE = __CODE) BDATA ON 
			BAD.TAG = BDATA.TAG
	WHERE
		BAD.USERACCESSIBLE = 1
	ORDER BY
		BAD.DISPLAYORDER;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetUserInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetUserInformation`(UNAME VARCHAR(50))
BEGIN
	SELECT * FROM user WHERE USERNAME=UNAME;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `GetZoneCostByWeight` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetZoneCostByWeight`(__WEIGHT DECIMAL, __BRANCH VARCHAR(20))
BEGIN

	SELECT
		BRANCHZONE.SHIPZONE AS BRANCHZONE,
		ZONECOSTS.*
	FROM
		shipZoneCosts ZONECOSTS
	CROSS JOIN
		(SELECT SHIPZONE FROM branches WHERE CODE = __BRANCH) BRANCHZONE
	WHERE
		ZONECOSTS.WEIGHT <= __WEIGHT 
	ORDER BY
		WEIGHT DESC;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchAssetDefinitionDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchAssetDefinitionDelete`(__TAG VARCHAR(100))
BEGIN
	DELETE FROM branchAssetDefinition WHERE TAG = __TAG;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchAssetDefinitionInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchAssetDefinitionInsert`(__TAG VARCHAR(100), __TYPE VARCHAR(30), __NAME VARCHAR(100), __VALIDATEPATTERN VARCHAR(100), __DISPLAYORDER INT, __VALIDATEERRORMSG VARCHAR(100),__USERACCESSIBLE INT)
BEGIN
	INSERT INTO  
		branchAssetDefinition
        (TAG,TYPE,NAME,VALIDATEPATTERN,DISPLAYORDER,VALIDATEERRORMSG,USERACCESSIBLE)
	VALUES
		(__TAG,__TYPE,__NAME,__VALIDATEPATTERN,__DISPLAYORDER,__VALIDATEERRORMSG,__USERACCESSIBLE);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchAssetDefinitionUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchAssetDefinitionUpdate`(__TAG VARCHAR(100), __TYPE VARCHAR(30), __NAME VARCHAR(100), __VALIDATEPATTERN VARCHAR(100), __DISPLAYORDER INT, __VALIDATEERRORMSG VARCHAR(100),__USERACCESSIBLE INT   )
BEGIN

	UPDATE 
		branchAssetDefinition
	SET
		 TYPE = __TYPE, 
         NAME = __NAME,
         VALIDATEPATTERN = __VALIDATEPATTERN, 
         DISPLAYORDER = __DISPLAYORDER,
         VALIDATEERRORMSG = __VALIDATEERRORMSG,
         USERACCESSIBLE = __USERACCESSIBLE
    WHERE
		TAG = __TAG;
    

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchesAddressesInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchesAddressesInsert`(__CODE VARCHAR(20), __LANGUAGE VARCHAR(2), __ISMAIN INT, __ADDRESS VARCHAR(1000), __ADDRESS2 VARCHAR(1000), __CITY VARCHAR(100), __PROVINCE VARCHAR(100), __COUNTRY VARCHAR(100), __POSTALCODE VARCHAR(20), __PHONE VARCHAR(20), __FAX VARCHAR(20))
BEGIN

	INSERT INTO
		branchesAddresses
        (CODE,LANGUAGE,ISMAIN,ADDRESS,ADDRESS2,CITY,PROVINCE,COUNTRY,POSTALCODE,PHONE,FAX)
	VALUES
		(__CODE,__LANGUAGE,__ISMAIN,__ADDRESS,__ADDRESS2,__CITY,__PROVINCE,__COUNTRY,__POSTALCODE,__PHONE,__FAX);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchesAddressesUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchesAddressesUpdate`(__CODE VARCHAR(20), __LANGUAGE VARCHAR(2), __ISMAIN INT, __ADDRESS VARCHAR(1000), __ADDRESS2 VARCHAR(1000), __CITY VARCHAR(100), __PROVINCE VARCHAR(100), __COUNTRY VARCHAR(100), __POSTALCODE VARCHAR(20), __PHONE VARCHAR(20), __FAX VARCHAR(20))
BEGIN

UPDATE
	branchesAddresses
SET
    ISMAIN = __ISMAIN,
    ADDRESS = __ADDRESS,
    ADDRESS2 = __ADDRESS2,
    CITY = __CITY,
    PROVINCE = __PROVINCE,
    COUNTRY = __COUNTRY,
    POSTALCODE = __POSTALCODE,
    PHONE = __PHONE,
    FAX = __FAX
WHERE
	CODE = __CODE AND
    LANGUAGE = __LANGUAGE;


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchesAssetDataDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchesAssetDataDelete`(__CODE VARCHAR(20), __TAG VARCHAR(100))
BEGIN

	DELETE FROM branchesAssetData WHERE BRANCHCODE = __CODE AND TAG = __TAG;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchesAssetDataInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchesAssetDataInsert`(__CODE VARCHAR(20), __TAG VARCHAR(100), __VALUE VARCHAR(1000))
BEGIN

	INSERT INTO
		branchesAssetData
			(BRANCHCODE,TAG,VALUE)
	VALUES
			(__CODE,__TAG,__VALUE);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchesAssetDataUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchesAssetDataUpdate`(__CODE VARCHAR(20), __TAG VARCHAR(100), __VALUE VARCHAR(1000))
BEGIN

	UPDATE 
		branchesAssetData
	SET
		VALUE = __VALUE
	WHERE
		BRANCHCODE = __CODE AND
        TAG = __TAG;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchesDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchesDelete`(__CODE VARCHAR(20), __LANGUAGE VARCHAR(2))
BEGIN

	DELETE FROM branchesAddresses WHERE CODE = __CODE AND LANGUAGE = __LANGUAGE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchesInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchesInsert`(__CODE VARCHAR(20), __NAME VARCHAR(100), __MANAGEMENTEMAIL VARCHAR(100), __TREASUREREMAIL VARCHAR(100), __TAXGROUP VARCHAR(6), __SKIN VARCHAR(20), __STATUS INT, __COMMENTS VARCHAR(1000), __SHIPZONE VARCHAR(6))
BEGIN

	INSERT INTO
		branches
        (CODE,NAME,MANAGEMENTEMAIL,TREASUREREMAIL,TAXGROUP,SKIN,STATUS,COMMENTS,SHIPZONE)
	VALUES
		(__CODE,__NAME,__MANAGEMENTEMAIL,__TREASUREREMAIL,__TAXGROUP,__SKIN,__STATUS,__COMMENTS,__SHIPZONE);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchesUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchesUpdate`(__CODE VARCHAR(20), __NAME VARCHAR(100), __MANAGEMENTEMAIL VARCHAR(100), __TREASUREREMAIL VARCHAR(100), __TAXGROUP VARCHAR(6), __SKIN VARCHAR(20), __STATUS INT, __COMMENTS VARCHAR(1000), __SHIPZONE VARCHAR(6))
BEGIN

	UPDATE
		branches
	SET
		NAME = __NAME,
        MANAGEMENTEMAIL = __MANAGEMENTEMAIL,
        TREASUREREMAIL = __TREASUREREMAIL,
        TAXGROUP = __TAXGROUP,
        SKIN = __SKIN,
        STATUS = __STATUS,
        COMMENTS = __COMMENTS,
        SHIPZONE = __SHIPZONE
	WHERE
		CODE = __CODE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchSkinDefinitionDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchSkinDefinitionDelete`(__SKIN VARCHAR(20))
BEGIN
	DELETE FROM branchSkinDefinition WHERE SKINNAME = __SKIN;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchSkinDefinitionInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchSkinDefinitionInsert`(__SKIN VARCHAR(20), __STYLEFILE VARCHAR(45))
BEGIN
	INSERT INTO
		branchSkinDefinition (SKINNAME, STYLEFILENAME)
	VALUES
		(__SKIN,__STYLEFILE);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_BranchSkinDefinitionUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_BranchSkinDefinitionUpdate`(__SKIN VARCHAR(20), __STYLEFILE VARCHAR(45))
BEGIN
	UPDATE
		branchSkinDefinition
	SET
		STYLEFILENAME = __STYLEFILE
	WHERE
		SKINNAME = __SKIN;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CategoriesCheckCATID` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CategoriesCheckCATID`(__CATID INT)
BEGIN

	SELECT CATID FROM categories WHERE CATID = __CATID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CategoriesDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CategoriesDelete`(__CATID INT)
BEGIN

	DELETE FROM categories WHERE CATID = __CATID;
	DELETE FROM subcategories WHERE CATID = __CATID;
	DELETE FROM itemsSubcategoryLink WHERE 
		SUBCATID NOT IN (SELECT SUBCATID FROM subcategories);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CategoriesInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CategoriesInsert`(__CATID INT, __NAME VARCHAR(50), __DESCRIPTION VARCHAR(200), __ICONURL VARCHAR(200), __LANGUAGE VARCHAR(2), __USERLEVEL INT,__COMMENTS VARCHAR(1000))
BEGIN

	INSERT INTO
		categories
        (CATID,NAME,DESCRIPTION,ICONURL,LANGUAGE,USERLEVEL,COMMENTS,CREATEDDATE,MODIFIEDDATE)
	VALUES
		(__CATID,__NAME,__DESCRIPTION,__ICONURL,__LANGUAGE,__USERLEVEL,__COMMENTS,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CategoriesUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CategoriesUpdate`(__CATID INT, __NAME VARCHAR(50), __DESCRIPTION VARCHAR(200), __ICONURL VARCHAR(200), __LANGUAGE VARCHAR(2), __USERLEVEL INT,__COMMENTS VARCHAR(1000))
BEGIN

	UPDATE
		categories
	SET
		NAME = __NAME,
        DESCRIPTION = __DESCRIPTION,
        ICONURL = __ICONURL,
        LANGUAGE = __LANGUAGE,
        USERLEVEL = __USERLEVEL,
        COMMENTS = __COMMENTS,
        MODIFIEDDATE = CURRENT_TIMESTAMP
	WHERE
		CATID = __CATID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckBRANCHASSETTAG` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckBRANCHASSETTAG`(__TAG VARCHAR(100))
BEGIN
	SELECT * FROM branchAssetDefinition WHERE TAG = __TAG;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckBRANCHCODE` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckBRANCHCODE`(__CODE VARCHAR(20))
BEGIN

	SELECT
		CODE 
	FROM
		branches
	WHERE
		CODE = __CODE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckITEMID` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckITEMID`(__ITEMID INT)
BEGIN

	SELECT ID FROM items WHERE ID = __ITEMID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckNEWSID` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckNEWSID`(__NEWSID INT)
BEGIN

	SELECT ID FROM newsItems WHERE ID = __NEWSID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckPROMOCODE` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckPROMOCODE`(__CODE VARCHAR(50))
BEGIN
	SELECT * FROM promos WHERE CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckSHIPID` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckSHIPID`(__SHIPID INT)
BEGIN
	SELECT ID FROM shipToAddresses WHERE ID = __SHIPID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckSHIPTOUSER` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `importTableData_CheckSHIPTOUSER`(__shipid INT, __username VARCHAR(30))
BEGIN
	SELECT * FROM shipToAddressesUserList WHERE ID = __shipid AND USERNAME = __username;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckSHIPWEIGHT` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckSHIPWEIGHT`(__WEIGHT INT)
BEGIN

	SELECT WEIGHT FROM shipZoneCosts WHERE WEIGHT = __WEIGHT;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckSHIPZONE` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckSHIPZONE`(__SHIPZONE VARCHAR(6))
BEGIN

	SELECT 
		COLUMN_NAME 
	FROM 
		information_schema.COLUMNS 
	WHERE 
		TABLE_NAME = 'shipZoneCosts' AND 
        COLUMN_NAME COLLATE utf8_unicode_ci = __SHIPZONE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckSKINNAME` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckSKINNAME`(__SKIN VARCHAR(20))
BEGIN

	SELECT * FROM branchSkinDefinition WHERE SKINNAME = __SKIN;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckSUBCATID` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckSUBCATID`(__SUBCATID INT)
BEGIN
	SELECT SUBCATID FROM subcategories WHERE SUBCATID = __SUBCATID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckTAXGROUP` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckTAXGROUP`(__TAXGROUP VARCHAR(6))
BEGIN

	SELECT TAXCODE FROM taxes WHERE TAXCODE = __TAXGROUP;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_CheckUSERNAME` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_CheckUSERNAME`(__USERNAME VARCHAR(50))
BEGIN

	SELECT USERNAME FROM user WHERE USERNAME = __USERNAME;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ItemPricingDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ItemPricingDelete`(__ITEMID INT, __QTY INT, __ITEMOPTION VARCHAR(30))
BEGIN

 DELETE FROM itemPricing WHERE ITEMID = __ITEMID AND QTY = __QTY AND ITEMOPTION = __ITEMOPTION;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ItemPricingInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ItemPricingInsert`(__ITEMID INT, __QTY INT, __ITEMOPTION VARCHAR(30), __PRICE DECIMAL(19,4), __LENGTH DECIMAL(19,4), __WIDTH DECIMAL(19,4), __HEIGHT DECIMAL(19,4), __WEIGHT DECIMAL(19,6), __PIECES INT)
BEGIN

 INSERT INTO 
 itemPricing
 (ITEMID,QTY,PRICE,LENGTH,WIDTH,HEIGHT,WEIGHT,PIECES,ITEMOPTION)
 VALUES
 (__ITEMID,__QTY,__PRICE,__LENGTH,__WIDTH,__HEIGHT,__WEIGHT,__PIECES,__ITEMOPTION);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ItemPricingUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ItemPricingUpdate`(__ITEMID INT, __QTY INT, __ITEMOPTION VARCHAR(30), __PRICE DECIMAL(19,4),  __LENGTH DECIMAL(19,4), __WIDTH DECIMAL(19,4), __HEIGHT DECIMAL(19,4), __WEIGHT DECIMAL(19,6), __PIECES INT)
BEGIN

 UPDATE
		itemPricing
	SET
		PRICE = __PRICE,
        LENGTH = __LENGTH,
        WIDTH = __WIDTH,
        HEIGHT = __HEIGHT,
        WEIGHT = __WEIGHT,
        PIECES = __PIECES,
        ITEMOPTION = __ITEMOPTION
	WHERE
		ITEMID = __ITEMID AND
        QTY = __QTY AND
        ITEMOPTION = __ITEMOPTION;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ItemPrintDefinitionDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ItemPrintDefinitionDelete`(__ITEMID INT)
BEGIN
  DELETE FROM itemsPrintDefinition WHERE ID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ItemPrintDefinitionInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ItemPrintDefinitionInsert`(__ITEMID INT, __PRESS VARCHAR(100),__NUMPAGES VARCHAR(100),__BLEEDS INT, __COLOURS VARCHAR(100),
__FLATSIZE VARCHAR(100), __FINISHSIZE VARCHAR(100), __STOCK VARCHAR(100), __PARENTSHEETSIZE VARCHAR(100),
__PRESSSHEETSIZE VARCHAR(100), __NUMUP VARCHAR(100), __LAYOUTORIENTATION VARCHAR(100),
__COATING VARCHAR(100), __CONTOURCUT VARCHAR(100), __LAMINATION VARCHAR(100), __FINISHING VARCHAR(200),
__ACCESSORY VARCHAR(200), __SPECIALINSTRUCTIONS VARCHAR(200), __MEMO VARCHAR(200), __PACKAGELOCATION VARCHAR(200),
__OUT VARCHAR(100), __FINISHED VARCHAR(100), __OVERS VARCHAR(100), __GROSS VARCHAR(100))
BEGIN

INSERT INTO itemsPrintDefinition
	(ID,PRESS,NUMPAGES,BLEEDS,COLOURS,FLATSIZE,FINISHSIZE,STOCK,PARENTSHEETSIZE,
	 PRESSSHEETSIZE,NUMUP,LAYOUTORIENTATION,COATING,CONTOURCUT,LAMINATION,FINISHING,
	 ACCESSORY,SPECIALINSTRUCTIONS,MEMO,PACKAGELOCATION,`OUT`,FINISHED,OVERS,GROSS)
	VALUES 
	(__ITEMID,__PRESS,__NUMPAGES,__BLEEDS,__COLOURS,__FLATSIZE,__FINISHSIZE,__STOCK,__PARENTSHEETSIZE,
	 __PRESSSHEETSIZE,__NUMUP,__LAYOUTORIENTATION,__COATING,__CONTOURCUT,__LAMINATION,__FINISHING,
	 __ACCESSORY,__SPECIALINSTRUCTIONS,__MEMO,__PACKAGELOCATION,__OUT,__FINISHED,__OVERS,__GROSS);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ItemPrintDefinitionUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ItemPrintDefinitionUpdate`(__ITEMID INT, __PRESS VARCHAR(100),__NUMPAGES VARCHAR(100),__BLEEDS INT, __COLOURS VARCHAR(100),
__FLATSIZE VARCHAR(100), __FINISHSIZE VARCHAR(100), __STOCK VARCHAR(100), __PARENTSHEETSIZE VARCHAR(100),
__PRESSSHEETSIZE VARCHAR(100), __NUMUP VARCHAR(100), __LAYOUTORIENTATION VARCHAR(100),
__COATING VARCHAR(100), __CONTOURCUT VARCHAR(100), __LAMINATION VARCHAR(100), __FINISHING VARCHAR(200),
__ACCESSORY VARCHAR(200), __SPECIALINSTRUCTIONS VARCHAR(200), __MEMO VARCHAR(200), __PACKAGELOCATION VARCHAR(200),
__OUT VARCHAR(100), __FINISHED VARCHAR(100), __OVERS VARCHAR(100), __GROSS VARCHAR(100)
)
BEGIN
	UPDATE itemsPrintDefinition
	SET 
		PRESS = __PRESS,
		NUMPAGES = __NUMPAGES,
		BLEEDS = __BLEEDS,
		COLOURS = __COLOURS,
		FLATSIZE = __FLATSIZE,
		FINISHSIZE = __FINISHSIZE,
		STOCK = __STOCK,
		PARENTSHEETSIZE = __PARENTSHEETSIZE,
		PRESSSHEETSIZE = __PRESSSHEETSIZE,
		NUMUP = __NUMUP,
		LAYOUTORIENTATION = __LAYOUTORIENTATION,
		COATING = __COATING,
		CONTOURCUT = __CONTOURCUT,
		LAMINATION = __LAMINATION,
		FINISHING = __FINISHING,
		ACCESSORY = __ACCESSORY,
		SPECIALINSTRUCTIONS = __SPECIALINSTRUCTIONS,
        MEMO = __MEMO,
		PACKAGELOCATION = __PACKAGELOCATION,
        `OUT` = __OUT , 
        FINISHED = __FINISHED, 
        OVERS = __OVERS, 
        GROSS = __GROSS
	WHERE ID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_itemsBranchesLinkDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_itemsBranchesLinkDelete`(__ITEMID INT, __BRANCHCODE VARCHAR(20))
BEGIN

	DELETE FROM itemsBranchesLink WHERE ITEMID = __ITEMID AND BRANCHCODE = __BRANCHCODE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_itemsBranchesLinkInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_itemsBranchesLinkInsert`(__ITEMID INT, __BRANCHCODE VARCHAR(20))
BEGIN

	INSERT INTO 
		itemsBranchesLink
        (ITEMID,BRANCHCODE)
	VALUES
		(__ITEMID,__BRANCHCODE);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ItemsDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ItemsDelete`(__ID INT)
BEGIN

  DELETE FROM items WHERE ID = __ID;
    DELETE FROM itemPricing WHERE ITEMID = __ID;
    DELETE FROM itemsBranchesLink WHERE ITEMID = __ID;
  DELETE FROM itemsSubcategoryLink WHERE ITEMID = __ID;
  DELETE FROM itemsInventory WHERE ITEMID = __ID;
    DELETE FROM itemsPrintDefinition WHERE ID = __ID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ItemsInsert` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `importTableData_ItemsInsert`(__ID INT, __TYPE INT, __CODE VARCHAR(50),
__DESCRIPTION VARCHAR(200), __PRODUCEDETAIL VARCHAR(1000), __SIZE VARCHAR(50), __NUMPAGES INT, __STATUS INT, __MINLEVEL INT,
__LEADTIME INT, __DISPLAYIMAGENAME VARCHAR(200), __PROOFPDFNAME VARCHAR(200), __PARENTITEM INT,
__ARCHIVED INT, __GENERATEDBY VARCHAR(200), __ASSETAPPROVED INT, __PARAMETERSFILENAME VARCHAR(200),
__UPLOADDIR VARCHAR(200),__PREVIEWIMAGENAME VARCHAR(200), __SHIPBOXINSLEEVE INT, __SKIPPDFPERMISSIONCHECK INT, __DLSUGGESTIONS VARCHAR(1000))
BEGIN

DECLARE __DISPNAME VARCHAR(200) DEFAULT NULL;
DECLARE __PROOFNAME VARCHAR(200) DEFAULT NULL;
DECLARE __PREVIEWNAME VARCHAR(200) DEFAULT NULL;
DECLARE __PARAMETERSNAME VARCHAR(200) DEFAULT NULL;
DECLARE __DISPPATH VARCHAR(200) DEFAULT NULL;
DECLARE __PROOFPATH VARCHAR(200) DEFAULT NULL;
DECLARE __PREVIEWPATH VARCHAR(200) DEFAULT NULL;
DECLARE __PARAMETERSPATH VARCHAR(200) DEFAULT NULL;

IF LENGTH(__DISPLAYIMAGENAME) > 0 THEN
  SET __DISPNAME = __DISPLAYIMAGENAME;
    SET __DISPPATH = CONCAT(__UPLOADDIR,__DISPLAYIMAGENAME);
END IF;
IF LENGTH(__PROOFPDFNAME) > 0 THEN
  SET __PROOFNAME = __PROOFPDFNAME;
    SET __PROOFPATH = CONCAT(__UPLOADDIR,__PROOFPDFNAME);
END IF;
IF LENGTH(__PREVIEWIMAGENAME) > 0 THEN
  SET __PREVIEWNAME = __PREVIEWIMAGENAME;
    SET __PREVIEWPATH = CONCAT(__UPLOADDIR,__PREVIEWIMAGENAME);
END IF;
IF LENGTH(__PARAMETERSFILENAME) > 0 THEN
  SET __PARAMETERSNAME = __PARAMETERSFILENAME;
    SET __PARAMETERSPATH = CONCAT(__UPLOADDIR,__PARAMETERSFILENAME);
END IF;

INSERT
  items
    (ID,TYPE,CODE,DESCRIPTION,PRODUCEDETAIL,SIZE,NUMPAGES,STATUS,MINLEVEL,LEADTIME,DISPLAYIMAGENAME,
   DISPLAYIMAGEPATH,PROOFPDFNAME,PROOFPDFPATH,PARENTITEM,ARCHIVED,GENERATEDBY,
     ASSETAPPROVED,PARAMETERSFILENAME,PARAMETERSFILEPATH, PREVIEWIMAGENAME,PREVIEWIMAGEPATH,
     SHIPBOXINSLEEVE,SKIPPDFPERMISSIONCHECK,DLSUGGESTIONS)
VALUES
  (__ID,__TYPE,__CODE,__DESCRIPTION,__PRODUCEDETAIL,__SIZE,__NUMPAGES,__STATUS,__MINLEVEL,__LEADTIME,
     __DISPNAME,__DISPPATH,__PROOFNAME,__PROOFPATH,__PARENTITEM,__ARCHIVED,__GENERATEDBY,
     __ASSETAPPROVED,__PARAMETERSNAME,__PARAMETERSPATH, __PREVIEWNAME, __PREVIEWPATH,
     __SHIPBOXINSLEEVE,__SKIPPDFPERMISSIONCHECK,__DLSUGGESTIONS);
     
IF __TYPE = 0 THEN
  INSERT INTO 
    itemsInventory
    (ITEMID,QTYONHAND)
  VALUES (__ID,0);
END IF;     

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_itemsInventoryUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_itemsInventoryUpdate`(__ITEMID INT, __QTY INT)
BEGIN

	UPDATE itemsInventory 
    SET QTYONHAND = __QTY 
    WHERE 
		ITEMID = __ITEMID;
        
	INSERT INTO
		itemsAdjustmentLog
			(ITEMID,QTY,ADJDATE,REASON)
	SELECT
		ITEMID,
        __QTY,
        CURRENT_TIMESTAMP,
        'Import File, Set Value Absolutely'
	FROM
		itemsInventory
	WHERE
		ITEMID = __ITEMID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_itemsSubcategoryLinkDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_itemsSubcategoryLinkDelete`(__ITEMID INT, __SUBCATID INT)
BEGIN
	
    DELETE FROM itemsSubcategoryLink WHERE ITEMID = __ITEMID AND SUBCATID = __SUBCATID;
    
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_itemsSubcategoryLinkInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_itemsSubcategoryLinkInsert`(__ITEMID INT, __SUBCATID INT)
BEGIN
	
    INSERT INTO 
		itemsSubcategoryLink
        (ITEMID,SUBCATID)
	VALUES
		(__ITEMID,__SUBCATID);
       
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ItemsUpdate` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `importTableData_ItemsUpdate`(__ID INT, __TYPE INT, __CODE VARCHAR(50),
__DESCRIPTION VARCHAR(200), __PRODUCEDETAIL VARCHAR(1000), __SIZE VARCHAR(50), __NUMPAGES INT, __STATUS INT, __MINLEVEL INT,
__LEADTIME INT, __DISPLAYIMAGENAME VARCHAR(200), __PROOFPDFNAME VARCHAR(200), __PARENTITEM INT,
__ARCHIVED INT, __GENERATEDBY VARCHAR(200), __ASSETAPPROVED INT, __PARAMETERSFILENAME VARCHAR(200),
__UPLOADDIR VARCHAR(200), __PREVIEWIMAGENAME VARCHAR(200), __SHIPBOXINSLEEVE INT, __SKIPPDFPERMISSIONCHECK INT, __DLSUGGESTIONS VARCHAR(1000))
BEGIN

DECLARE __DISPNAME VARCHAR(200) DEFAULT NULL;
DECLARE __PROOFNAME VARCHAR(200) DEFAULT NULL;
DECLARE __PREVIEWNAME VARCHAR(200) DEFAULT NULL;
DECLARE __PARAMETERSNAME VARCHAR(200) DEFAULT NULL;
DECLARE __DISPPATH VARCHAR(200) DEFAULT NULL;
DECLARE __PROOFPATH VARCHAR(200) DEFAULT NULL;
DECLARE __PREVIEWPATH VARCHAR(200) DEFAULT NULL;
DECLARE __PARAMETERSPATH VARCHAR(200) DEFAULT NULL;

IF LENGTH(__DISPLAYIMAGENAME) > 0 THEN
  SET __DISPNAME = __DISPLAYIMAGENAME;
    SET __DISPPATH = CONCAT(__UPLOADDIR,__DISPLAYIMAGENAME);
END IF;
IF LENGTH(__PROOFPDFNAME) > 0 THEN
  SET __PROOFNAME = __PROOFPDFNAME;
    SET __PROOFPATH = CONCAT(__UPLOADDIR,__PROOFPDFNAME);
END IF;
IF LENGTH(__PREVIEWIMAGENAME) > 0 THEN
  SET __PREVIEWNAME = __PREVIEWIMAGENAME;
    SET __PREVIEWPATH = CONCAT(__UPLOADDIR,__PREVIEWIMAGENAME);
END IF;
IF LENGTH(__PARAMETERSFILENAME) > 0 THEN
  SET __PARAMETERSNAME = __PARAMETERSFILENAME;
    SET __PARAMETERSPATH = CONCAT(__UPLOADDIR,__PARAMETERSFILENAME);
END IF;

UPDATE
  items
SET
  CODE = __CODE,
    DESCRIPTION = __DESCRIPTION,
    PRODUCEDETAIL = __PRODUCEDETAIL,
    SIZE = __SIZE,
    NUMPAGES = __NUMPAGES,
    STATUS = __STATUS,
    MINLEVEL = __MINLEVEL,
    LEADTIME = __LEADTIME,
    DISPLAYIMAGENAME = __DISPNAME,
    DISPLAYIMAGEPATH = __DISPPATH,
    PROOFPDFNAME = __PROOFNAME,
    PROOFPDFPATH = __PROOFPATH,
    PREVIEWIMAGENAME = __PREVIEWNAME,
    PREVIEWIMAGEPATH = __PREVIEWPATH,    
    PARENTITEM = __PARENTITEM,
    ARCHIVED = __ARCHIVED,
    GENERATEDBY = __GENERATEDBY,
    ASSETAPPROVED = __ASSETAPPROVED,
    PARAMETERSFILENAME = __PARAMETERSNAME,
    PARAMETERSFILEPATH = __PARAMETERSPATH,
    SHIPBOXINSLEEVE = __SHIPBOXINSLEEVE,
    SKIPPDFPERMISSIONCHECK = __SKIPPDFPERMISSIONCHECK,
    DLSUGGESTIONS = __DLSUGGESTIONS
WHERE
  ID = __ID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_NewsDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_NewsDelete`(__NEWSID INT)
BEGIN

	DELETE FROM newsItems WHERE ID = __NEWSID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_NewsInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_NewsInsert`(__NEWSID INT, __STARTDATE DATE, __ENDDATE DATE,__LANGUAGE VARCHAR(2), __TITLE VARCHAR(1000), __MESSAGE VARCHAR(1000))
BEGIN

	INSERT INTO
		newsItems
        (ID,STARTDATE,ENDDATE,LANGUAGE,TITLE,MESSAGE)
	VALUES
		(__NEWSID,__STARTDATE,__ENDDATE,__LANGUAGE,__TITLE,__MESSAGE);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_NewsUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_NewsUpdate`(__NEWSID INT, __STARTDATE DATE, __ENDDATE DATE,__LANGUAGE VARCHAR(2), __TITLE VARCHAR(1000), __MESSAGE VARCHAR(1000))
BEGIN

	UPDATE
		newsItems
	SET
		STARTDATE = __STARTDATE,
        ENDDATE = __ENDDATE,
        LANGUAGE = __LANGUAGE,
        TITLE = __TITLE,
        MESSAGE = __MESSAGE
	WHERE
		ID = __NEWSID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_PromoDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_PromoDelete`(__CODE VARCHAR(50))
BEGIN
	DELETE FROM promos WHERE CODE = __CODE;
    DELETE FROM promosItems WHERE CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_PromoInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_PromoInsert`(__CODE VARCHAR(50), __NAME VARCHAR(100), __CODETYPE VARCHAR(8), __STARTDATE DATE, __ENDDATE DATE, __SINGLEUSE INT, __REDEEMED INT, __PROMOVALUE DECIMAL(19,2), __MAXQTY INT, __SINGLEITEM INT)
BEGIN
 INSERT INTO 
 promos
 (CODE,NAME,CODETYPE,STARTDATE,ENDDATE,SINGLEUSE,REDEEMED,PROMOVALUE,MAXQTY,SINGLEITEM)
 VALUES
 (__CODE, __NAME, __CODETYPE, __STARTDATE, __ENDDATE, __SINGLEUSE, __REDEEMED, __PROMOVALUE,__MAXQTY, __SINGLEITEM);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_PromoItemsDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_PromoItemsDelete`(__CODE VARCHAR(50), __ITEMID INT)
BEGIN
	DELETE FROM promosItems WHERE CODE = __CODE AND ITEMID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_PromoItemsInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_PromoItemsInsert`(__CODE VARCHAR(50), __ITEMID INT)
BEGIN
	INSERT INTO promosItems
    (CODE,ITEMID)
    VALUES
    (__CODE,__ITEMID);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_PromoItemsUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_PromoItemsUpdate`(__CODE VARCHAR(50), __ITEMID INT)
BEGIN
	UPDATE
		promosItems
	SET
		CODE = __CODE,
        ITEMID = __ITEMID
	WHERE
		CODE = __CODE AND
        ITEMID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_PromoUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_PromoUpdate`(__CODE VARCHAR(50), __NAME VARCHAR(100), __CODETYPE VARCHAR(8), __STARTDATE DATE, __ENDDATE DATE, __SINGLEUSE INT, __REDEEMED INT, __PROMOVALUE DECIMAL(19,2), __MAXQTY INT, __SINGLEITEM INT)
BEGIN
 UPDATE
 promos
 SET
 NAME = __NAME,
        CODETYPE = __CODETYPE,
        STARTDATE = __STARTDATE,
        ENDDATE = __ENDDATE,
        SINGLEUSE = __SINGLEUSE,
        REDEEMED = __REDEEMED,
        PROMOVALUE = __PROMOVALUE,
        MAXQTY = __MAXQTY,
        SINGLEITEM = __SINGLEITEM
	WHERE
		CODE = __CODE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ShippingCostsDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ShippingCostsDelete`(__WEIGHT INT)
BEGIN

	DELETE FROM shipZoneCosts WHERE WEIGHT = __WEIGHT;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ShippingCostsInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ShippingCostsInsert`(__WEIGHT INT, __NONE DECIMAL(16,2),
 __ZONE1 DECIMAL(16,2), __ZONE2 DECIMAL(16,2), __ZONE3 DECIMAL(16,2), __ZONE4 DECIMAL(16,2),
 __ZONE5 DECIMAL(16,2), __ZONE6 DECIMAL(16,2), __ZONE7 DECIMAL(16,2), __ZONE8 DECIMAL(16,2),
 __ZONE9 DECIMAL(16,2), __ZONE10 DECIMAL(16,2), __ZONE11 DECIMAL(16,2), __ZONE12 DECIMAL(16,2),
 __ZONE13 DECIMAL(16,2), __ZONE14 DECIMAL(16,2), __ZONE15 DECIMAL(16,2), __ZONE16 DECIMAL(16,2),
 __ZONE17 DECIMAL(16,2), __ZONE18 DECIMAL(16,2), __ZONE19 DECIMAL(16,2))
BEGIN

	INSERT INTO
		shipZoneCosts
        (WEIGHT,None,Zone1,Zone2,Zone3,Zone4,Zone5,Zone6,Zone7,Zone8,Zone9,Zone10,
         Zone11,Zone12,Zone13,Zone14,Zone15,Zone16,Zone17,Zone18,Zone19)
	VALUES
		(__WEIGHT,__NONE,__ZONE1,__ZONE2,__ZONE3,__ZONE4,__ZONE5,__ZONE6,__ZONE7,__ZONE8,
        __ZONE9,__ZONE10,__ZONE11,__ZONE12,__ZONE13,__ZONE14,__ZONE15,__ZONE16,__ZONE17,
        __ZONE18,__ZONE19);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ShippingCostsUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ShippingCostsUpdate`(__WEIGHT INT, __NONE DECIMAL(16,2),
 __ZONE1 DECIMAL(16,2), __ZONE2 DECIMAL(16,2), __ZONE3 DECIMAL(16,2), __ZONE4 DECIMAL(16,2),
 __ZONE5 DECIMAL(16,2), __ZONE6 DECIMAL(16,2), __ZONE7 DECIMAL(16,2), __ZONE8 DECIMAL(16,2),
 __ZONE9 DECIMAL(16,2), __ZONE10 DECIMAL(16,2), __ZONE11 DECIMAL(16,2), __ZONE12 DECIMAL(16,2),
 __ZONE13 DECIMAL(16,2), __ZONE14 DECIMAL(16,2), __ZONE15 DECIMAL(16,2), __ZONE16 DECIMAL(16,2),
 __ZONE17 DECIMAL(16,2), __ZONE18 DECIMAL(16,2), __ZONE19 DECIMAL(16,2))
BEGIN

	UPDATE
		shipZoneCosts
	SET
		None  = __NONE,
        Zone1 = __ZONE1,
        Zone2 = __ZONE2,
        Zone3 = __ZONE3,
        Zone4 = __ZONE4,
        Zone5 = __ZONE5,
        Zone6 = __ZONE6,
        Zone7 = __ZONE7,
        Zone8 = __ZONE8,
        Zone9 = __ZONE9,
        Zone10 = __ZONE10,
        Zone11 = __ZONE11,
        Zone12 = __ZONE12,
        Zone13 = __ZONE13,
        Zone14 = __ZONE14,
        Zone15 = __ZONE15,
        Zone16 = __ZONE16,
        Zone17 = __ZONE17,
        Zone18 = __ZONE18,
        Zone19 = __ZONE19
	WHERE
		WEIGHT = __WEIGHT;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ShipToDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ShipToDelete`(__SHIPID INT)
BEGIN

	DELETE FROM shipToAddresses WHERE ID = __SHIPID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ShipToInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ShipToInsert`(__SHIPID INT, __NAME VARCHAR(100), __STOREID VARCHAR(20), __ADDRESS VARCHAR(1000), __ADDRESS2 VARCHAR(1000), __CITY VARCHAR(100), __PROVINCE VARCHAR(100), __COUNTRY VARCHAR(100), __POSTAL VARCHAR(20), __PHONE VARCHAR(20), __FAX VARCHAR(20), __TAXGROUP VARCHAR(6), __SHIPZONE VARCHAR(6))
BEGIN

	INSERT INTO
		shipToAddresses
			(ID,NAME,STOREID,ADDRESS,ADDRESS2,CITY,PROVINCE,COUNTRY,POSTAL,PHONE,FAX,TAXGROUP,SHIPZONE)
	VALUES
		(__SHIPID,__NAME,__STOREID,__ADDRESS,__ADDRESS2,__CITY,__PROVINCE,__COUNTRY,__POSTAL,__PHONE,__FAX,__TAXGROUP,__SHIPZONE);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ShipToUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_ShipToUpdate`(__SHIPID INT, __NAME VARCHAR(100), __STOREID VARCHAR(20), __ADDRESS VARCHAR(1000), __ADDRESS2 VARCHAR(1000), __CITY VARCHAR(100), __PROVINCE VARCHAR(100), __COUNTRY VARCHAR(100), __POSTAL VARCHAR(20), __PHONE VARCHAR(20), __FAX VARCHAR(20), __TAXGROUP VARCHAR(6), __SHIPZONE VARCHAR(6))
BEGIN

	UPDATE
		shipToAddresses
	SET
		NAME = __NAME,
        STOREID = __STOREID,
        ADDRESS = __ADDRESS,
        ADDRESS2 = __ADDRESS2,
        CITY = __CITY,
        PROVINCE = __PROVINCE,
        COUNTRY = __COUNTRY,
        POSTAL = __POSTAL,
        PHONE = __PHONE,
        FAX = __FAX,
        TAXGROUP = __TAXGROUP,
        SHIPZONE = __SHIPZONE       
	WHERE
		ID = __SHIPID;


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ShipToUserListDelete` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `importTableData_ShipToUserListDelete`(__shipid INT, __username VARCHAR(30))
BEGIN
	DELETE FROM shipToAddressesUserList WHERE ID = __shipid AND USERNAME = __username; 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_ShipToUserListInsert` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `importTableData_ShipToUserListInsert`(__shipid INT, __username VARCHAR(30))
BEGIN
	INSERT INTO shipToAddressesUserList (ID,USERNAME) VALUES (__shipid,__username); 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_SubcategoriesDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_SubcategoriesDelete`(__SUBCATID INT)
BEGIN

	DELETE FROM subcategories WHERE SUBCATID = __SUBCATID;
	DELETE FROM itemsSubcategoryLink WHERE 
		SUBCATID NOT IN (SELECT SUBCATID FROM subcategories);    

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_SubcategoriesInsert` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `importTableData_SubcategoriesInsert`(__SUBCATID INT, __CATID INT, __PARENTSUBCATID INT, __NAME VARCHAR(50), __DESCRIPTION VARCHAR(200), __ICONURL VARCHAR(200), __USERLEVEL INT)
BEGIN

    INSERT INTO
        subcategories
        (SUBCATID,CATID,PARENTSUBCATID,NAME,DESCRIPTION,ICONURL,USERLEVEL)
    VALUES
        (__SUBCATID,__CATID,__PARENTSUBCATID,__NAME,__DESCRIPTION,__ICONURL,__USERLEVEL);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_SubcategoriesUpdate` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `importTableData_SubcategoriesUpdate`(__SUBCATID INT, __CATID INT, __NAME VARCHAR(50), __DESCRIPTION VARCHAR(200), __ICONURL VARCHAR(200), __USERLEVEL INT)
BEGIN

    UPDATE
        subcategories
    SET
        CATID = __CATID,
        NAME = __NAME,
        DESCRIPTION = __DESCRIPTION,
        ICONURL = __ICONURL,
        USERLEVEL = __USERLEVEL
    WHERE
        SUBCATID = __SUBCATID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_TaxesDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_TaxesDelete`(__TAXCODE VARCHAR(6))
BEGIN

	DELETE FROM taxes WHERE TAXCODE = __TAXCODE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_TaxesInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_TaxesInsert`(__TAXCODE VARCHAR(6), __TAXGROUPNAME VARCHAR(100), __TAXNAME1 VARCHAR(100), __TAXNAME2 VARCHAR(100), __TAXNAME3 VARCHAR(100), __TAXNAME4 VARCHAR(100), __TAXNAME5 VARCHAR(100), __TAXRATE1 DECIMAL(19,5), __TAXRATE2 DECIMAL(19,5), __TAXRATE3 DECIMAL(19,5), __TAXRATE4 DECIMAL(19,5), __TAXRATE5 DECIMAL(19,5))
BEGIN

	INSERT INTO 
		taxes
        (TAXCODE,TAXGROUPNAME,TAXNAME1,TAXNAME2,TAXNAME3,TAXNAME4,TAXNAME5,TAXRATE1,TAXRATE2,TAXRATE3,TAXRATE4,TAXRATE5)
	VALUES
		(__TAXCODE,__TAXGROUPNAME,__TAXNAME1,__TAXNAME2,__TAXNAME3,__TAXNAME4,__TAXNAME5,__TAXRATE1,__TAXRATE2,__TAXRATE3,__TAXRATE4,__TAXRATE5);
        
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_TaxesUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_TaxesUpdate`(__TAXCODE VARCHAR(6), __TAXGROUPNAME VARCHAR(100), __TAXNAME1 VARCHAR(100), __TAXNAME2 VARCHAR(100), __TAXNAME3 VARCHAR(100), __TAXNAME4 VARCHAR(100), __TAXNAME5 VARCHAR(100), __TAXRATE1 DECIMAL(19,5), __TAXRATE2 DECIMAL(19,5), __TAXRATE3 DECIMAL(19,5), __TAXRATE4 DECIMAL(19,5), __TAXRATE5 DECIMAL(19,5))
BEGIN

	UPDATE
		taxes
	SET
		TAXGROUPNAME = __TAXGROUPNAME,
        TAXNAME1 = __TAXNAME1,
        TAXNAME2 = __TAXNAME2,
        TAXNAME3 = __TAXNAME3,
        TAXNAME4 = __TAXNAME4,
        TAXNAME5 = __TAXNAME5,
        TAXRATE1 = __TAXRATE1,
        TAXRATE2 = __TAXRATE2,
        TAXRATE3 = __TAXRATE3,
        TAXRATE4 = __TAXRATE4,
        TAXRATE5 = __TAXRATE5
	WHERE
		TAXCODE = __TAXCODE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_UserDelete` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_UserDelete`(__USERNAME VARCHAR(20))
BEGIN

	DELETE FROM user WHERE USERNAME = __USERNAME;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_UserInsert` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_UserInsert`(IN `__USERNAME` VARCHAR(50), IN `__BRANCH` VARCHAR(20), IN `__PLAINPASSWORD` VARCHAR(50), IN `__FIRSTNAME` VARCHAR(100), IN `__LASTNAME` VARCHAR(100), IN `__EMAIL` VARCHAR(100), IN `__LANGUAGE` VARCHAR(2), IN `__USERLEVEL` INT, IN `__STATUS` INT, IN `__COMMENTS` VARCHAR(1000))
BEGIN

	INSERT INTO
		user
        (USERNAME,BRANCH,PLAINPASSWORD,PASSWORD,FIRSTNAME,LASTNAME,EMAIL,LANGUAGE,
         USERLEVEL,STATUS,COMMENTS,CREATEDDATE,MODIFIEDDATE)
	VALUES
		(__USERNAME,__BRANCH,__PLAINPASSWORD,CONCAT('*', UPPER(SHA1(UNHEX(SHA1(__PLAINPASSWORD))))),__FIRSTNAME,
        __LASTNAME,__EMAIL,__LANGUAGE,__USERLEVEL,__STATUS,__COMMENTS,CURRENT_TIMESTAMP,
        CURRENT_TIMESTAMP);


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `importTableData_UserUpdate` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `importTableData_UserUpdate`(IN `__USERNAME` VARCHAR(50), IN `__BRANCH` VARCHAR(20), IN `__PLAINPASSWORD` VARCHAR(50), IN `__FIRSTNAME` VARCHAR(100), IN `__LASTNAME` VARCHAR(100), IN `__EMAIL` VARCHAR(100), IN `__LANGUAGE` VARCHAR(2), IN `__USERLEVEL` INT, IN `__STATUS` INT, IN `__COMMENTS` VARCHAR(1000))
BEGIN

	UPDATE
		user
	SET
		BRANCH = __BRANCH,
        PLAINPASSWORD = __PLAINPASSWORD,
        PASSWORD = CONCAT('*', UPPER(SHA1(UNHEX(SHA1(__PLAINPASSWORD))))),
        FIRSTNAME = __FIRSTNAME,
        LASTNAME = __LASTNAME,
        EMAIL = __EMAIL,
        LANGUAGE = __LANGUAGE,
        USERLEVEL = __USERLEVEL,
        STATUS = __STATUS,
        COMMENTS = __COMMENTS
	WHERE
		USERNAME = __USERNAME;


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `InsertPromoCategory` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `InsertPromoCategory`(__CODE VARCHAR(50), __CATID INT)
BEGIN
  INSERT INTO 
    promosCategories 
  (CODE,CATID)
    VALUES 
  (__CODE,__CATID);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `InsertPromoItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertPromoItems`(__CODE VARCHAR(50), __ITEMID INT)
BEGIN
	INSERT INTO 
		promosItems 
	(CODE,ITEMID)
    VALUES 
	(__CODE,__ITEMID);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `MakeGeneratedItem` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `MakeGeneratedItem`(__USERNAME VARCHAR(50), __ITEMID INT, __UPLOADDIR VARCHAR(500), __DESCR VARCHAR(500), __MGRAPPROVAL BIT, __PREFIX VARCHAR(10))
BEGIN

DECLARE __NEXTCOUNT INT;
DECLARE __CHKCODE INT;
DECLARE __APPROVALCODE VARCHAR(50);
SELECT COUNT(*)+1 FROM items WHERE PARENTITEM = __ITEMID LIMIT 1 INTO __NEXTCOUNT;

SET __CHKCODE = 1;
WHILE __CHKCODE >= 1 DO
  SET __APPROVALCODE = MD5(UUID());
    SET __CHKCODE = (SELECT COUNT(*) FROM items WHERE APPROVALLINK = @__APPROVALCODE);
END WHILE;

INSERT INTO
  items
    (TYPE,CODE,DESCRIPTION,PRODUCEDETAIL,SIZE,NUMPAGES,STATUS,MINLEVEL,LEADTIME,
     DISPLAYIMAGENAME,DISPLAYIMAGEPATH,PROOFPDFNAME,PROOFPDFPATH,
     PARENTITEM,ARCHIVED,GENERATEDBY,ASSETAPPROVED,APPROVALLINK,PARAMETERSFILENAME,
     PARAMETERSFILEPATH,SHIPBOXINSLEEVE,SKIPPDFPERMISSIONCHECK,DLSUGGESTIONS)
SELECT
  3 AS TYPE,
    CONCAT(CODE,'-', RIGHT(CONCAT('00000',__NEXTCOUNT),5)) AS CODE,
    CASE 
    WHEN LENGTH(__DESCR) > 0 THEN CONCAT(DESCRIPTION,'  (',__DESCR,')')
        ELSE CONCAT(DESCRIPTION,'')
  END  AS DESCRIPTION,
    PRODUCEDETAIL AS PRODUCEDETAIL,
    SIZE AS SIZE,
    NUMPAGES AS NUMPAGES,
    STATUS AS STATUS,
    MINLEVEL AS MINLEVEL,
    LEADTIME AS LEADTIME,
    'PLACEHOLDER' AS DISPLAYIMAGENAME,
    'PLACEHOLDER' AS DISPLAYIMAGEPATH,
    'PLACEHOLDER' AS PROOFPDFNAME,
    'PLACEHOLDER' AS PROOFPDFPATH,
    ID AS PARENTITEM,
    0 AS ARCHIVED,
    __USERNAME AS GENERATEDBY,
    CASE WHEN __MGRAPPROVAL = 0 THEN 1 ELSE 0 END AS ASSETAPPROVED,
  CASE WHEN __MGRAPPROVAL = 0 THEN NULL ELSE __APPROVALCODE END AS APPROVALLINK,
    '' AS PARAMETERSFILENAME,
    '' AS PARAMETERSFILEPATH,
    SHIPBOXINSLEEVE,
    SKIPPDFPERMISSIONCHECK,
    DLSUGGESTIONS
FROM
  items ITEMDATA
WHERE
  ID = __ITEMID;
    
SET @INSERTID = LAST_INSERT_ID();
SET @BRANCHEMAIL = (SELECT MANAGEMENTEMAIL FROM branches WHERE CODE IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME));
SET @BRANCHCODE = (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME);
SELECT ID AS INSERTID,APPROVALLINK, @BRANCHEMAIL AS BEMAIL, CODE FROM items WHERE ID = @INSERTID;

UPDATE
  items
SET
    DISPLAYIMAGENAME = CONCAT(__PREFIX,@INSERTID,'-',@BRANCHCODE,'-',CODE,'.jpg'),
    DISPLAYIMAGEPATH = CONCAT(__UPLOADDIR,__PREFIX,@INSERTID,'-',@BRANCHCODE,'-',CODE,'.jpg'),
    PROOFPDFNAME = CONCAT(__PREFIX,@INSERTID,'-',@BRANCHCODE,'-',CODE,'.pdf'),
    PROOFPDFPATH = CONCAT(__UPLOADDIR,__PREFIX,@INSERTID,'-',@BRANCHCODE,'-',CODE,'.pdf')
WHERE
  ID = @INSERTID;

INSERT INTO
  itemPricing
    (ITEMID,QTY,PRICE,LENGTH,WIDTH,HEIGHT,WEIGHT,PIECES,ITEMOPTION)
SELECT
  @INSERTID AS ITEMID,
    QTY,
    PRICE,
    LENGTH,
    WIDTH,
    HEIGHT,
    WEIGHT,
    PIECES,
    ITEMOPTION
FROM
  itemPricing
WHERE
  ITEMID = __ITEMID;
    
INSERT INTO
  itemsBranchesLink
    (ITEMID,BRANCHCODE)
SELECT
  @INSERTID AS ITEMID,
    BRANCH AS BRANCHCODE
FROM
  user
WHERE
  USERNAME = __USERNAME;
    
INSERT INTO
  itemsSubcategoryLink
    (ITEMID,SUBCATID)
SELECT
  @INSERTID AS ITEMID,
    SUBCATID
FROM
  itemsSubcategoryLink
WHERE
  ITEMID = __ITEMID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ManualChangeOrderShipToAddress` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ManualChangeOrderShipToAddress`(__USERNAME VARCHAR(50), __NAME VARCHAR(100), __STOREID VARCHAR(20), __ADDRESS VARCHAR(1000), __ADDRESS2 VARCHAR(1000), __CITY VARCHAR(100), __PROVINCE VARCHAR(100), __COUNTRY VARCHAR(100), __POSTAL VARCHAR(20), __PHONE VARCHAR(20), __FAX VARCHAR(20))
BEGIN


SET SQL_SAFE_UPDATES = 0;


SET @TGROUPCHECK = (SELECT COUNT(*) FROM taxes WHERE TAXCODE = __PROVINCE);

IF @TGROUPCHECK <= 0 THEN
	SIGNAL SQLSTATE '45000'
	SET MESSAGE_TEXT = 'No Tax group matching province';	
ELSE 
	UPDATE
		orderHeader
	SET
		SHIPNAME = __NAME,
        SHIPSTOREID = __STOREID,
		SHIPADDRESS = __ADDRESS,
        SHIPADDRESS2 = __ADDRESS2,
		SHIPCITY = __CITY,
		SHIPPROVINCE = __PROVINCE,
		SHIPCOUNTRY = __COUNTRY,
		SHIPPOSTAL = __POSTAL,
		SHIPCONTACTPHONE = __PHONE,
		SHIPCONTACTFAX = __FAX,
		SHIPTAXGROUP = __PROVINCE
	WHERE 
		USERNAME  = __USERNAME AND 
		ORDERSTATUS = 'CART';
END IF;


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ModifyAdItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ModifyAdItem`(__ID INT, __NAME VARCHAR(1000), __STARTDATE DATE, __ENDDATE DATE, __LANGUAGE VARCHAR(2), __SORTORDER INT, __URL VARCHAR(500), __ADPATH VARCHAR(200))
BEGIN

	UPDATE 
		AdItems
	SET
		NAME = __NAME,
        STARTDATE = __STARTDATE,
        ENDDATE = __ENDDATE,
        LANGUAGE = __LANGUAGE,
        SORTORDER = __SORTORDER,
        IMAGEPATH = CASE WHEN __ADPATH = 'NOUPDATE' THEN IMAGEPATH ELSE __ADPATH END,
        URL = __URL
	WHERE
		ID = __ID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ModifyBranchAddress` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ModifyBranchAddress`(__CODE VARCHAR(20), __LANG VARCHAR(2), __ISMAIN TINYINT(1), __ADDRESS VARCHAR(1000), __ADDRESS2 VARCHAR(1000), __CITY VARCHAR(100), __PROVINCE VARCHAR(100), __COUNTRY VARCHAR(100), __POSTALCODE VARCHAR(20), __PHONE VARCHAR(20), __FAX VARCHAR(20))
BEGIN

	SET @FOUNDMATCH := 0;
    SELECT @FOUNDMATCH := COUNT(*) FROM branchesAddresses WHERE CODE = __CODE AND LANGUAGE = __LANG;

	IF @FOUNDMATCH > 0 THEN
		UPDATE
			branchesAddresses
		SET
			ISMAIN = __ISMAIN, 
			ADDRESS = __ADDRESS, 
            ADDRESS2 = __ADDRESS2,
			CITY = __CITY, 
			PROVINCE = __PROVINCE, 
			COUNTRY = __COUNTRY, 
			POSTALCODE = __POSTALCODE, 
			PHONE = __PHONE, 
			FAX = __FAX
		WHERE
			CODE = __CODE AND
			LANGUAGE = __LANG;
		UPDATE 
			orderHeader 
		SET 
			SHIPCONTACTPHONE = __PHONE, 
			SHIPCONTACTFAX = __FAX, 
			SHIPADDRESS = __ADDRESS, 
			SHIPADDRESS2 = __ADDRESS2, 
			SHIPCITY = __CITY, 
			SHIPPROVINCE = __PROVINCE, 
			SHIPCOUNTRY = __COUNTRY, 
			SHIPPOSTAL = __POSTALCODE, 
			REQCONTACTPHONE = __PHONE, 
			REQCONTACTFAX = __FAX, 
			REQADDRESS = __ADDRESS, 
			REQADDRESS2 = __ADDRESS2, 
			REQCITY = __CITY, 
			REQPROVINCE = __PROVINCE, 
			REQCOUNTRY = __COUNTRY, 
			REQPOSTAL = __POSTALCODE
		WHERE 
			USERNAME IN (SELECT USERNAME FROM user WHERE branch = __CODE) AND 
			ORDERSTATUS = 'CART';
    ELSE
		INSERT INTO
			branchesAddresses
			(CODE, LANGUAGE, ISMAIN, ADDRESS, ADDRESS2, CITY, PROVINCE, COUNTRY, POSTALCODE, PHONE, FAX)
		VALUES
			(__CODE, __LANG, __ISMAIN, __ADDRESS, __ADDRESS2, __CITY, __PROVINCE, __COUNTRY, __POSTALCODE, __PHONE, __FAX);
	END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ModifyBranchProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ModifyBranchProfile`(__CODE VARCHAR(20), __NAME VARCHAR(100), __MGREMAIL VARCHAR(100), __TREEMAIL VARCHAR(100), __TAXGROUP VARCHAR(6), __SKIN VARCHAR(20), __STATUS INTEGER, __COMMENTS VARCHAR(1000), __SHIPZONE VARCHAR(20))
BEGIN

UPDATE
	branches
SET
	CODE = __CODE,
    NAME = __NAME,
    MANAGEMENTEMAIL = __MGREMAIL,
    TREASUREREMAIL = __TREEMAIL,
    TAXGROUP = __TAXGROUP,
    SKIN = __SKIN,
    STATUS = __STATUS,
    COMMENTS = __COMMENTS,
    SHIPZONE = __SHIPZONE,
    MODIFIEDDATE = CURRENT_TIMESTAMP
WHERE
	CODE = __CODE;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ModifyCategory` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ModifyCategory`(__CATID INTEGER, __NAME VARCHAR(50), __DESCRIPTION VARCHAR(200), __LANGUAGE VARCHAR(2), __ICON VARCHAR(200), __USERLEVEL INTEGER, __COMMENTS VARCHAR(1000))
BEGIN
	UPDATE
		categories
	SET
		NAME = __NAME,
        DESCRIPTION = __DESCRIPTION,
        ICONURL = __ICON,
        LANGUAGE = __LANGUAGE,
        USERLEVEL = __USERLEVEL,
        COMMENTS  = __COMMENTS,
        MODIFIEDDATE = CURRENT_TIMESTAMP
	WHERE
		CATID = __CATID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ModifyItem` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `ModifyItem`(IN `__ITEMID` INT, IN `__TYPE` INT, IN `__CODE` VARCHAR(50), IN `__DESCRIPTION` VARCHAR(200), IN `__PRODUCEDETAIL` VARCHAR(1000), IN `__SIZE` VARCHAR(50), IN `__NUMPAGES` VARCHAR(50), IN `__PRINTINGTYPE` VARCHAR(50), IN `__STOCK` VARCHAR(50), IN `__STATUS` INT, IN `__MINLEVEL` INT, IN `__LEADTIME` INT, IN `__DISPLAYNAME` VARCHAR(1000), IN `__PROOFNAME` VARCHAR(1000), IN `__PARAMETERSNAME` VARCHAR(1000), IN `__UPLOADDIR` VARCHAR(1000), IN `__PREVIEWNAME` VARCHAR(1000), IN `__SHIPBOXINSLEEVE` INT, IN `__SKIPPDFPERMISSIONCHECK` INT, IN `__DLSUGGESTIONS` VARCHAR(1000))
BEGIN
        UPDATE
                items
        SET
                TYPE = __TYPE, 
        CODE = __CODE,
        DESCRIPTION = __DESCRIPTION,
        PRODUCEDETAIL = __PRODUCEDETAIL,
        SIZE = __SIZE,
        NUMPAGES = __NUMPAGES,
        STATUS = __STATUS,
        MINLEVEL = __MINLEVEL,
        LEADTIME = __LEADTIME,
        DISPLAYIMAGENAME = __DISPLAYNAME,
        PROOFPDFNAME = __PROOFNAME,
        PREVIEWIMAGENAME = __PREVIEWNAME,
        PARAMETERSFILENAME = __PARAMETERSNAME,
        DISPLAYIMAGEPATH = CASE WHEN LENGTH(__DISPLAYNAME) > 0 THEN CONCAT(__UPLOADDIR,__DISPLAYNAME) ELSE '' END,
        PROOFPDFPATH = CASE WHEN LENGTH(__PROOFNAME) > 0 THEN CONCAT(__UPLOADDIR,__PROOFNAME) ELSE '' END,
        PARAMETERSFILEPATH = CASE WHEN LENGTH(__PARAMETERSNAME) > 0 THEN CONCAT(__UPLOADDIR,__PARAMETERSNAME) ELSE '' END,
        PREVIEWIMAGEPATH = CASE WHEN LENGTH(__PREVIEWNAME) > 0 THEN CONCAT(__UPLOADDIR,__PREVIEWNAME) ELSE '' END,
        SHIPBOXINSLEEVE = __SHIPBOXINSLEEVE,
        SKIPPDFPERMISSIONCHECK = __SKIPPDFPERMISSIONCHECK,
        DLSUGGESTIONS = __DLSUGGESTIONS,
        STOCK=__STOCK,
        PRINTINGTYPE=__PRINTINGTYPE
        WHERE
                ID = __ITEMID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ModifyNewsItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ModifyNewsItem`(__ID INTEGER, __STARTDATE DATE, __ENDDATE DATE, __LANGUAGE VARCHAR(2), __TITLE VARCHAR(1000), __MESSAGE VARCHAR(1000))
BEGIN
	UPDATE
		newsItems
	SET
		STARTDATE = __STARTDATE,
        ENDDATE = __ENDDATE,
        LANGUAGE = __LANGUAGE,
        TITLE = __TITLE,
        MESSAGE = __MESSAGE
	WHERE
		ID = __ID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ModifyPromo` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `ModifyPromo`(__NAME VARCHAR(100), __CODE VARCHAR(50), __CODETYPE VARCHAR(12), __PROMOVALUE DECIMAL(19,2), __QTYTYPE VARCHAR(12), __MAXQTY INT, __MINQTY INT, __EXACTQTY INT, __STARTDATE DATE, __ENDDATE DATE, __SINGLEUSE INT, __REDEEMED INT, __SINGLEITEM INT)
BEGIN

 UPDATE 
 promos
 SET
 NAME = __NAME,
 CODETYPE = __CODETYPE,
 PROMOVALUE = __PROMOVALUE,
 QTYTYPE = __QTYTYPE,
 MAXQTY = __MAXQTY,
 MINQTY = __MINQTY,
 EXACTQTY = __EXACTQTY,
 STARTDATE = __STARTDATE,
 ENDDATE = __ENDDATE,
 SINGLEUSE = __SINGLEUSE,
 REDEEMED = __REDEEMED,
 SINGLEITEM = __SINGLEITEM
 WHERE
 CODE = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ModifyShipToAddress` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ModifyShipToAddress`(__ID INT, __NAME VARCHAR(100), __STOREID VARCHAR(20), __ADDRESS VARCHAR(1000), __ADDRESS2 VARCHAR(1000), __CITY VARCHAR(100),
__PROVINCE VARCHAR(100), __COUNTRY VARCHAR(100), __POSTAL VARCHAR(20), __PHONE VARCHAR(20), __FAX VARCHAR(20),
__TAXGROUP VARCHAR(6), __SHIPZONE VARCHAR(6))
BEGIN

UPDATE
	shipToAddresses
SET
	NAME = __NAME,
    STOREID = __STOREID,
    ADDRESS = __ADDRESS,
    ADDRESS2 = __ADDRESS2,
    CITY = __CITY,
    PROVINCE = __PROVINCE,
    COUNTRY = __COUNTRY,
    POSTAL = __POSTAL,
    PHONE = __PHONE,
    FAX = __FAX,
    TAXGROUP = __TAXGROUP,
    SHIPZONE = __SHIPZONE
WHERE
	ID = __ID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ModifySubCategory` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `ModifySubCategory`(__SUBCATID INTEGER, __CATID INTEGER, __NAME VARCHAR(50), __DESCRIPTION VARCHAR(200), __ICONURL VARCHAR(200), __USERLEVEL INT)
BEGIN
    UPDATE
        subcategories
    SET
        NAME = __NAME,
        DESCRIPTION = __DESCRIPTION,
        ICONURL = __ICONURL,
        USERLEVEL = __USERLEVEL
    WHERE
        SUBCATID = __SUBCATID AND
        CATID = __CATID ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ModifyUserProfile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ModifyUserProfile`(IN `UNAME` VARCHAR(50), IN `__BRANCH` VARCHAR(20), IN `PASS` VARCHAR(50), IN `FNAME` VARCHAR(50), IN `LNAME` VARCHAR(50), IN `LANG` VARCHAR(2), IN `STAT` INT, IN `USERLVL` INT, IN `COMMENTS` VARCHAR(1000), IN `EMAIL` VARCHAR(100))
BEGIN

UPDATE
	`user`
SET
	`BRANCH` = __BRANCH, 
	`PASSWORD` = CONCAT('*', UPPER(SHA1(UNHEX(SHA1(PASS))))),
    `PLAINPASSWORD` = PASS,
    `FIRSTNAME` = FNAME,
    `LASTNAME` = LNAME,
    `LANGUAGE` = LANG,
    `STATUS` = STAT,
    `USERLEVEL` = USERLVL,
    `COMMENTS` = COMMENTS,
    `EMAIL` = EMAIL,
    `MODIFIEDDATE` = CURRENT_TIMESTAMP
WHERE
	`USERNAME` = UNAME;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `RejectItem` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `RejectItem`(__CODE VARCHAR(200))
BEGIN
	SELECT
		ITEM.ID AS ITEMID,
        USERS.EMAIL AS USEREMAIL,
        ITEM.DISPLAYIMAGEPATH
	FROM
		items ITEM 
	INNER JOIN
		user USERS ON 
			USERS.USERNAME = ITEM.GENERATEDBY
	WHERE 
		APPROVALLINK = __CODE;

	UPDATE
		items
	SET
		STATUS = 0,
		ARCHIVED = 1,
		ASSETAPPROVED = 0,
        APPROVALLINK = NULL
	WHERE
		APPROVALLINK = __CODE;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `RejectOrder` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `RejectOrder`(__APPROVALLINK NVARCHAR(100))
BEGIN


SELECT
	HDR.*,
    DTL.*,
    ITEM.TYPE,
    USER.FIRSTNAME AS USER_FIRSTNAME,
    USER.LASTNAME AS USER_LASTNAME,
    USER.EMAIL AS USER_EMAIL,
    USER.LANGUAGE AS USER_LANGUAGE,
    BRANCH.NAME AS BRANCH_NAME,
    BRANCH.MANAGEMENTEMAIL AS BRANCH_MANAGEMENTEMAIL,
    COALESCE(BRANCHADDRESS.LANGUAGE,'EN') AS BRANCH_LANGUAGE,
    'CANCELLED' AS REALSTATUS
FROM
	orderHeader HDR
INNER JOIN
	orderDetail DTL ON 
		HDR.ORDERID = DTL.ORDERID
INNER JOIN
	items ITEM ON
		DTL.ITEMID = ITEM.ID
INNER JOIN
	user USER ON 
		HDR.USERNAME = USER.USERNAME
INNER JOIN
	branches BRANCH ON 
		USER.BRANCH = BRANCH.CODE
LEFT OUTER JOIN
	(SELECT * FROM branchesAddresses WHERE ISMAIN = 1) BRANCHADDRESS ON 
		BRANCH.CODE = BRANCHADDRESS.CODE
WHERE
	HDR.APPROVALLINK  COLLATE utf8_unicode_ci = __APPROVALLINK AND
    HDR.APPROVALLINK IS NOT NULL;
    
UPDATE
	orderHeader
SET
	APPROVALLINK = NULL,
    ORDERSTATUS = 'REJECTED',
    ORDERMODIFIED = CURRENT_TIMESTAMP
WHERE
	APPROVALLINK  COLLATE utf8_unicode_ci = __APPROVALLINK AND
    APPROVALLINK IS NOT NULL;	

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `RemoveItemFromCart` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `RemoveItemFromCart`(__USERNAME NVARCHAR(20), __ITEMLINE INT)
BEGIN
	
    DELETE
    FROM
		orderDetail
	WHERE
		ITEMLINE = __ITEMLINE AND
        ORDERID IN (SELECT ORDERID FROM orderHeader WHERE USERNAME COLLATE utf8_unicode_ci = __USERNAME AND ORDERSTATUS = 'CART')
	;
    
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `RemoveOldCartOrders` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `RemoveOldCartOrders`()
BEGIN

DELETE FROM orderDetail WHERE ORDERID IN (
SELECT ORDERID FROM orderHeader WHERE ORDERSTATUS = 'CART' AND ORDERMODIFIED < DATE_ADD(CURRENT_TIMESTAMP,INTERVAL -24 HOUR)
);

DELETE FROM orderHeader WHERE ORDERSTATUS = 'CART' AND ORDERMODIFIED < DATE_ADD(CURRENT_TIMESTAMP,INTERVAL -24 HOUR);

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `RemovePromoFromCart` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `RemovePromoFromCart`(__USERNAME VARCHAR(20), __PROMO VARCHAR(50))
BEGIN
	
    DELETE
    FROM
		orderPromos
	WHERE
		PROMOCODE = __PROMO AND
        ORDERID IN (SELECT ORDERID FROM orderHeader WHERE USERNAME COLLATE utf8_unicode_ci = __USERNAME AND ORDERSTATUS = 'CART')
	;

    UPDATE
		promos
	SET
		REDEEMED = 0
	WHERE
		CODE = __PROMO AND
        SINGLEUSE = 1;
    
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ReportOrderBranches` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `ReportOrderBranches`(IN `__STARTDATE` DATE, IN `__ENDDATE` DATE, IN `__ACCESS` BIT, IN `__USERNAME` VARCHAR(50))
BEGIN

	SELECT
		HDR.ORDERID,
        HDR.ORDERREF,
        HDR.PAYMENTREF,
        HDR.ORDERSTATUS,
        HDR.PONUMBER,
        HDR.BILLINGCATEGORY,
        HDR.SPECIALINSTRUCTIONS,
        CASE WHEN USER.USERNAME IS NOT NULL THEN CONCAT(USER.FIRSTNAME,' ',USER.LASTNAME) ELSE 'Unknown User' END AS ORDERBY,
        DATE(ORDERDATE) AS ORDERDATE,
        DATE(APPROVALDATE) AS APPROVALDATE,
        HDR.SHIPNAME,
        CONCAT(HDR.SHIPCONTACTFIRSTNAME,' ',HDR.SHIPCONTACTLASTNAME) AS SHIPCONTACT,
        HDR.SHIPCONTACTEMAIL,
        HDR.SHIPADDRESS,
        HDR.SHIPCITY,
        HDR.SHIPPROVINCE,
        HDR.SHIPPOSTAL,
        HDR.SHIPPINGCOST,
        COALESCE(DTLSUM.EXTPRICE,0) AS EXTPRICE,
        COALESCE(DTLSUM.TAXAMT,0) + HDR.SHIPPINGCOSTTAXAMT1 + HDR.SHIPPINGCOSTTAXAMT2 + HDR.SHIPPINGCOSTTAXAMT3 + HDR.SHIPPINGCOSTTAXAMT4 + HDR.SHIPPINGCOSTTAXAMT5 AS TAXAMT,
        COALESCE(DTLSUM.EXTPRICE,0) + COALESCE(DTLSUM.TAXAMT,0) + HDR.SHIPPINGCOST + HDR.SHIPPINGCOSTTAXAMT1 + HDR.SHIPPINGCOSTTAXAMT2 + HDR.SHIPPINGCOSTTAXAMT3 + HDR.SHIPPINGCOSTTAXAMT4 + HDR.SHIPPINGCOSTTAXAMT5 AS GRANDTOTAL,
        COALESCE(SHDR.TRACKNUM,'No Tracking #') AS TRACKNUM,
        COALESCE(DATE(SHDR.SHIPDATE),'') AS SHIPDATE,
        DTL.ITEMID,
        COALESCE(DTL.ITEMCODE,'Unknown Item') AS ITEMCODE,
        COALESCE(DTL.ITEMDESC,'Unknown Item') AS ITEMDESC,
        COALESCE(DTL.ORDERQTY,0) AS ORDERQTY,
        COALESCE(DTL.SHIPTODATEQTY,0) AS SHIPTODATEQTY,
        COALESCE(DTL.EXTPRICE,0) AS ITEMEXTPRICE,
        COALESCE(DTL.TAXAMT1 + DTL.TAXAMT2 + DTL.TAXAMT3 + DTL.TAXAMT4 + DTL.TAXAMT5,0) AS ITEMTAXES,
        COALESCE(DTL.EXTPRICE + DTL.TAXAMT1 + DTL.TAXAMT2 + DTL.TAXAMT3 + DTL.TAXAMT4 + DTL.TAXAMT5,0) AS ITEMTOTAL,
        BRANCH.NAME AS BRANCHNAME,
        BRANCH.CODE AS BRANCHCODE,
        COALESCE(BRANCH.SKIN,'NA') AS SKINBRAND
	FROM
		orderHeader HDR
	LEFT OUTER JOIN
		( SELECT ORDERID,SUM(EXTPRICE) AS EXTPRICE, SUM(TAXAMT1+TAXAMT2+TAXAMT3+TAXAMT4+TAXAMT5) AS TAXAMT FROM orderDetail GROUP BY ORDERID) DTLSUM ON 
			HDR.ORDERID = DTLSUM.ORDERID
	LEFT OUTER JOIN
		orderDetail DTL ON 
			HDR.ORDERID = DTL.ORDERID
	LEFT OUTER JOIN
		( SELECT ORDERID,MAX(TRACKNUM) AS TRACKNUM, MAX(SHIPDATE) AS SHIPDATE FROM shipmentHeader GROUP BY ORDERID ) SHDR ON 
			HDR.ORDERID = SHDR.ORDERID
	LEFT OUTER JOIN
		user USER ON 
			HDR.USERNAME = USER.USERNAME
	LEFT OUTER JOIN
		branches BRANCH ON 
			USER.BRANCH = BRANCH.CODE
	WHERE
		HDR.ORDERDATE BETWEEN __STARTDATE AND DATE_ADD(__ENDDATE,INTERVAL 1 DAY) AND
		HDR.ORDERSTATUS NOT IN ('WAITMA','CART') AND
        (__ACCESS = 1 OR USER.BRANCH IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME))
	ORDER BY
		COALESCE(BRANCH.SKIN,'NA'),
		BRANCH.NAME,
		ORDERDATE,
        HDR.ORDERID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ReportOrderDetailed` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `ReportOrderDetailed`(IN `__STARTDATE` DATE, IN `__ENDDATE` DATE, IN `__ACCESS` BIT, IN `__USERNAME` VARCHAR(50))
BEGIN

	SELECT
		HDR.ORDERID,
        HDR.ORDERREF,
        HDR.ORDERSTATUS,
        HDR.PAYMENTREF,
		HDR.PONUMBER,
        HDR.BILLINGCATEGORY,
        CASE WHEN USER.USERNAME IS NOT NULL THEN CONCAT(USER.FIRSTNAME,' ',USER.LASTNAME) ELSE 'Unknown User' END AS ORDERBY,
        DATE(ORDERDATE) AS ORDERDATE,
        HDR.SHIPNAME,
        CONCAT(HDR.SHIPCONTACTFIRSTNAME,' ',HDR.SHIPCONTACTLASTNAME) AS SHIPCONTACT,
        HDR.SHIPCONTACTEMAIL,
        HDR.SHIPADDRESS,
        HDR.SHIPCITY,
        HDR.SHIPPROVINCE,
        HDR.SHIPPOSTAL,
        HDR.SHIPPINGCOST,
        COALESCE(DTLSUM.EXTPRICE,0) AS EXTPRICE,
        COALESCE(DTLSUM.TAXAMT,0) + HDR.SHIPPINGCOSTTAXAMT1 + HDR.SHIPPINGCOSTTAXAMT2 + HDR.SHIPPINGCOSTTAXAMT3 + HDR.SHIPPINGCOSTTAXAMT4 + HDR.SHIPPINGCOSTTAXAMT5 AS TAXAMT,
        COALESCE(DTLSUM.EXTPRICE,0) + COALESCE(DTLSUM.TAXAMT,0) + HDR.SHIPPINGCOST + HDR.SHIPPINGCOSTTAXAMT1 + HDR.SHIPPINGCOSTTAXAMT2 + HDR.SHIPPINGCOSTTAXAMT3 + HDR.SHIPPINGCOSTTAXAMT4 + HDR.SHIPPINGCOSTTAXAMT5 AS GRANDTOTAL,
        COALESCE(SHDR.TRACKNUM,'No Tracking #') AS TRACKNUM,
        COALESCE(DATE(SHDR.SHIPDATE),'') AS SHIPDATE,
        DTL.ITEMID,
        COALESCE(DTL.ITEMCODE,'Unknown Item') AS ITEMCODE,
        COALESCE(DTL.ITEMDESC,'Unknown Item') AS ITEMDESC,
        COALESCE(DTL.ORDERQTY,0) AS ORDERQTY,
        COALESCE(DTL.SHIPTODATEQTY,0) AS SHIPTODATEQTY,
        COALESCE(DTL.EXTPRICE,0) AS ITEMEXTPRICE,
        COALESCE(DTL.TAXAMT1 + DTL.TAXAMT2 + DTL.TAXAMT3 + DTL.TAXAMT4 + DTL.TAXAMT5,0) AS ITEMTAXES,
        COALESCE(DTL.EXTPRICE + DTL.TAXAMT1 + DTL.TAXAMT2 + DTL.TAXAMT3 + DTL.TAXAMT4 + DTL.TAXAMT5,0) AS ITEMTOTAL,
        COALESCE(BRANCH.SKIN,'N/A') AS SKINBRAND,
	   BRANCH.CODE AS BRANCHCODE
	FROM
		orderHeader HDR
	LEFT OUTER JOIN
		( SELECT ORDERID,SUM(EXTPRICE) AS EXTPRICE, SUM(TAXAMT1+TAXAMT2+TAXAMT3+TAXAMT4+TAXAMT5) AS TAXAMT FROM orderDetail GROUP BY ORDERID) DTLSUM ON 
			HDR.ORDERID = DTLSUM.ORDERID
	LEFT OUTER JOIN
		orderDetail DTL ON 
			HDR.ORDERID = DTL.ORDERID
	LEFT OUTER JOIN
		( SELECT ORDERID,MAX(TRACKNUM) AS TRACKNUM, MAX(SHIPDATE) AS SHIPDATE FROM shipmentHeader GROUP BY ORDERID ) SHDR ON 
			HDR.ORDERID = SHDR.ORDERID
	LEFT OUTER JOIN
		user USER ON 
			HDR.USERNAME = USER.USERNAME
	LEFT OUTER JOIN
		branches BRANCH ON 
			USER.BRANCH = BRANCH.CODE            
	WHERE
		HDR.ORDERDATE BETWEEN __STARTDATE AND DATE_ADD(__ENDDATE,INTERVAL 1 DAY) AND
		HDR.ORDERSTATUS NOT IN ('WAITMA','CART') AND
        (__ACCESS = 1 OR USER.BRANCH IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME))

ORDER BY
        HDR.ORDERID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ReportOrderSummary` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ReportOrderSummary`(__STARTDATE DATE, __ENDDATE DATE, __ACCESS BIT, __USERNAME VARCHAR(50))
BEGIN

	SELECT
		HDR.ORDERID,
        HDR.ORDERREF,
        HDR.PAYMENTREF,
        HDR.ORDERSTATUS,
        CASE WHEN USER.USERNAME IS NOT NULL THEN CONCAT(USER.FIRSTNAME,' ',USER.LASTNAME) ELSE 'Unknown User' END AS ORDERBY,
        DATE(ORDERDATE) AS ORDERDATE,
        HDR.SHIPNAME,
        CONCAT(HDR.SHIPCONTACTFIRSTNAME,' ',HDR.SHIPCONTACTLASTNAME) AS SHIPCONTACT,
        HDR.SHIPADDRESS,
        HDR.SHIPCITY,
        HDR.SHIPPROVINCE,
        HDR.SHIPPOSTAL,
        HDR.SHIPPINGCOST,
        HDR.SHIPSTOREID,
        COALESCE(DTL.EXTPRICE,0) AS EXTPRICE,
        COALESCE(DTL.TAXAMT,0) + HDR.SHIPPINGCOSTTAXAMT1 + HDR.SHIPPINGCOSTTAXAMT2 + HDR.SHIPPINGCOSTTAXAMT3 + HDR.SHIPPINGCOSTTAXAMT4 + HDR.SHIPPINGCOSTTAXAMT5 AS TAXAMT,
        COALESCE(DTL.EXTPRICE,0) + COALESCE(DTL.TAXAMT,0) + HDR.SHIPPINGCOST + HDR.SHIPPINGCOSTTAXAMT1 + HDR.SHIPPINGCOSTTAXAMT2 + HDR.SHIPPINGCOSTTAXAMT3 + HDR.SHIPPINGCOSTTAXAMT4 + HDR.SHIPPINGCOSTTAXAMT5 AS GRANDTOTAL,
        COALESCE(SHDR.TRACKNUM,'No Tracking #') AS TRACKNUM,
        COALESCE(DATE(SHDR.SHIPDATE),'') AS SHIPDATE,
        COALESCE(BRANCH.SKIN,'N/A') AS SKINBRAND,
        BRANCH.CODE AS BRANCHCODE
	FROM
		orderHeader HDR
	LEFT OUTER JOIN
		( SELECT ORDERID,SUM(EXTPRICE) AS EXTPRICE, SUM(TAXAMT1+TAXAMT2+TAXAMT3+TAXAMT4+TAXAMT5) AS TAXAMT FROM orderDetail GROUP BY ORDERID) DTL ON 
			HDR.ORDERID = DTL.ORDERID
	LEFT OUTER JOIN
		( SELECT ORDERID,MAX(TRACKNUM) AS TRACKNUM, MAX(SHIPDATE) AS SHIPDATE FROM shipmentHeader GROUP BY ORDERID ) SHDR ON 
			HDR.ORDERID = SHDR.ORDERID
	LEFT OUTER JOIN
		user USER ON 
			HDR.USERNAME = USER.USERNAME
	LEFT OUTER JOIN
		branches BRANCH ON 
			USER.BRANCH = BRANCH.CODE
	WHERE
		HDR.ORDERDATE BETWEEN __STARTDATE AND DATE_ADD(__ENDDATE,INTERVAL 1 DAY) AND
		HDR.ORDERSTATUS NOT IN ('WAITMA','CART') AND
        (__ACCESS = 1 OR USER.BRANCH IN (SELECT BRANCH FROM user WHERE USERNAME = __USERNAME));

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ResendAssetEmail` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ResendAssetEmail`(__ITEMID INT)
BEGIN

SELECT
	ITEMS.ID AS ITEMID,
    ITEMS.APPROVALLINK,
    BRANCHES.MANAGEMENTEMAIL AS BEMAIL,
    ITEMS.DISPLAYIMAGEPATH
FROM
	items ITEMS
INNER JOIN
	user USER ON 
		ITEMS.GENERATEDBY = USER.USERNAME
INNER JOIN
	branches BRANCHES ON 
		USER.BRANCH = BRANCHES.CODE
WHERE
	ITEMS.ID = __ITEMID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SaveDiscountCalc` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `SaveDiscountCalc`(__ORDERID INT, __PROMO VARCHAR(50), __CALCAMT DECIMAL(19,2), __TAXAMT1 DECIMAL(19,2), __TAXAMT2 DECIMAL(19,2), __TAXAMT3 DECIMAL(19,2), __TAXAMT4 DECIMAL(19,2), __TAXAMT5 DECIMAL(19,2))
BEGIN

	UPDATE 
		orderPromos
	SET
		CALCDISCOUNT = __CALCAMT,
        TAXAMT1 = __TAXAMT1,
        TAXAMT2 = __TAXAMT2,
        TAXAMT3 = __TAXAMT3,
        TAXAMT4 = __TAXAMT4,
        TAXAMT5 = __TAXAMT5
	WHERE
		ORDERID = __ORDERID AND
        PROMOCODE = __PROMO;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SearchForBranches` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `SearchForBranches`(SEARCH VARCHAR(1000), SEARCHBY INTEGER)
BEGIN
	SELECT CODE,NAME FROM branches WHERE
    (
 		(CODE LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,1)) OR
        (NAME LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,2)) 
    );
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SearchForCategories` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `SearchForCategories`(SEARCH VARCHAR(1000), SEARCHBY INTEGER)
BEGIN
	SELECT
		CATID,NAME,DESCRIPTION,LANGUAGE
	FROM
		categories
	WHERE
    (
		(NAME LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,1)) OR
        (DESCRIPTION LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,2)) OR
        (LANGUAGE LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,3))
    );
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SearchForItems` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `SearchForItems`(__SEARCH VARCHAR(1000), __SEARCHBY INTEGER)
BEGIN
	SELECT DISTINCT
		ITEMS.ID,
        ITEMS.CODE,
        ITEMS.DESCRIPTION,
        CONCAT(CAT.NAME,'-',SUBCAT.NAME) AS CATNAME,
        ITEMS.TYPE,
        COALESCE(STOCK.QTYONHAND,0) AS QTYONHAND
	FROM
		items ITEMS
	LEFT OUTER JOIN itemsSubcategoryLink CATLINK ON 
		ITEMS.ID = CATLINK.ITEMID
	LEFT OUTER JOIN subcategories SUBCAT ON 
		CATLINK.SUBCATID = SUBCAT.SUBCATID
	LEFT OUTER JOIN categories CAT ON 
		SUBCAT.CATID = CAT.CATID
	LEFT OUTER JOIN itemsInventory STOCK ON
		ITEMS.ID = STOCK.ITEMID
	WHERE
    (
		(ITEMS.ID LIKE CONCAT('%',__SEARCH,'%') AND __SEARCHBY IN (0,1)) OR
        (ITEMS.CODE LIKE CONCAT('%',__SEARCH,'%') AND __SEARCHBY IN (0,2)) OR
        (ITEMS.DESCRIPTION LIKE CONCAT('%',__SEARCH,'%') AND __SEARCHBY IN (0,3)) OR
        (CONCAT(CAT.NAME,'-',SUBCAT.NAME) LIKE CONCAT('%',__SEARCH,'%') AND __SEARCHBY IN (0,4))
    )
    ORDER BY ITEMS.ID, ITEMS.CODE
    ;    
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SearchForPromos` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `SearchForPromos`(SEARCH VARCHAR(1000), SEARCHBY INTEGER)
BEGIN
	SELECT 
		CODE,
        NAME,
        CODETYPE,
        DATE_FORMAT(STARTDATE,'%Y-%m-%d')  AS STARTDATE,
        DATE_FORMAT(ENDDATE,'%Y-%m-%d') AS ENDDATE
	FROM promos 
    WHERE
    (
		(CODE LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,1)) OR
        (NAME LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,2))
    )
    ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SearchForShipOrders` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `SearchForShipOrders`(IN `__SEARCH` VARCHAR(1000), IN `__SEARCHBY` INT)
BEGIN
	SELECT
		HDR.ORDERID,
        HDR.ORDERREF,
        DATE(HDR.ORDERDATE) AS ORDERDATE,
        HDR.SHIPNAME,
        CONCAT(HDR.SHIPCONTACTFIRSTNAME, ' - ', HDR.SHIPADDRESS, ' ', HDR.SHIPCITY, ' ', HDR.SHIPPROVINCE) AS DESTINATION,
        DATE(HDR.EXPDATE) AS EXPDATE,
        HDR.ORDERSTATUS,
        COALESCE(HDR.PAYMENTREF, '') AS PAYMENTREF,
        COALESCE(SHP.TRACKNUM, '') AS TRACKNUM
	FROM
		orderHeader HDR
		LEFT JOIN shipmentHeader SHP ON SHP.ORDERID = HDR.ORDERID
	WHERE
		(
			CONCAT(HDR.SHIPCONTACTFIRSTNAME, ' - ', HDR.SHIPADDRESS, ' ', HDR.SHIPCITY, ' ', HDR.SHIPPROVINCE) LIKE CONCAT('%', __SEARCH, '%') OR
            HDR.SHIPNAME LIKE CONCAT('%', __SEARCH, '%') OR 
            HDR.ORDERREF LIKE CONCAT('%', __SEARCH, '%') OR 
            HDR.ORDERDATE LIKE CONCAT('%', __SEARCH, '%') OR 
            HDR.EXPDATE LIKE CONCAT('%', __SEARCH, '%')
		) 
        AND (
			(__SEARCHBY = 1 AND HDR.ORDERSTATUS = 'ACTIVE') OR 
            (__SEARCHBY = 2 AND HDR.ORDERSTATUS = 'ACTIVE' AND NOW() >= DATE(HDR.EXPDATE) - INTERVAL 1 DAY) OR 
            (__SEARCHBY = 3 AND HDR.ORDERSTATUS = 'ACTIVE' AND NOW() >= DATE(HDR.EXPDATE) - INTERVAL 2 DAY) OR
            (__SEARCHBY = 4 AND HDR.ORDERSTATUS = 'WAITMA') OR 
            (__SEARCHBY = 5 AND HDR.ORDERSTATUS = 'SHIPPED') OR
            (__SEARCHBY = 6 AND HDR.ORDERSTATUS = 'CANCELLED') OR 
            (__SEARCHBY = 7 AND HDR.ORDERSTATUS = 'REJECTED')
        )
	ORDER BY HDR.ORDERREF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SearchForShipToAddresses` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `SearchForShipToAddresses`(SEARCH VARCHAR(1000), SEARCHBY INTEGER)
BEGIN
	SELECT ID,NAME,ADDRESS,STOREID FROM shipToAddresses WHERE
    (
 		(NAME LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,1)) OR
        (ADDRESS LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,2)) OR 
        (STOREID LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,3))
    );
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SearchForSubCategories` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `SearchForSubCategories`(__CATID INTEGER)
BEGIN
	SELECT * FROM subcategories WHERE CATID = __CATID ORDER BY NAME;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SearchForUsers` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `SearchForUsers`(SEARCH VARCHAR(1000), SEARCHBY INTEGER, ACCESSLEVEL INTEGER)
BEGIN
    SELECT USERNAME,FIRSTNAME,LASTNAME FROM user WHERE
    (
        (USERNAME LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,1)) OR
        (FIRSTNAME LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,2)) OR
        (LASTNAME LIKE CONCAT('%',SEARCH,'%') AND SEARCHBY IN (0,3))
    ) AND USERLEVEL <= ACCESSLEVEL
    ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SubmitOrder` */;
DELIMITER ;;
CREATE DEFINER=`admin`@`localhost` PROCEDURE `SubmitOrder`(__USERNAME NVARCHAR(50), __FIRSTNAME NVARCHAR(200), __LASTNAME NVARCHAR(200), __EMAIL NVARCHAR(45), __SPECINSTR NVARCHAR(1000), __RECEIVERINSTR NVARCHAR(1000), __SHIPPINGMETHOD VARCHAR(45), __SHIPPINGCOST DECIMAL(19,4), __MGRAPPROVAL INT, __PAYMENTREF VARCHAR(100), __PONUMBER VARCHAR(100),  __BILLINGCATEGORY VARCHAR(100))
BEGIN


SET @ORDERREF = IFNULL((SELECT MAX(ORDERREF)+1 FROM orderHeader),10000);


UPDATE 
  orderHeader
SET
  SHIPCONTACTFIRSTNAME = __FIRSTNAME,
    SHIPCONTACTLASTNAME = __LASTNAME,
    SHIPCONTACTEMAIL = __EMAIL,
    SPECIALINSTRUCTIONS = __SPECINSTR,
    RECEIVERINSTRUCTIONS = __RECEIVERINSTR,
    SHIPPINGMETHOD = __SHIPPINGMETHOD,
    SHIPPINGCOST = __SHIPPINGCOST,
    SHIPPINGCOSTTAXAMT1 = ROUND(__SHIPPINGCOST * TAXRATE1,2),
    SHIPPINGCOSTTAXAMT2 = ROUND(__SHIPPINGCOST * TAXRATE2,2),
    SHIPPINGCOSTTAXAMT3 = ROUND(__SHIPPINGCOST * TAXRATE3,2),
    SHIPPINGCOSTTAXAMT4 = ROUND(__SHIPPINGCOST * TAXRATE4,2),
    SHIPPINGCOSTTAXAMT5 = ROUND(__SHIPPINGCOST * TAXRATE5,2),
    APPROVALLINK = CASE WHEN __MGRAPPROVAL = 0 THEN NULL ELSE CONCAT(USERNAME,ORDERID,MD5(MD5(NOW())+ORDERID)) END,
    ORDERREF = CASE WHEN __MGRAPPROVAL = 0 THEN @ORDERREF ELSE 0 END,
    PAYMENTREF = __PAYMENTREF,
    PONUMBER = __PONUMBER,
    BILLINGCATEGORY = __BILLINGCATEGORY


WHERE 
  USERNAME COLLATE utf8_unicode_ci = __USERNAME AND 
    ORDERSTATUS = 'CART';
    
UPDATE orderDetail
  SET 
  SHIPTODATEQTY = ORDERQTY,
  DOWNLOADLINK = CONCAT(ORDERID,'-',ITEMLINE,'-',MD5(MD5(MD5(NOW())+ORDERID)+ITEMLINE))
WHERE
  ORDERQTY = -2 AND
  ORDERID IN (SELECT ORDERID FROM orderHeader WHERE USERNAME COLLATE utf8_unicode_ci = __USERNAME AND ORDERSTATUS = 'CART');   
    
SELECT
  HDR.*,
    DTL.*,
    ITEM.TYPE,
    USER.FIRSTNAME AS USER_FIRSTNAME,
    USER.LASTNAME AS USER_LASTNAME,
    USER.EMAIL AS USER_EMAIL,
    USER.LANGUAGE AS USER_LANGUAGE,
    BRANCH.NAME AS BRANCH_NAME,
    BRANCH.MANAGEMENTEMAIL AS BRANCH_MANAGEMENTEMAIL,
    COALESCE(BRANCHADDRESS.LANGUAGE,'EN') AS BRANCH_LANGUAGE,
    CASE WHEN __MGRAPPROVAL = 0 THEN 'ACTIVE' ELSE 'WAITMA' END AS REALSTATUS,
    COALESCE(ITEM.DLSUGGESTIONS,'') AS DLSUGGESTIONS
FROM
  orderHeader HDR
INNER JOIN
  orderDetail DTL ON 
    HDR.ORDERID = DTL.ORDERID
INNER JOIN
  items ITEM ON 
    DTL.ITEMID = ITEM.ID
INNER JOIN
  user USER ON 
    HDR.USERNAME = USER.USERNAME
INNER JOIN
  branches BRANCH ON 
    USER.BRANCH = BRANCH.CODE
LEFT OUTER JOIN
  (SELECT * FROM branchesAddresses WHERE ISMAIN = 1) BRANCHADDRESS ON 
    BRANCH.CODE = BRANCHADDRESS.CODE
WHERE 
  HDR.USERNAME COLLATE utf8_unicode_ci = __USERNAME AND 
    ORDERSTATUS = 'CART';

IF __MGRAPPROVAL = 0 THEN

        
    SELECT @SHIPLINECOUNT := COUNT(*) FROM orderDetail 
    WHERE ORDERQTY <> -2 AND
        ORDERID IN (SELECT ORDERID FROM orderHeader WHERE USERNAME COLLATE utf8_unicode_ci = __USERNAME AND ORDERSTATUS = 'CART');  
        
  UPDATE 
    orderHeader
  SET
    ORDERSTATUS = CASE WHEN @SHIPLINECOUNT = 0 THEN 'SHIPPED' ELSE 'ACTIVE' END
  WHERE 
    USERNAME COLLATE utf8_unicode_ci = __USERNAME AND 
    ORDERSTATUS = 'CART';   
    
ELSE

  UPDATE 
    orderHeader
  SET
    ORDERSTATUS = CASE WHEN __MGRAPPROVAL = 0 THEN 'ACTIVE' ELSE 'WAITMA' END
  WHERE 
    USERNAME COLLATE utf8_unicode_ci = __USERNAME AND 
    ORDERSTATUS = 'CART'; 

END IF;



END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `UpdateBranchAsset` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `UpdateBranchAsset`(__BRANCHCODE VARCHAR(20), __TAGNAME VARCHAR(100), __TAGVALUE VARCHAR(1000))
BEGIN

	SET @ROWCNT = (SELECT COUNT(*) FROM branchesAssetData WHERE BRANCHCODE = __BRANCHCODE AND TAG = __TAGNAME);

	IF @ROWCNT = 0 THEN
		INSERT INTO
			branchesAssetData
            (BRANCHCODE,TAG,VALUE)
		VALUES
			(__BRANCHCODE,__TAGNAME,__TAGVALUE);
    ELSE
    
		UPDATE 
			branchesAssetData
		SET
			VALUE = __TAGVALUE
		WHERE
			BRANCHCODE = __BRANCHCODE AND
            TAG = __TAGNAME;
    END IF;


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `UpdateItemDisplayImage` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `UpdateItemDisplayImage`(__ITEMID INT, __DISPLAYNAME VARCHAR(200), __DISPLAYPATH VARCHAR(200))
BEGIN
	UPDATE
		items
	SET
		DISPLAYIMAGENAME = __DISPLAYNAME,
        DISPLAYIMAGEPATH = __DISPLAYPATH
	WHERE
		ID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `UpdateItemParametersFile` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `UpdateItemParametersFile`(__ITEMID INT, __PARAMETERSFILE VARCHAR(200), __PARAMETERSPATH VARCHAR(200))
BEGIN
	UPDATE
		items
	SET
		PARAMETERSFILENAME = __PARAMETERSFILE,
        PARAMETERSFILEPATH = __PARAMETERSPATH
	WHERE
		ID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `UpdateItemPreviewImage` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `UpdateItemPreviewImage`(__ITEMID INT, __PREVIEWNAME VARCHAR(200), __PREVIEWPATH VARCHAR(200))
BEGIN
	UPDATE
		items
	SET
		PREVIEWIMAGENAME = __PREVIEWNAME,
        PREVIEWIMAGEPATH = __PREVIEWPATH
	WHERE
		ID = __ITEMID;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `UpdateItemProofPDF` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `UpdateItemProofPDF`(__ITEMID INT, __PDFNAME VARCHAR(200), __PDFPATH VARCHAR(200))
BEGIN
	UPDATE
		items
	SET
		PROOFPDFNAME = __PDFNAME,
        PROOFPDFPATH = __PDFPATH
	WHERE
		ID = __ITEMID;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `UpdateOrderInformation` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `UpdateOrderInformation`(__USERNAME NVARCHAR(50), __FIRSTNAME NVARCHAR(200), __LASTNAME NVARCHAR(200), __EMAIL NVARCHAR(45), __SPECINSTR NVARCHAR(1000), __RECEIVERINSTR NVARCHAR(1000), __SHIPPINGMETHOD VARCHAR(45), __SHIPPINGCOST DECIMAL(19,4), __PONUMBER VARCHAR(100), __BILLINGCATEGORY VARCHAR(100))
BEGIN


UPDATE 
	orderHeader
SET
	SHIPCONTACTFIRSTNAME = __FIRSTNAME,
    SHIPCONTACTLASTNAME = __LASTNAME,
    SHIPCONTACTEMAIL = __EMAIL,
    SPECIALINSTRUCTIONS = __SPECINSTR,
    RECEIVERINSTRUCTIONS = __RECEIVERINSTR,
    SHIPPINGMETHOD = __SHIPPINGMETHOD,
    SHIPPINGCOST = __SHIPPINGCOST,
    SHIPPINGCOSTTAXAMT1 = __SHIPPINGCOST * TAXRATE1,
    SHIPPINGCOSTTAXAMT2 = __SHIPPINGCOST * TAXRATE2,
    SHIPPINGCOSTTAXAMT3 = __SHIPPINGCOST * TAXRATE3,
    SHIPPINGCOSTTAXAMT4 = __SHIPPINGCOST * TAXRATE4,
    SHIPPINGCOSTTAXAMT5 = __SHIPPINGCOST * TAXRATE5,
	PONUMBER = __PONUMBER,
    BILLINGCATEGORY = __BILLINGCATEGORY
WHERE 
	USERNAME COLLATE utf8_unicode_ci = __USERNAME AND 
    ORDERSTATUS = 'CART';

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `UserCancelOrder` */;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `UserCancelOrder`(__USERNAME VARCHAR(100), __ORDERID INT)
BEGIN
 UPDATE
 orderHeader
 SET
 APPROVALLINK = NULL,
 ORDERSTATUS = 'CANCELLED',
 ORDERMODIFIED = CURRENT_TIMESTAMP
 WHERE
 ORDERID = __ORDERID AND
 USERNAME = __USERNAME; 
 
 UPDATE 
 orderDetail
 SET
 ORDERQTY = 0,
 SHIPTODATEQTY = 0
 WHERE
 ORDERID = __ORDERID AND
 ORDERID IN (SELECT ORDERID FROM orderHeader WHERE USERNAME = __USERNAME);
END ;;
DELIMITER ;


