<?php
include_once("_nemo.list.cls.php");

/*
ALTER TABLE `slaQuote` drop FOREIGN KEY `slaQuote.strUser`;
ALTER TABLE `slaQuote` ADD CONSTRAINT `slaQuote.strUser` FOREIGN KEY (`refWPSID`) REFERENCES `sysUser` (`UserID`) ON UPDATE CASCADE ON DELETE NO ACTION;

	//20160314 - Finalize depreciated as status is now ALWAYS proposal - Christiaan
	//20160316 - Disable this if not an admin or admin dev - Christiaan
	//20180319 - Check if IWP Option is chosen // used when checking if Step 2 of the wizard is available - CL
	//20180320 - Check if a Proposal contains inactive Services// used in process to disallow editing if its an old Proposal - CL
	//20180320 - Add if Statement to make VAT 14% if createDate of Proposal is < "20180401"
	//20180322 - Add page break infront of BMS section at PJ's request - CL
	//20180326 - remove all mention of (CRMIntegrator) and replace with "OM Wealth Xplan Multi-site" - CL
	//20180411 - Fix format of SLA filename - CL
	//20180411 - Add cleanFilename function to remove unwanted characters and format string correctly - CL
	//20181126 - IBC Course - pj
	//20181206 - $arrTermItems[0] is always a paragraph, make an exception not to add a bullet and do not indent - Rachel
	20181207 - Removed width from both tds TO accomodate longer emails - Rachel
	//20191117 - Set different footer on last page - Rachel
	//20201012 - Save presonalised Corporate Partner Prices - Rachel
*/

class Quote extends NemoList
{
	private $ID = 0;

	public static $BTN_AMEND_DETAILS_FINANCIAL_PLANNING = "Setup Planners";
	public static $BTN_AMEND_DETAILS_BMS = "Setup Services";

	public static $STRATEGIC_PARTNER = "Strategic Partner";
	public static $CORPORATE_PARTNER = "Corporate Partner";
	public static $STRATEGIC_ACSIS_PARTNER = "Strategic Partner (Acsis Legacy only)";

	public function __construct($DataKey)
	{
		global $xdb;


		$this->Filters[frWPS]->tag = "select";
		//20160316 - Disable this if not an admin or admin dev - Christiaan
		if($_SESSION["USER"]->SECURITYGROUPID != 1 && $_SESSION["USER"]->SECURITYGROUPID != 2)
		{
			$this->Filters[frWPS]->html->disabled = "disabled";


			$row = $xdb->getRowSQL("SELECT WPSID FROM vieWPS WHERE WPSID =".$_SESSION["USER"]->ID."");
			if($row)
			{
				$this->Filters[frWPS]->html->value = $_SESSION["USER"]->ID;
			}
			else
			{
				$this->Filters[frWPS]->html->value = "-1"; //defalt value = 0, -1 = '- Unassigned -'
			}
		}
		else
		{
			$this->Filters[frWPS]->html->value = "0";
		}

		$this->Filters[frWPS]->html->class = "controlText";
		$this->Filters[frWPS]->sql = "
				SELECT -1 AS ControlValue, '- Select -' AS ControlText
			UNION ALL
				SELECT 0 AS ControlValue, '- All -' AS ControlText
			UNION ALL
				SELECT WPSID AS ControlValue, strWPS AS ControlText
				FROM vieWPS
				WHERE vieWPS.blnActive = 1
			ORDER BY ControlText ASC";

		$this->Filters[frPartnerType]->tag = "select";
		$this->Filters[frPartnerType]->html->value = ""; //defalt value = 0, -1 = '- Unassigned -'
		$this->Filters[frPartnerType]->html->class = "controlText";
		$this->Filters[frPartnerType]->sql = "
				SELECT '' AS ControlValue, '- All -' AS ControlText
			UNION ALL
				SELECT 'Partner' AS ControlValue, 'Partner' AS ControlText
			UNION ALL
				SELECT 'Strategic Partner' AS ControlValue, 'Strategic Partner' AS ControlText";

		$this->Filters[frStatus]->tag = "select";
		$this->Filters[frStatus]->html->value = ""; //defalt value = 0, -1 = '- Unassigned -'
		$this->Filters[frStatus]->html->class = "controlText";
		$this->Filters[frStatus]->sql = "
				SELECT '' AS ControlValue, '- All -' AS ControlText
			UNION ALL
				SELECT strStatus AS ControlValue, concat(strStatus, ' (',count(*),')') AS ControlText
				FROM slaQuote
				GROUP BY strStatus
			ORDER BY ControlText ASC";

		$this->Filters[frIgnoreDate]->tag = "input";
		$this->Filters[frIgnoreDate]->html->value = "checked";
		$this->Filters[frIgnoreDate]->html->type = "checkbox";
		$this->Filters[frIgnoreDate]->html->onclick = "d('frStartDate').disabled=this.checked;d('frEndDate').disabled=this.checked;";

		$this->Filters[frStartDate]->tag = "input";
		$this->Filters[frStartDate]->html->value = date("Y-m-01");
		$this->Filters[frStartDate]->html->type = "text";
		$this->Filters[frStartDate]->html->class = "controlText controlNumeric datePicker";

		$this->Filters[frEndDate]->tag = "input";
		$this->Filters[frEndDate]->html->value = date("Y-m-d");
		$this->Filters[frEndDate]->html->type = "text";
		$this->Filters[frEndDate]->html->class = "controlText controlNumeric datePicker";

		$this->Filters[frSearch]->tag = "input";
		$this->Filters[frSearch]->html->value = "";
		$this->Filters[frSearch]->html->type = "text";
		$this->Filters[frSearch]->html->class = "controlText";

		parent::__construct($DataKey);
	}

	protected function ToolBar()
	{
		return "
		<div id='divToolBar' style='min-height: 90px;'>
			<div style='float:left;'>
				<table class='tblBlank'>
					<tr>
						<td><img src='images/extraimages/header/icon-48-module.png' height='44'></img></td>
						<td style='padding: 16px;'><span class='textHeading'>". $this->ToolBar->Label ."</span></td>
						<td style='position: relative; border: 0px dashed orange; padding: 0px;'>". $this->ToolBar->Block . $this->renderFilters() ."</td>
					</tr>
				</table>
			</div>
			<div class='divButtons'>
				". $this->renderToolbarButtons() ."
			</div>
		</div>
		";
	}

	public function getList()
	{
		if($this->Filters[frSearch]->html->value != "")
		{
			$like = "LIKE(". $this->db->qs("%".$this->Filters[frSearch]->html->value."%") .")";
			$Where .= " AND (slaQuote.strQuote $like OR slaQuote.strPartner $like OR slaQuote.strClient $like OR slaQuote.strEmail $like OR slaQuote.strVersion $like )";
		}

		if($this->Filters[frWPS]->html->value == -1)
		{
			return "No records match your filter.";
		}
		else if($this->Filters[frWPS]->html->value != 0)
		{
			$Where .= " AND slaQuote.refWPSID = ". $this->Filters[frWPS]->html->value;
		}

		if($this->Filters[frPartnerType]->html->value != "")
		{
			$Where .= " AND slaQuote.strPartnerType = '". $this->Filters[frPartnerType]->html->value."'";
		}

		if($this->Filters[frStatus]->html->value != "")
		{
			$Where .= " AND slaQuote.strStatus = '". $this->Filters[frStatus]->html->value."'";
		}

		if($this->Filters[frIgnoreDate]->html->checked != "checked")
		{
			$Where .= " AND ((left(dtCreationDate,10) >= '". $this->Filters[frStartDate]->html->value ."' AND left(dtCreationDate,10) <= '". $this->Filters[frEndDate]->html->value ."')
				OR (left(dtAgreementStartDate,10) >= '". $this->Filters[frStartDate]->html->value ."' AND left(dtAgreementStartDate,10) <= '". $this->Filters[frEndDate]->html->value ."'))";
		}


		$this->ListSQL("
			SELECT slaQuote.QuoteID, vieWPS.strWPS AS 'Prepared by', slaQuote.strPartner AS Partner, slaQuote.strClient AS 'Contact Person', slaQuote.strPartnerType AS 'Partner Type'
			, concat(FORMAT(slaQuote.dblTotalCostYear1, 0),' / ', FORMAT(slaQuote.dblTotalCostMaintenance , 0)) AS 'Value (Y1/Ongoing)'
			, slaQuote.strStatus AS Status
			, slaQuote.dtCreationDate AS 'Date Created', slaQuote.dtAgreementStartDate AS 'Start Date', slaQuote.strLastUser AS 'Last User', slaQuote.dtLastEdit AS 'Last Edit'
			FROM slaQuote LEFT JOIN vieWPS ON slaQuote.refWPSID = vieWPS.WPSID
			WHERE 1=1 $Where
			ORDER BY slaQuote.strQuote", 0);//concat(slaQuote.strQuote, ' (v',slaQuote.strVersion,')') AS 'Quote Name',

		$this->Columns["Value (Y1/Ongoing)"]->html->align = "right";

		return $this->renderTable("Quote List");
	}

	//20180319 - Check if IWP Option is chosen // used when checking if Step 2 of the wizard is available - CL
	public static function checkIWPServiceSelected($QuoteID)
	{
		global $xdb;
		//ini
		//go
		$rstQI = $xdb->doQuery("
			SELECT slaQuoteItem.*, slaService.*
			FROM slaQuoteItem LEFT JOIN slaService on slaQuoteItem.refServiceID = slaService.ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Financial Planner Service' OR ServiceID IS NULL)
			ORDER BY strPlannerName",0);
		if($xdb->Rows > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	//20180320 - Check if a Proposal contains inactive Services// used in process to disallow editing if its an old Proposal - CL
	public static function checkProposalContainsOnlyActiveServices($QuoteID)
	{
		global $xdb;
		//ini
		//go
		$rstQI = $xdb->doQuery("
			SELECT slaQuoteItem.*, slaService.*
			FROM slaQuoteItem LEFT JOIN slaService on slaQuoteItem.refServiceID = slaService.ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND slaService.blnActive = 0
			ORDER BY strPlannerName",0);
		if($xdb->Rows > 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	public function setupFinancialPlanning($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		//clean QuoteID

		$rowQuote = $xdb->getRowSQL("SELECT * FROM slaQuote WHERE slaQuote.QuoteID=".$xdb->qs($QuoteID),0);
		$strPartnerType =  $rowQuote->strPartnerType;

		$intPlannerColspan = 3;
		$intServiceColspan = 3;
		$dblTotalRateYear1 = 0;
		$dblTotalRateMaintenance = 0;

		//Preload array
		$arrService = array();
		$rstService = $xdb->doQuery("
			SELECT * FROM slaService
			WHERE slaService.strType='Financial Planner Service'
			ORDER BY intDisplayOrder,strService DESC", 0);
		while($rowService = $xdb->fetch_object($rstService))
		{
			$arrService[$rowService->ServiceID] = $rowService;
		}
		// print_rr($arrService);

		//go
		$rstQI = $xdb->doQuery("
			SELECT slaQuoteItem.*, slaService.*
			FROM slaQuoteItem LEFT JOIN slaService on slaQuoteItem.refServiceID = slaService.ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Financial Planner Service' OR ServiceID IS NULL)
			ORDER BY strPlannerName", 0);
		while($rowQI = $xdb->fetch_object($rstQI))
		{//print_rr($rowQI);
			//ini

			//print_rr($rowQI); die;
			//$btnDelete = "<a href='?Action=DeleteFinPlanning&QuoteID=$QuoteID&QuoteItemID=$rowQI->QuoteItemID' onclick = \"return confirm('Are you sure you want to remove this Financial Planner?');\"><img width='20px' src='images/delete.png' /></a>";
			//20180320 - Check if a Proposal contains inactive Services// used in process to disallow editing if its an old Proposal - CL
			if(Quote::checkProposalContainsOnlyActiveServices($QuoteID))
			{
				$btnDelete = "<a onclick = 'return jsDeletePlanner($rowQI->QuoteItemID);'><img width='20px' src='images/delete.png' /></a>";
			}
			else
			{
				$btnDelete = "n/a";
			}
			$i++;

			$tblService = "";


			$intIBC_Yes_RadChecked = "";
			$intIBC_No_RadChecked = "";
			$intIBC_Yes_RadChecked = $rowQI->intIBC=="1"?"checked":""; 
			$intIBC_No_RadChecked = $rowQI->intIBC=="0"?"checked":"";

			$intAssetMapPlanner_Yes_RadChecked = "";
			$intAssetMapPlanner_No_RadChecked = "";
			$intAssetMapPlanner_Yes_RadChecked = $rowQI->intAssetMapPlanner=="1"?"checked":""; 
			$intAssetMapPlanner_No_RadChecked = $rowQI->intAssetMapPlanner=="0"?"checked":"";

			$intAssetMapAdmim_Yes_RadChecked = "";
			$intAssetMapAdmin_No_RadChecked = "";
			$intAssetMapAdmin_Yes_RadChecked = $rowQI->intAssetMapAdmin=="1"?"checked":""; 
			$intAssetMapAdmin_No_RadChecked = $rowQI->intAssetMapAdmin=="0"?"checked":"";
			

			$blnFirstService = 1;
			foreach ($arrService AS $ServiceID => $rowService)
			{
				$cssInactiveService = "";
				//20180319 - check if service is selected even while inactive or just active - CL
				if($rowService->blnActive == 1 || $rowQI->refServiceID == $ServiceID)
				{
					// $rowCheckQI = $xdb->getRowSQL("SELECT slaQuote.QuoteID, slaQuoteItem.QuoteItemID, slaService.ServiceID
					//                         FROM slaQuote INNER JOIN (slaQuoteItem INNER JOIN slaService ON slaQuoteItem.refServiceID = slaService.ServiceID) ON slaQuote.QuoteID = slaQuoteItem.refQuoteID
					//                         WHERE (((slaQuote.QuoteID)=$QuoteID) AND ((slaService.ServiceID)=$ServiceID) AND ((slaService.strType)='Financial Planner Service'))
					//                         ",0);

					//$strServiceRadChecked = "";
					$strRateYear1RadChecked = "";
					$strRateMaintenanceRadChecked = "";

					if($rowQI->refServiceID == $ServiceID)
					{
						//$strServiceRadChecked = "checked";

						$strRateYear1RadChecked = $rowQI->strRateType=="Year 1"?"checked":"";
						$strRateMaintenanceRadChecked = $rowQI->strRateType=="Maintenance"?"checked":"";

						
					}


					//20180319 - Add greyed out text if the selected service is inactive- CL
					// if($rowService->blnActive == 0)
					// {
					//    $cssInactiveService = "color:red;";
					//    $titleInactiveReason = "title = 'Older Service (being phased out)'";
					// }

					$strborderTop = "border-top: 1px dashed #808080;";
					if($blnFirstService == 1)
					{
						$strborderTop = "";
						$blnFirstService = 0;
					}


					//20181126 - IBC Course - pj
					//if PT != Q.SP then disable IBC $rowQuote->strPartnerType == Quote::$STRATEGIC_PARTNER

					//if S.blnIBC render IBC - //20181126 - IBC Course - pj

//20191120 - Added Asset Map Pilot - Rachel


					if($rowService->blnIBC == 1)
					{                  
						if( $rowQuote->strPartnerType == Quote::$STRATEGIC_PARTNER || $rowQuote->strPartnerType == Quote::$CORPORATE_PARTNER ){//SP and Corporate Partner only!
							$tblService .= "
								<tr>                  
									<td style='padding-left:2px;padding-right:2px;width:20em;$strborderTop $cssInactiveService' $titleInactiveReason>                           
										$rowService->strService</td>
									<td style='padding-left:1px;padding-right:0;width:2em;vertical-align: middle;border-left: 1px solid #808080;$strborderTop'>
										<input type='radio' name='intIBC[".$rowQI->QuoteItemID."]' data='true' id='intIBC_Yes_".$rowQI->QuoteItemID."_$ServiceID' $intIBC_Yes_RadChecked value='1' onclick=\"\" />
									</td>
									<td style='padding-left:0;padding-right:2px;width:4em;text-align:center;$strborderTop $cssInactiveService'>                           
										<span>Yes</span>
									</td>
									<td style='padding-left:1px;padding-right:0;width:2em;vertical-align: middle;border-left: 1px solid #808080;$strborderTop'>
										<input type='radio' name='intIBC[".$rowQI->QuoteItemID."]' data='false' id='intIBC_No_".$rowQI->QuoteItemID."_$ServiceID' $intIBC_No_RadChecked value='0' onclick=\"\" />
									</td>
									<td style='padding-left:0;padding-right:2px;width:4em;text-align:center;$strborderTop $cssInactiveService'>
										<span>No</span>
									</td>
								</tr>";
						}

					}elseif ($rowService->blnAssetMapPlanner == 1 ){

						//SP only!
							$tblService .= "
								<tr>                  
									<td style='padding-left:2px;padding-right:2px;width:20em;$strborderTop $cssInactiveService' $titleInactiveReason>                           
										$rowService->strService</td>
									<td style='padding-left:1px;padding-right:0;width:2em;vertical-align: middle;border-left: 1px solid #808080;$strborderTop'>
										<input type='radio' name='intAssetMapPlanner[".$rowQI->QuoteItemID."]' data='true' id='intAssetMapPlanner_Yes_".$rowQI->QuoteItemID."_$ServiceID' $intAssetMapPlanner_Yes_RadChecked value='1' onclick=\"\" />
									</td>
									<td style='padding-left:0;padding-right:2px;width:4em;text-align:center;$strborderTop $cssInactiveService'>                           
										<span>Yes</span>
									</td>
									<td style='padding-left:1px;padding-right:0;width:2em;vertical-align: middle;border-left: 1px solid #808080;$strborderTop'>
										<input type='radio' name='intAssetMapPlanner[".$rowQI->QuoteItemID."]' data='false' id='intAssetMapPlanner_No_".$rowQI->QuoteItemID."_$ServiceID' $intAssetMapPlanner_No_RadChecked value='0' onclick=\"\" />
									</td>
									<td style='padding-left:0;padding-right:2px;width:4em;text-align:center;$strborderTop $cssInactiveService'>
										<span>No</span>
									</td>
								</tr>";
						

						# code...
					}elseif ($rowService->blnAssetMapAdmin == 1 ){

						//SP only!
							$tblService .= "
								<tr>                  
									<td style='padding-left:2px;padding-right:2px;width:20em;$strborderTop $cssInactiveService' $titleInactiveReason>                           
										$rowService->strService</td>
									<td style='padding-left:1px;padding-right:0;width:2em;vertical-align: middle;border-left: 1px solid #808080;$strborderTop'>
										<input type='radio' name='intAssetMapAdmin[".$rowQI->QuoteItemID."]' data='true' id='intAssetMapAdmin_Yes_".$rowQI->QuoteItemID."_$ServiceID' $intAssetMapAdmin_Yes_RadChecked value='1' onclick=\"\" />
									</td>
									<td style='padding-left:0;padding-right:2px;width:4em;text-align:center;$strborderTop $cssInactiveService'>                           
										<span>Yes</span>
									</td>
									<td style='padding-left:1px;padding-right:0;width:2em;vertical-align: middle;border-left: 1px solid #808080;$strborderTop'>
										<input type='radio' name='intAssetMapAdmin[".$rowQI->QuoteItemID."]' data='false' id='intAssetMapAdmin_No_".$rowQI->QuoteItemID."_$ServiceID' $intAssetMapAdmin_No_RadChecked value='0' onclick=\"\" />
									</td>
									<td style='padding-left:0;padding-right:2px;width:4em;text-align:center;$strborderTop $cssInactiveService'>
										<span>No</span>
									</td>
								</tr>";
						

						# code...
					}else {
						if($rowQuote->strPartnerType != Quote::$STRATEGIC_ACSIS_PARTNER)
						{
						$tblService .= " 
							<tr>                 
								<td style='padding-left:2px;padding-right:2px;width:20em;$strborderTop $cssInactiveService' $titleInactiveReason>                           
									$rowService->strService</td>
								<td style='padding-left:1px;padding-right:0;width:2em;vertical-align: middle;border-left: 1px solid #808080;$strborderTop'>
									<input type='radio' name='strRateType[".$rowQI->QuoteItemID."]' data='$rowService->dblCostYear1' id='strRateTypeYear1_".$rowQI->QuoteItemID."_$ServiceID' $strRateYear1RadChecked value='Year 1' onclick=\"jsSetCurrentServiceID($rowQI->QuoteItemID,$ServiceID);jsSetRate($rowQI->QuoteItemID,$ServiceID,'Year 1');\" />
								</td>
								<td style='padding-left:0;padding-right:2px;width:4em;text-align:right;$strborderTop $cssInactiveService'>
									<span>".number_format($rowService->dblCostYear1,2, '.', ',')."</span>
								</td>
								<td style='padding-left:1px;padding-right:0;width:2em;vertical-align: middle;border-left: 1px solid #808080;$strborderTop'>
									<input type='radio' name='strRateType[".$rowQI->QuoteItemID."]' data='$rowService->dblCostMaintenance' id='strRateTypeMaintenance_".$rowQI->QuoteItemID."_$ServiceID' $strRateMaintenanceRadChecked value='Maintenance' onclick=\"jsSetCurrentServiceID($rowQI->QuoteItemID,$ServiceID);jsSetRate($rowQI->QuoteItemID,$ServiceID,'Maintenance');\" />
								</td>
								<td style='padding-left:0;padding-right:2px;width:4em;text-align:right;$strborderTop $cssInactiveService'>
									<span>".number_format($rowService->dblCostMaintenance,2, '.', ',')."</span>
								</td>
							</tr>";
						}
					}


					//<input type='radio' name='strRateType".$i."[".$rowQI->QuoteItemID."]' id='strRateType".$i."_".$rowQI->QuoteItemID."'>
							  // <input type='hidden' name='refServiceID[".$rowQI->QuoteItemID."][$ServiceID]' id='refServiceID_".$rowQI->QuoteItemID."_ $ServiceID' value='$ServiceID' />

								//<input type='radio' name='radService[".$rowQI->QuoteItemID."]' id='radService_".$rowQI->QuoteItemID."' $strServiceRadChecked value='$ServiceID' />
				}//end if - check if service is selected even while inactive or just active
			}

			//go

			if($currentPlanner != $rowQI->strPlannerName."_". $rowQI->strPlannerID ."_". $rowQI->strPlannerEmail)
			{//20181126 - IBC Course - pj            
				$tr .= "
					<tr>
						<td align='center'>
							<label class='tdCount textColour'>$i</label>
							<input type='hidden' name='QuoteItemID[$rowQI->QuoteItemID]' id='QuoteItemID_$rowQI->QuoteItemID' value='".$rowQI->QuoteItemID."'  />
						</td>
						<td align='left' colspan=$intPlannerColspan>
							<input type='text' name='strPlannerName[$rowQI->QuoteItemID]'  id='strPlannerName' value=\"$rowQI->strPlannerName\" class='controlText controlWideMax' />
						</td>
						<td align='left' colspan='$intServiceColspan' style='border-collapse:collapse;margin:0;padding:0;border-spacing:0;'>
							<input type='hidden' name='refServiceID[".$rowQI->QuoteItemID."]' id='refServiceID_".$rowQI->QuoteItemID."' value='".$rowQI->refServiceID."' />
							<table style='table-layout: fixed;margin:0;padding:0;border:0;border-collapse:collapse; height:100%;width:100%;'>
								$tblService
							</table>
						</td>
						<td>
							<input type='input' name='strRateYear1[$rowQI->QuoteItemID]' id='strRateYear1_$rowQI->QuoteItemID' value='".number_format($rowQI->dblRateYear1,2, '.', ',')."' class='controlText controlWideMax controlLabel' style='text-align:right;' />
							<input type='hidden' name='dblRateYear1[$rowQI->QuoteItemID]' id='dblRateYear1_$rowQI->QuoteItemID' value='".$rowQI->dblRateYear1."'  />
						</td>
						<td>
							<input type='input' name='strRateMaintenance[$rowQI->QuoteItemID]' id='strRateMaintenance_$rowQI->QuoteItemID' value='".number_format($rowQI->dblRateMaintenance,2, '.', ',')."' class='controlText controlWideMax controlLabel' style='text-align:right;' />
							<input type='hidden' name='dblRateMaintenance[$rowQI->QuoteItemID]' id='dblRateMaintenance_$rowQI->QuoteItemID' value='".$rowQI->dblRateMaintenance."'  />
						</td>
						<td align='center'>
							$btnDelete
						</td>
					</tr>";
					// planner details, delete later if we never go back to using it
					// <tr>
					//    <th>ID</th>
					//    <th>Email</th>
					//    <th>Contact</th>
					// </tr>
					// <tr>
					//    <td align='left'><input type='text' name='strPlannerID[$rowQI->QuoteItemID]'  id='strPlannerID_$rowQI->QuoteItemID' value=\"$rowQI->strPlannerID\" class='controlText controlWideMax' /></td>
					//    <td align='left'><input type='text' name='strPlannerEmail[$rowQI->QuoteItemID]'  id='strPlannerEmail_$rowQI->QuoteItemID' value=\"$rowQI->strPlannerEmail\" class='controlText controlWideMax' /></td>
					//    <td align='left'><input type='text' name='strPlannerCell[$rowQI->QuoteItemID]'  id='strPlannerCell_$rowQI->QuoteItemID' value=\"$rowQI->strPlannerCell\" class='controlText controlWideMax' /></td>
					// </tr>";
				}

			//post
			$dblTotalRateYear1 += $rowQI->dblRateYear1;
			$dblTotalRateMaintenance += $rowQI->dblRateMaintenance;

			$currentPlanner = $rowQI->strPlannerName."_". $rowQI->strPlannerID ."_". $rowQI->strPlannerEmail;


		}//eoFE QI

		$trTotal = "
					<tr>
						<td style='text-align:right;' colspan=7>
							<b>Total:</b>
						</td>
						<td style='text-align:right;'>
							<input type='text' name='strTotalRateYear1' id='strTotalRateYear1' value=\"".number_format($dblTotalRateYear1,2, '.', ',')."\" class='controlText controlLabel controlWideMax' style='text-align:right;' readonly />
							<input type='hidden' name='dblTotalRateYear1' id='dblTotalRateYear1' value=\"".$dblTotalRateYear1."\" />
						</td>
						<td style='text-align:right;'>
							<input type='text' name='strTotalRateMaintenance' id='strTotalRateMaintenance' value=\"".number_format($dblTotalRateMaintenance,2, '.', ',')."\" class='controlText controlLabel controlWideMax' style='text-align:right;' readonly />
							<input type='hidden' name='dblTotalRateMaintenance' id='dblTotalRateMaintenance' value=\"".$dblTotalRateMaintenance."\" />
						</td>
						<td>
						</td>
					</tr>
				";

		// $content = "
		//    <div style=''>
		//       <table cellpadding=0 cellspacing=0 border=0 style='width:100%;padding:0;margin:0px;border:0;border-collapse:collapse;background-color:none;'>
		//          <tr>
		//             <td style='width:60%;vertical-align:top; padding: 0px;'>
			$content = "
				<table cellpadding=2 cellspacing=1 border=1 class='tblNemoDetails' style='table-layout: fixed;width:100%;margin:0px;border-collapse:collapse;'>
					<caption>Step 1: Set up Financial Planning Services</caption>
					<tr>
						<th style='width:30px' align='center' nowrap>#</th>
						<th style='' colspan=$intPlannerColspan>Planner</th>
						<th style='width:20em;padding-left:2px;padding-right:2px;'>Service</th>
						<th style='width:6em;padding-left:1px;padding-right:2px;'>Year 1</th>
						<th style='width:6em;padding-left:1px;padding-right:2px;'>Ongoing</th>
						<th style='width:50px'>Fees<br/>Year 1</th>
						<th style='width:50px'>Fees<br/>Ongoing</th>
						<th style='width:40px'>Delete</th>
					</tr>
					$tr
					$trTotal
				</table>
				<input type='hidden' id='strPartnerType' name='strPartnerType' value=\"$strPartnerType\" />
				<input type='hidden' id='Mode' name='Mode' value='FinPlanning' />
				<input type='hidden' id='QuoteID' name='QuoteID' value='$QuoteID' />
				<input type='hidden' id='DeleteQuoteItemID' name='DeleteQuoteItemID' value='' />
				<input type='submit' id='btnDeletePlanner' name='Action' value='DeleteFinPlanning' style='display:none;'/>"
				.js("
				function jsDeletePlanner(QuoteItemID)
				{
					if(confirm('Are you sure you want to remove this Financial Planner?'))
					{
						$('#DeleteQuoteItemID').val(QuoteItemID);
						$('#btnDeletePlanner').click();
					}
				}

				function jsSetCurrentServiceID(QuoteItemID, refServiceID)
				{
					
					$('#refServiceID_'+QuoteItemID).val(refServiceID);
				}

				function jsSetRate(QuoteItemID, refServiceID, strRateType)
				{
					/*year 1*/
					var dblTotalRateYear1 = parseFloat($('#dblTotalRateYear1').val());
					var dblCurrentRateYear1 = parseFloat($('#dblRateYear1_'+QuoteItemID).val());

					var dblRateYear1 = '0';
					if(strRateType == 'Year 1')
					{
						dblRateYear1 = parseFloat($('#strRateTypeYear1_'+QuoteItemID+'_'+refServiceID).attr('data'));
					}
					else
					{
						dblRateYear1 = parseFloat($('#strRateTypeMaintenance_'+QuoteItemID+'_'+refServiceID).attr('data'));
					}

					var dblNewRateYear1 = parseFloat(dblRateYear1);
					var dblNewTotalRateYear1 = parseFloat((dblTotalRateYear1 - dblCurrentRateYear1) + dblRateYear1);
					var strNewRateYear1 = dblNewRateYear1.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");
					var strNewTotalRateYear1 = dblNewTotalRateYear1.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					$('#dblRateYear1_'+QuoteItemID).val(dblNewRateYear1);
					$('#strRateYear1_'+QuoteItemID).val(strNewRateYear1);
					$('#dblTotalRateYear1').val(dblNewTotalRateYear1);
					$('#strTotalRateYear1').val(strNewTotalRateYear1);

					/*maintenance*/
					var dblTotalRateMaintenance = parseFloat($('#dblTotalRateMaintenance').val());
					var dblCurrentRateMaintenance = parseFloat($('#dblRateMaintenance_'+QuoteItemID).val());
					var dblRateMaintenance = parseFloat($('#strRateTypeMaintenance_'+QuoteItemID+'_'+refServiceID).attr('data'));

					var dblNewRateMaintenance = parseFloat(dblRateMaintenance);
					var dblNewTotalRateMaintenance = parseFloat((dblTotalRateMaintenance - dblCurrentRateMaintenance) + dblRateMaintenance);
					var strNewRateMaintenance = dblNewRateMaintenance.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");
					var strNewTotalRateMaintenance = dblNewTotalRateMaintenance.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					$('#dblRateMaintenance_'+QuoteItemID).val(dblNewRateMaintenance);
					$('#strRateMaintenance_'+QuoteItemID).val(strNewRateMaintenance);
					$('#dblTotalRateMaintenance').val(dblNewTotalRateMaintenance);
					$('#strTotalRateMaintenance').val(strNewTotalRateMaintenance);
				}
				");
						// </td>
						// <td style='width:40%; padding: 0px; padding-left: 20px;' valign='top' >";
		// $content .= Quote::previewQuote($QuoteID);
		// $content .= "</td>
		//          </tr>
		//       </table>
		//    </div>";

		return $content;
	}

	public function setupBMS($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		$rowQuote = $xdb->getRowSQL("SELECT * FROM slaQuote WHERE slaQuote.QuoteID=".$xdb->qs($QuoteID)."",0);
		$strPartnerType =  $rowQuote->strPartnerType;

		$tr = "";
		$dblTotalRateYear1 = 0;
		$dblTotalRateMaintenance = 0;

		$intCurrentServiceID = 0;

		//*****************************************************************************************************************************
		//******************************************              BMS table                   ****************************************
		//*****************************************************************************************************************************

		//Preload array
		$arrService = array();
		$rstService = $xdb->doQuery("SELECT * FROM slaService WHERE slaService.strType='Business Management Service' ORDER BY intDisplayOrder,strService DESC", 0);

		while($rowService = $xdb->fetch_object($rstService))
		{
			$arrService[$rowService->ServiceID] = $rowService;
		}
		//print_rr($arrService); die;

		//go
		$rstQI = $xdb->doQuery("
			SELECT slaQuoteItem.*, slaService.*
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Business Management Service')
			ORDER BY slaService.intDisplayOrder",0);
		while($rowQI = $xdb->fetch_object($rstQI))
		{
			$arrServiceQuoteItem[$rowQI->ServiceID] = $rowQI;
		}
		//print_rr($arrServiceQuoteItem);

		foreach ($arrService AS $ServiceID => $rowService)
		{
			//20180319 - check if service is selected even while inactive or just active - CL
			if($rowService->blnActive == 1 || $arrServiceQuoteItem[$ServiceID]->refServiceID == $ServiceID)
			{
				//if there is a QuoteItem record then use the rate from that, otherwise use the default rate
				if(isset($arrServiceQuoteItem[$ServiceID]))
				{
					$strServiceRadChecked = "checked='checked'";
					$strRateYear1RadChecked = $arrServiceQuoteItem[$ServiceID]->strRateType=="Year 1"?"checked":"";
					$strRateMaintenanceRadChecked = $arrServiceQuoteItem[$ServiceID]->strRateType=="Maintenance"?"checked":"";

					$dblRateYear1 = $arrServiceQuoteItem[$ServiceID]->dblRateYear1;
					$dblRateMaintenance = $arrServiceQuoteItem[$ServiceID]->dblRateMaintenance;

					//if this is not the xplan service
					if($ServiceID != 8 && $ServiceID != 34)
					{
						$intCurrentServiceID = $ServiceID;
					}
				}
				else
				{
					$strServiceRadChecked ="";
					$strRateYear1RadChecked ="";
					$strRateMaintenanceRadChecked ="";

					$dblRateYear1 = 0;
					$dblRateMaintenance = 0;
				}

				switch($ServiceID)
				{
					case "1": //Knowmore Standard
					case "2": //Knowmore Plus
					case "3": //Knowmore BCH M
					case "4": //Knowmore BCH H
					case "22": //Knowmore Consulting Services
					//case "8": //X Plan
					if($strPartnerType != "Strategic Partner (Acsis Legacy only)")
					{
					$tr .= "
						<tr>
							<td colspan='2'>
								$rowService->strService
							</td>
							<td style='width:20px;text-align:left;'>
								<input type='radio' name='strRateType' data='$rowService->dblCostYear1' id='strRateTypeYear1_$ServiceID' service='$ServiceID' $strRateYear1RadChecked value='Year 1' onclick='jsSetRateYear1($ServiceID); jsSetCurrentServiceID($ServiceID); checkAdditionalLicensesAvailable();' />
							</td>
							<td style='width:60px;text-align:right;border-left:hidden;'>
								".number_format($rowService->dblCostYear1,2, '.', ',')."
							</td>
							<td style='width:20px;text-align:left;'>
								 <input type='radio' name='strRateType' data='$rowService->dblCostMaintenance' id='strRateTypeMaintenance_$ServiceID' service='$ServiceID' $strRateMaintenanceRadChecked value='Maintenance' onclick='jsSetRateMaintenance($ServiceID); jsSetCurrentServiceID($ServiceID); checkAdditionalLicensesAvailable()' />
							</td>
							<td style='width:60px;text-align:right;border-left:hidden;'>
								".number_format($rowService->dblCostMaintenance,2, '.', ',')."
							</td>
							<td>
								<input type='text' name='strRateYear1[$ServiceID]' id='strRateYear1_$ServiceID' value='".number_format($dblRateYear1,2, '.', ',')."' class='controlText controlLabel controlWideMax' style='text-align:right;' />
								<input type='hidden' name='dblRateYear1[$ServiceID]' id='dblRateYear1_$ServiceID' value='".$dblRateYear1."' />
							</td>
							<td>
								<input type='text' name='strRateMaintenance[$ServiceID]' id='strRateMaintenance_$ServiceID' value='".number_format($dblRateMaintenance,2, '.', ',')."' class='controlText controlLabel controlWideMax' style='text-align:right;' />
								<input type='hidden' name='dblRateMaintenance[$ServiceID]' id='dblRateMaintenance_$ServiceID' value='".$dblRateMaintenance."' />
							</td>
						</tr>";
					}
					break;
					case "8": //X Plan
						$tr .= "
						<tr>

							 <td style='text-align:left;'>
								$rowService->strService
							</td>
							<td style='text-align:right; width:80px;'>
								Include: <input type='checkbox' name='refServiceIDXPlan' id='refServiceIDXPlan' $strServiceRadChecked value='$ServiceID' onclick='jsToggleXPlan()' />
							</td>
							<td>
								<input type='radio' name='strRateTypeXPlan' data='$rowService->dblCostYear1' service='$ServiceID' id='strRateTypeYear1_$ServiceID' $strRateYear1RadChecked value='Year 1' onclick='jsSetRateYear1XPlan($ServiceID); checkAdditionalLicensesAvailable()' />
							</td>
							<td style='text-align:right;border-left:hidden;'>
								".number_format($rowService->dblCostYear1,2, '.', ',')."
							</td>
							<td style='text-align:left;'>
								 <input type='radio' name='strRateTypeXPlan' data='$rowService->dblCostMaintenance' service='$ServiceID' id='strRateTypeMaintenance_$ServiceID' $strRateMaintenanceRadChecked value='Maintenance' onclick='jsSetRateMaintenanceXPlan($ServiceID); checkAdditionalLicensesAvailable()' />
							</td>
							<td style='text-align:right;border-left:hidden;'>
								".number_format($rowService->dblCostMaintenance,2, '.', ',')."
							</td>
							<td>
								<input type='text' name='strRateYear1[$ServiceID]' id='strRateYear1_$ServiceID' value='".number_format($dblRateYear1,2, '.', ',')."' class='controlText controlLabel controlWideMax' style='text-align:right;' />
								<input type='hidden' name='dblRateYear1[$ServiceID]' id='dblRateYear1_$ServiceID' value='".$dblRateYear1."' />
							</td>
							<td>
								<input type='text' name='strRateMaintenance[$ServiceID]' id='strRateMaintenance_$ServiceID' value='".number_format($dblRateMaintenance,2, '.', ',')."' class='controlText controlLabel controlWideMax' style='text-align:right;' />
								<input type='hidden' name='dblRateMaintenance[$ServiceID]' id='dblRateMaintenance_$ServiceID' value='".$dblRateMaintenance."' />
							</td>
						</tr>";
					break;
					case "34": //Available to all partners
						$tr .= "
						<tr>

							 <td style='text-align:left;'>
								$rowService->strService
							</td>
							<td style='text-align:right; width:80px;'>
								Include: <input type='checkbox' name='refServiceIDValuation' id='refServiceIDValuation' $strServiceRadChecked value='$ServiceID' onclick='jsToggleValuations()' />
							</td>
							<td>
								<input type='radio' name='strRateTypeValuation' data='$rowService->dblCostYear1' service='$ServiceID' id='strRateTypeYear1_$ServiceID' $strRateYear1RadChecked value='Year 1' onclick='jsSetRateYear1Valuation($ServiceID); checkAdditionalLicensesAvailable()' />
							</td>
							<td style='text-align:right;border-left:hidden;'>
								".number_format($rowService->dblCostYear1,2, '.', ',')."
							</td>
							<td style='text-align:left;'>
								 <input type='radio' name='strRateTypeValuation' data='$rowService->dblCostMaintenance' service='$ServiceID' id='strRateTypeMaintenance_$ServiceID' $strRateMaintenanceRadChecked value='Maintenance' onclick='jsSetRateMaintenanceValuation($ServiceID); checkAdditionalLicensesAvailable()' />
							</td>
							<td style='text-align:right;border-left:hidden;'>
								".number_format($rowService->dblCostMaintenance,2, '.', ',')."
							</td>
							<td>
								<input type='text' name='strRateYear1[$ServiceID]' id='strRateYear1_$ServiceID' value='".number_format($dblRateYear1,2, '.', ',')."' class='controlText controlLabel controlWideMax' style='text-align:right;' />
								<input type='hidden' name='dblRateYear1[$ServiceID]' id='dblRateYear1_$ServiceID' value='".$dblRateYear1."' />
							</td>
							<td>
								<input type='text' name='strRateMaintenance[$ServiceID]' id='strRateMaintenance_$ServiceID' value='".number_format($dblRateMaintenance,2, '.', ',')."' class='controlText controlLabel controlWideMax' style='text-align:right;' />
								<input type='hidden' name='dblRateMaintenance[$ServiceID]' id='dblRateMaintenance_$ServiceID' value='".$dblRateMaintenance."' />
							</td>
						</tr>";
					
					break;
				}
				$dblTotalRateYear1 += $dblRateYear1;
				$dblTotalRateMaintenance += $dblRateMaintenance;
			}//End IF - check if service is selected even while inactive or just active - CL
		}

		$trTotal = "
					<tr>
						<td style='text-align:right;' colspan=6>
							<b>Total:</b>
						</td>
						<td style='text-align:right;'>
							<input type='text' name='strTotalRateYear1' id='strTotalRateYear1' value=\"".number_format($dblTotalRateYear1,2, '.', ',')."\" class='controlText controlLabel controlWideMax' style='text-align:right;' readonly />
							<input type='hidden' name='dblTotalRateYear1' id='dblTotalRateYear1' value=\"".$dblTotalRateYear1."\" />
						</td>
						<td style='text-align:right;'>
							<input type='text' name='strTotalRateMaintenance' id='strTotalRateMaintenance' value=\"".number_format($dblTotalRateMaintenance,2, '.', ',')."\" class='controlText controlLabel controlWideMax' style='text-align:right;' readonly />
							<input type='hidden' name='dblTotalRateMaintenance' id='dblTotalRateMaintenance' value=\"".$dblTotalRateMaintenance."\" />
						</td>
					</tr>
				";

		//*****************************************************************************************************************************
		//******************************************           OUTPUT CONTENT              ****************************************
		//*****************************************************************************************************************************


		// $content = "
		//    <div style=''>
		//       <table cellpadding=0 cellspacing=0 border=0 style='width:100%;padding:0;margin:0px;border:0;border-collapse:collapse;background-color:none;'>
		//          <tr>
		//             <td style='width:60%;vertical-align:top; padding: 0px;'>
		$content = "<table cellpadding=2 cellspacing=1 border=1 class='tblNemoDetails' style='width:100%;margin:0px;border-collapse:collapse;'>
								<input type='hidden' id='strPartnerType' name='strPartnerType' value=\"$strPartnerType\" />
								<input type='hidden' id='Mode' name='Mode' value='BMS' />
								<input type='hidden' id='QuoteID' name='QuoteID' value='$QuoteID' />
								<input type='hidden' id='refServiceID' name='refServiceID'  value='$intCurrentServiceID' />
								<caption>Step 2: Set up Business Management Services & Other Services</caption>
								<tr>
									<th style='width:400px; text-align:center;' colspan='2'>Service</th>
									<th style='width:80px; text-align:center;' colspan='2'>Year 1</th>
									<th style='width:80px; text-align:center;' colspan='2'>Ongoing</th>
									<th style='width:80px; text-align:center;'>Fees Year1</th>
									<th style='width:80px; text-align:center;'>Fees Ongoing</th>
								</tr>
								$tr
								$trTotal
							</table>"
				.js("
				var currentSelectedXPlanOption = '';
				var currentSelectedValuationOption = '';


				function jsToggleXPlan()
				{
					if($('#refServiceIDXPlan').attr('checked'))
					{
						var refServiceID = $('#refServiceIDXPlan').val();
						$('#strRateTypeYear1_'+refServiceID).removeAttr('disabled');
						$('#strRateTypeMaintenance_'+refServiceID).removeAttr('disabled');

						if(currentSelectedXPlanOption == 'Year 1')
						{
							$('#strRateTypeYear1_'+refServiceID).Attr('checked','checked');
						}
						else if(currentSelectedXPlanOption == 'Maintenance')
						{
							$('#strRateTypeMaintenance_'+refServiceID).Attr('checked','checked');
						}
					}
					else
					{
						var refServiceID = $('#refServiceIDXPlan').val();

						if($('#strRateTypeYear1_'+refServiceID).is(':checked'))
						{
							currentSelectedXPlanOption = 'Year 1';
						}
						else if($('#strRateTypeMaintenance_'+refServiceID).is(':checked'))
						{
							currentSelectedXPlanOption = 'Maintenance';
						}

						$('#strRateTypeYear1_'+refServiceID).attr('disabled',true);
						$('#strRateTypeMaintenance_'+refServiceID).attr('disabled',true);

						$('#strRateTypeYear1_'+refServiceID).removeAttr('checked');
						$('#strRateTypeMaintenance_'+refServiceID).removeAttr('checked');

						$('#dblRateYear1_'+refServiceID).val(parseFloat(0));
						$('#strRateYear1_'+refServiceID).val(parseFloat(0));

						$('#dblRateMaintenance_'+refServiceID).val(parseFloat(0));
						$('#strRateMaintenance_'+refServiceID).val(parseFloat(0));
					}
				}

				function jsToggleValuations()
				{
					if($('#refServiceIDValuation').attr('checked'))
					{

						var refServiceID = $('#refServiceIDValuation').val();
						$('#strRateTypeYear1_'+refServiceID).removeAttr('disabled');

						if(currentSelectedValuationOption == 'Year 1')
						{
							$('#strRateTypeYear1_'+refServiceID).Attr('checked','checked');
						}
					}
					else
					{

						var refServiceID = $('#refServiceIDValuation').val();

						if($('#strRateTypeYear1_'+refServiceID).is(':checked'))
						{
							currentSelectedValuationOption = 'Year 1';
						}

						$('#strRateTypeYear1_'+refServiceID).attr('disabled',true);
						$('#strRateTypeMaintenance_'+refServiceID).attr('disabled',true);

						$('#strRateTypeYear1_'+refServiceID).removeAttr('checked');
						$('#strRateTypeMaintenance_'+refServiceID).removeAttr('checked');

						$('#dblRateYear1_'+refServiceID).val(parseFloat(0));
						$('#strRateYear1_'+refServiceID).val(parseFloat(0));

						$('#dblRateMaintenance_'+refServiceID).val(parseFloat(0));
						$('#strRateMaintenance_'+refServiceID).val(parseFloat(0));
					}
				}

				function jsSetCurrentServiceID(refServiceID)
				{
					$('#refServiceID').val(refServiceID);
				}

				function jsSetRateYear1(refServiceID)
				{
					var dblRateYear1 = parseFloat($('#strRateTypeYear1_'+refServiceID).attr('data'));
					var strRateYear1 = dblRateYear1.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					var dblRateMaintenance = parseFloat($('#strRateTypeMaintenance_'+refServiceID).attr('data'));
					var strRateMaintenance = dblRateMaintenance.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					jsCalcTotalRate();
					jsClearRateTextBoxes()

					$('#dblRateYear1_'+refServiceID).val(dblRateYear1);
					$('#strRateYear1_'+refServiceID).val(strRateYear1);

					$('#dblRateMaintenance_'+refServiceID).val(dblRateMaintenance);
					$('#strRateMaintenance_'+refServiceID).val(strRateMaintenance);
				}

				function jsSetRateMaintenance(refServiceID)
				{
					var dblRateMaintenance = parseFloat($('#strRateTypeMaintenance_'+refServiceID).attr('data'));
					var strRateMaintenance = dblRateMaintenance.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					jsCalcTotalRate();
					jsClearRateTextBoxes()

					$('#dblRateYear1_'+refServiceID).val(parseFloat(dblRateMaintenance));
					$('#strRateYear1_'+refServiceID).val(strRateMaintenance);

					$('#dblRateMaintenance_'+refServiceID).val(parseFloat(dblRateMaintenance));
					$('#strRateMaintenance_'+refServiceID).val(strRateMaintenance);
				}

				function jsSetRateYear1XPlan(refServiceID)
				{
					var dblRateYear1 = parseFloat($('#strRateTypeYear1_'+refServiceID).attr('data'));
					var strRateYear1 = dblRateYear1.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					var dblRateMaintenance = parseFloat($('#strRateTypeMaintenance_'+refServiceID).attr('data'));
					var strRateMaintenance = dblRateMaintenance.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					jsCalcTotalRate();

					$('#dblRateYear1_'+refServiceID).val(parseFloat(dblRateYear1));
					$('#strRateYear1_'+refServiceID).val(strRateYear1);

					$('#dblRateMaintenance_'+refServiceID).val(parseFloat(dblRateMaintenance));
					$('#strRateMaintenance_'+refServiceID).val(strRateMaintenance);

					currentSelectedXPlanOption = 'Year 1';
				}

				function jsSetRateYear1Valuation(refServiceID)
				{
					var dblRateYear1 = parseFloat($('#strRateTypeYear1_'+refServiceID).attr('data'));
					var strRateYear1 = dblRateYear1.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					var dblRateMaintenance = parseFloat($('#strRateTypeMaintenance_'+refServiceID).attr('data'));
					var strRateMaintenance = dblRateMaintenance.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					jsCalcTotalRate();

					$('#dblRateYear1_'+refServiceID).val(parseFloat(dblRateYear1));
					$('#strRateYear1_'+refServiceID).val(strRateYear1);

					$('#dblRateMaintenance_'+refServiceID).val(parseFloat(dblRateMaintenance));
					$('#strRateMaintenance_'+refServiceID).val(strRateMaintenance);

					currentSelectedValuationOption = 'Year 1';
				}

				function jsSetRateMaintenanceXPlan(refServiceID)
				{
					var dblRateYear1 = parseFloat($('#strRateTypeYear1_'+refServiceID).attr('data'));
					var strRateYear1 = dblRateYear1.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					var dblRateMaintenance = parseFloat($('#strRateTypeMaintenance_'+refServiceID).attr('data'));
					var strRateMaintenance = dblRateMaintenance.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					jsCalcTotalRate();

					$('#dblRateYear1_'+refServiceID).val(parseFloat(dblRateMaintenance));
					$('#strRateYear1_'+refServiceID).val(strRateMaintenance);

					$('#dblRateMaintenance_'+refServiceID).val(parseFloat(dblRateMaintenance));
					$('#strRateMaintenance_'+refServiceID).val(strRateMaintenance);

					currentSelectedXPlanOption = 'Maintenance';
				}

				function jsSetRateMaintenanceValuation(refServiceID)
				{
					var dblRateYear1 = parseFloat($('#strRateTypeYear1_'+refServiceID).attr('data'));
					var strRateYear1 = dblRateYear1.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					var dblRateMaintenance = parseFloat($('#strRateTypeMaintenance_'+refServiceID).attr('data'));
					var strRateMaintenance = dblRateMaintenance.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					jsCalcTotalRate();

					$('#dblRateYear1_'+refServiceID).val(parseFloat(dblRateMaintenance));
					$('#strRateYear1_'+refServiceID).val(strRateMaintenance);

					$('#dblRateMaintenance_'+refServiceID).val(parseFloat(dblRateMaintenance));
					$('#strRateMaintenance_'+refServiceID).val(strRateMaintenance);

					currentSelectedValuationOption = 'Maintenance';
				}

				function jsCalcTotalRate()
				{
					var dblTotalRateYear1 = 0;
					var dblTotalRateMaintenance = 0;

					$(\"input:radio[name^='strRateType']:checked\").each(function ()
					{
						if( $(this).val() == 'Year 1')
						{
							var refServiceID = $(this).attr('service');
							dblTotalRateYear1 += parseFloat($(this).attr('data'));
							dblTotalRateMaintenance += parseFloat($('#strRateTypeMaintenance_'+refServiceID).attr('data'));
						}
						else if($(this).val() == 'Maintenance')
						{
							dblTotalRateYear1 += parseFloat($(this).attr('data'));
							dblTotalRateMaintenance += parseFloat($(this).attr('data'));
						}

					});
					var strTotalRateYear1 = dblTotalRateYear1.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");
					var strTotalRateMaintenance = dblTotalRateMaintenance.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");

					$('#dblTotalRateYear1').val(parseFloat(dblTotalRateYear1));
					$('#strTotalRateYear1').val(strTotalRateYear1);

					$('#dblTotalRateMaintenance').val(parseFloat(dblTotalRateMaintenance));
					$('#strTotalRateMaintenance').val(strTotalRateMaintenance);
				}

				function jsClearRateTextBoxes()
				{
					$(\"input:radio[name='strRateType']:not(:checked)\").each(function ()
					{
						var refServiceID = $(this).attr('service');

						$('#dblRateYear1_'+refServiceID).val(parseFloat(0));
						$('#strRateYear1_'+refServiceID).val(parseFloat(0));

						$('#dblRateMaintenance_'+refServiceID).val(parseFloat(0));
						$('#strRateMaintenance_'+refServiceID).val(parseFloat(0));
					});
				}");
	//               </td>
	//               <td style='width:40%; padding: 0px; padding-left: 20px;' valign='top' >";
	//$content .= Quote::previewQuote($QuoteID);
	// $content .= "
	//                </td>
	//             </tr>
	//          </table>";

		return $content;
	}

	public static function setupAdditionalServiceLicenses($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		// *****************************************************************************************************************************
		// ******************************************           Other Services Div              ****************************************
		// *****************************************************************************************************************************

		//Preload array
		$arrService = array();
		$rstService = $xdb->doQuery("SELECT * FROM slaService WHERE slaService.strType='Additional License' ORDER BY intDisplayOrder,strService DESC",0);

		while($rowService = $xdb->fetch_object($rstService))
		{
			$arrService[$rowService->ServiceID] = $rowService;
		}
		//print_rr($arrService); //die;

		//go
		$rstQI = $xdb->doQuery("
			SELECT `intRowGroup`,`refServiceID`,QuoteItemID, slaQuoteItem.strPlannerName
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Additional License')
			ORDER BY strPlannerName, intRowGroup,ServiceID", 0);
		//preload
		while($rowQI = $xdb->fetch_object($rstQI))
		{
			$arrServiceGroup[$rowQI->intRowGroup][$rowQI->refServiceID] = $rowQI->QuoteItemID;
		}

		//count services
		$intServiceRowCount = 0;
		foreach ($arrServiceGroup AS $intRowGroup => $rowQuoteService)
		{
			$intServiceRowCount++;
		}
		//print_rr($arrServiceGroup);
		$intCounter = 0;
		foreach($arrServiceGroup AS $intRowGroup => $rowQuoteService)
		{
			$btnDelete = "<a href='?Action=DeleteAdditionalLicense&QuoteID=$QuoteID&intRowGroup=$intRowGroup' onclick = \"return confirm('Are you sure you want to remove this row?');\"><img width='20px' src='images/delete.png' /></a>";
			$trContentInner = "";
			$intCounter++;

			foreach($arrService AS $ServiceID => $rowService)
			{
				if(isset($rowQuoteService[$ServiceID]))
				{
					$row = $xdb->getRowSQL("
					SELECT slaQuoteItem.*
					FROM slaQuoteItem
					WHERE QuoteItemID=".$rowQuoteService[$ServiceID],0);

					$strPlannerName = $row->strPlannerName;

					$blnChecked = "checked";

					${"dblTotalCostMaintenance".$ServiceID} += $row->dblRateYear1;
				}
				else
				{
					$blnChecked = "";
				}
				$trContentInner .= "
				<td width='20px' align='left' style='text-align:left;white-space: nowrap;width:20px;'>
					<input type='checkbox' id='chkAdditionalService_".$intRowGroup."_".$ServiceID."]' name='chkAdditionalService[".$intRowGroup."][".$ServiceID."]' service='$ServiceID' value='1' $blnChecked onclick='jsUpdateAdditionalLicenseTotals();'>
				</td>
				<td width='80px' align='right' style='text-align:right;white-space: nowrap;width:80px;border-left:hidden;'>
					".(number_format($rowService->dblCostYear1,2, '.', ','))."
				</td>";

					//}
			}
			$trContent .= "
			<tr>
				<td align='center' style='text-align:center'>$intCounter</td>
				<td><input type='text' id='strPlannerName_$intRowGroup' name='strPlannerName[$intRowGroup]' value='$strPlannerName' class='controlText controlWideMax' /></td>
				$trContentInner
				<td align='center' style='text-align:center;'>$btnDelete</td>
			</tr>";
		}

		//build heading
		$tdHeading = "";
		foreach ($arrService AS $ServiceID => $rowService)
		{
			//print_rr($rowService);
			$tdHeading .= "
			<th width='100px' align='center' style='text-align:center;width:100px;' colspan='2'>
				".$rowService->strService//." (R".number_format($rowService->dblCostMaintenance,0, '.', ',')." per License)
				."<input type='hidden' name='txtAdditionalService[$ServiceID]' id='txtAdditionalService_$ServiceID' value='$ServiceID' />
				<input type='hidden' name='dblRateYear1[$ServiceID]' id='dblRateYear1_$ServiceID' value=\"".$rowService->dblCostYear1."\" />
				<input type='hidden' name='dblRateMaintenance[$ServiceID]' id='dblRateMaintenance_$ServiceID' value=\"".$rowService->dblCostYear1."\" />
			</th>";
			$tdBlankContent .= "
			<td width='20px' align='left' style='text-align:left;'>
				<input align='right' style='text-align:right;' type='checkbox' id='chkAdditionalService' service='$ServiceID' name='' value='1' onclick='jsUpdateAdditionalLicenseTotals();'></td>
			<td width='80px' align='right' style='text-align:right;white-space: nowrap;width:80px;border-left:hidden;'>
					".(number_format($rowService->dblCostYear1,2, '.', ','))."
				</td>";
			$tdTotalDetailInner .="<td align='right' style='text-align:right;' colspan='2'><input align='right' style='text-align:right;width:80px;' type='text' id='txtTotal_$ServiceID' name='txtTotal[$ServiceID]' value='".${"dblTotalCostMaintenance".$ServiceID}."' class=' controlLabel' readonly></td>";
		}

		// blank row template
		$trAdd .= "
					<tr class='itemRow' id='extraRow' style='display:none;'>
						<td align='center' style='width: 20px;'><b class='tdCount textColour'>+</b></td>
						<td align='left'><input type='text' id='strPlannerName' name='' class='controlText controlWideMax' /></td>
						$tdBlankContent
						<td></td>
					</tr>";

		$trTotal = "
					<tr>
						<td colspan='2' align='right' style='text-align:right;'><b>Totals:</b></td>
						$tdTotalDetailInner
						<td></td>

					</tr>";

		if(count($arrServiceGroup) > 0)
		{
			$strShowAdditionalLicensesChecked = "checked";
			$strHideAdditionalLicensesChecked = "";
		}
		else
		{
			$strShowAdditionalLicensesChecked = "";
			$strHideAdditionalLicensesChecked = "checked";
		}

		return "
		$BR
		<div>
			<h3 class=''>Would you like to add additional <span class='textColour'>Bussiness Assessment (BAT)</span> or <span class='textColour'>Client Survey (CSS)</span> licenses?</h3>
			<div style='padding-left: 20px;'>
				$SP <label for='radEnableAdditionalLicensesYes' >Yes</label> <input type='radio' id='radEnableAdditionalLicensesYes' name='radEnableAdditionalLicenses' value='1' $strShowAdditionalLicensesChecked $strNoBMSDisable $strNoBMSTitle onclick='jsToggleAdditionalLicenses();' />
				$SP <label for='radEnableAdditionalLicensesNo' >No, thanks</label> <input type='radio' id='radEnableAdditionalLicensesNo' name='radEnableAdditionalLicenses' value='0' $strHideAdditionalLicensesChecked $strNoBMSDisable $strNoBMSTitle onclick='jsToggleAdditionalLicenses();' />
			</div>

		</div>
		$BR
		<div id='divAdditionalLicenses' style='width:100%;'>
		<table cellpadding=2 cellspacing=1 border=1 class='tblNemoDetails' style='width:100%;margin:0px;border-collapse:collapse;'>
			<caption>Step 2: Set up Additional Licenses</caption>
			<tr>
				<!--[if IE]>
					<th align='center' style='width: 40px;' rowspan='".($intServiceRowCount+3)."' id='thAdd'><img onclick='jsAdd();' src='images/add.png' width='24px;' class='imgbutton'/></th>
				<![endif]-->
				<!--[if !IE]> -->
				<th align='center' style='width: 40px;' rowspan='".($intServiceRowCount+2)."' id='thAdd'><img onclick='jsAdd();' src='images/add.png' width='24px;' class='imgbutton'/></th>
				<![endif]-->
				<th align='center' style='text-align:center;width: 25px;' class='tdCount'>#</th>
				<th>Name</th>
				$tdHeading
				<th align='center' style='text-align:center;width:40px'>Delete</th>
			</tr>
			$trContent
			$trAdd
			$trTotal
		</table>
		</div>"
		.js("
			var UniqueID = -1;

				function jsAdd()
				{
					var copy = $('#extraRow').clone(true).insertAfter('#extraRow');
					var trID = 'extraRow'+UniqueID;
					copy.attr('id', trID);

					// Planner //////////////////////////////////////////////////////////////////////////

					$('#extraRow'+UniqueID).find('#strPlannerName').each(function(){
						var Id = $(this).attr('id');
						$(this).attr('name', 'strPlannerName['+UniqueID+']');
						$(this).attr('id', Id+'_'+UniqueID);
					});

					// staff code //////////////////////////////////////////////////////////////////////////

					$('#extraRow'+UniqueID).find('#chkAdditionalService').each(function(){
						var Id = $(this).attr('id');
						var ServiceID = $(this).attr('service');
						$(this).attr('name', 'chkAdditionalService['+UniqueID+']['+ServiceID+']');
						$(this).attr('id', Id+'_'+UniqueID+'_'+ServiceID);

					});

					$('#extraRow'+UniqueID).css('display','');
					UniqueID--;

					var rowspan = $('#thAdd').attr('rowspan');
					rowspan ++;
					$('#thAdd').attr('rowspan',rowspan);
				}

				function jsToggleAdditionalLicenses()
				{
					if($('#radEnableAdditionalLicensesYes').is(':checked'))
					{
						$('#divAdditionalLicenses').show();
					}
					else
					{
						$('#divAdditionalLicenses').hide();
					}
				}

				function jsUpdateAdditionalLicenseTotals()
				{
					$(\"input[name^='txtAdditionalService']\").each(function ()
					{
						var ServiceID = $(this).val();
						var dblTotalCost = 0;
						var dblCost = $('#dblRateMaintenance_'+ServiceID).val();

						$(\"input:checkbox[name^='chkAdditionalService']:checked\").each(function ()
						{
							var refServiceID = $(this).attr('service');
							if(refServiceID == ServiceID)
							{
								dblTotalCost += parseFloat(dblCost);
							}

						});

						var dblTotalCost = dblTotalCost.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, \"$1,\");
						$('#txtTotal_'+ServiceID).val(dblTotalCost);
					});
				}

				function checkAdditionalLicensesAvailable()
				{
					var count = 0;
					$(\"input:radio[name^='strRateType']:checked\").each(function ()
					{
						count++
					});

					if(count > 0)
					{
						$('#radEnableAdditionalLicensesYes').removeAttr('disabled');
						$('#radEnableAdditionalLicensesNo').removeAttr('disabled');
					}
					else
					{
							$('#radEnableAdditionalLicensesYes').attr('disabled',true);
							$('#radEnableAdditionalLicensesNo').attr('disabled',true);

							$('#radEnableAdditionalLicensesYes').attr('title', 'At least one BMS service is needed.');
							$('#radEnableAdditionalLicensesNo').attr('title', 'At least one BMS service is needed.');
					}

				}
			");
	}



	public static function Save(&$QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		
		$db = new NemoDatabase("slaQuote", $QuoteID, null, 0);

		$strOriginalPartnerType = $db->Fields["strPartnerType"];

		$db->SetValues($_POST);

		if($QuoteID == 0){
			$db->Fields["dtCreationDate"] = date("Y-m-d");
		}
		$db->Fields["strLastUser"] = $_SESSION['USER']->USERNAME;

		if(!(isset($_POST["dtAgreementStartDate"])) || $_POST["dtAgreementStartDate"] == "")
		{
			$db->Fields["dtAgreementStartDate"] = "NULL";
		}

		//20160308 - remove service ServiceID = 7 (IWF HIGH) and XPlan ServiceID=8 if its not a strategic partner = Christiaan
		if($db->Fields["strPartnerType"] != Quote::$STRATEGIC_PARTNER && $strOriginalPartnerType == Quote::$STRATEGIC_PARTNER)
		{
			// $xdb->doQuery("UPDATE slaQuoteItem SET intIBC = 0 WHERE slaQuoteItem.refQuoteID = ". $xdb->qs($QuoteID)."", 1);

			$xdb->doQuery("UPDATE slaQuoteItem SET intIBC = 0, intAssetMapPlanner = 0 , intAssetMapAdmin = 0  WHERE slaQuoteItem.refQuoteID = ". $xdb->qs($QuoteID)."", 0);

			$rst = $xdb->doQuery("
            SELECT slaQuoteItem.*, slaService.* FROM slaQuoteItem INNER JOIN slaService ON slaService.ServiceID = slaQuoteItem.refServiceID 
            WHERE slaQuoteItem.refQuoteID = ". $xdb->qs($QuoteID)." AND refServiceID IN (7,8,22)",0);

			if($xdb->Rows > 0)
			{
				while($rowQuoteItem = $xdb->fetch_object($rst))
				{

					$xdb->doQuery("DELETE FROM slaQuoteItem WHERE refQuoteID = ". $xdb->qs($QuoteID)."AND refServiceID = $rowQuoteItem->refServiceID");

					$strDeleteMessageInner .= " $rowQuoteItem->strService,";

				}
				$strDeleteMessageInner = rtrim($strDeleteMessageInner, ",");
				$strDeleteStrategicPartnerServicesMessage = "<b style='color:darkorange;'>You have downgraded your Partner Type from ". Quote::$STRATEGIC_PARTNER ." to ".$db->Fields["strPartnerType"]." and the following option(s) have been removed: ".$strDeleteMessageInner.".</b> ";
			}
		}

		//20201012 - Save presonalised Corporate Partner Prices - Rachel
		// print_rr($_POST["dblCorporateRateYear1"]);
		if($_POST["dblCorporateRateYear1"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCorporateRateYear1"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateYear1 = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}
		if($_POST["dblCorporateRateMaintenance"]){

			foreach ($_POST["dblCorporateRateMaintenance"] as $QIID => $value) {
				$dblCorporateRateMaintenance = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateMaintenance = '$dblCorporateRateMaintenance' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}

		}

		if($_POST["dblBMSCorporateRateYear1"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblBMSCorporateRateYear1"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateYear1 = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}
		if($_POST["dblBMSCorporateRateMaintenance"]){

			foreach ($_POST["dblBMSCorporateRateMaintenance"] as $QIID => $value) {
				$dblCorporateRateMaintenance = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateMaintenance = '$dblCorporateRateMaintenance' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}

		}

		if($_POST["dblXPlanCorporateRateYear1"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblXPlanCorporateRateYear1"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateYear1 = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}
		if($_POST["dblXPlanCorporateRateMaintenance"]){

			foreach ($_POST["dblXPlanCorporateRateMaintenance"] as $QIID => $value) {
				$dblCorporateRateMaintenance = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateMaintenance = '$dblCorporateRateMaintenance' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}

		}

		if($_POST["dblIBCMaintenaceCost"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblIBCMaintenaceCost"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomIBCRate = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}

		if($_POST["dblCustomMapPlannerRate"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCustomMapPlannerRate"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomAssetMapPlannerRate = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}

		if($_POST["dblCustomMapAdminRate"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCustomMapAdminRate"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomAssetMapAdmin = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}

		if($_POST["dblCustomValuationRate"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCustomValuationRate"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomValuationRate = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}


		

		$result = $db->Save(0,0);
		if($QuoteID == 0) $QuoteID = $db->ID["QuoteID"];

		//print_rr($result);
		if($result->Error == 1){
			return $result->Message;
		}else{
			return "Details Saved. $strDeleteStrategicPartnerServicesMessage";
		}
	}

	public static function SaveFinPlanning($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

// print_rr($_POST); //die("KOSDKN");/

		foreach($_POST["strPlannerName"] as $QuoteItemID => $strPlanner)
		{
			$db = new NemoDatabase("slaQuoteItem", $QuoteItemID, null, 0);

			// print_rr($_POST["dblRateYear1"][$QuoteItemID]);

			$db->Fields["refQuoteID"] = $QuoteID;
			$db->Fields["refServiceID"] = qs($_POST["refServiceID"][$QuoteItemID]);

			$db->Fields["strPlannerName"] = qs($_POST["strPlannerName"][$QuoteItemID]);
			$db->Fields["strPlannerID"] = qs($_POST["strPlannerID"][$QuoteItemID]);
			$db->Fields["strPlannerEmail"] = qs($_POST["strPlannerEmail"][$QuoteItemID]);
			$db->Fields["strPlannerCell"] = qs($_POST["strPlannerCell"][$QuoteItemID]);

			$dblRateYear1 = qs($_POST["dblRateYear1"][$QuoteItemID]);
			$dblRateYear1 = str_replace(",", "", $dblRateYear1);
			$db->Fields["dblRateYear1"] = $dblRateYear1;

			$dblRateMaintenance = qs($_POST["dblRateMaintenance"][$QuoteItemID]);
			$dblRateMaintenance = str_replace(",", "", $dblRateMaintenance);
			$db->Fields["dblRateMaintenance"] = $dblRateMaintenance;

			$db->Fields["strRateType"] = qs($_POST["strRateType"][$QuoteItemID]);

			//20181126 - IBC Course - pj
			$db->Fields["intIBC"] = qs($_POST["intIBC"][$QuoteItemID]);

			$db->Fields["intAssetMapPlanner"] = qs($_POST["intAssetMapPlanner"][$QuoteItemID]);

			$db->Fields["intAssetMapAdmin"] = qs($_POST["intAssetMapAdmin"][$QuoteItemID]);

			$db->Fields["strLastUser"] = $_SESSION['USER']->USERNAME;

			$result = $db->Save(0, 0);

			self::updateQuoteTotalCost($QuoteID);
		}

		//20201012 - Save presonalised Corporate Partner Prices - Rachel
		// print_rr($_POST["dblCorporateRateYear1"]);
		if($_POST["dblCorporateRateYear1"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCorporateRateYear1"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateYear1 = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}
		if($_POST["dblCorporateRateMaintenance"]){

			foreach ($_POST["dblCorporateRateMaintenance"] as $QIID => $value) {
				$dblCorporateRateMaintenance = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateMaintenance = '$dblCorporateRateMaintenance' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}

		}

		if($_POST["dblXPlanCorporateRateYear1"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblXPlanCorporateRateYear1"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateYear1 = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}
		if($_POST["dblXPlanCorporateRateMaintenance"]){

			foreach ($_POST["dblXPlanCorporateRateMaintenance"] as $QIID => $value) {
				$dblCorporateRateMaintenance = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateMaintenance = '$dblCorporateRateMaintenance' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}

		}

		if($_POST["dblBMSCorporateRateYear1"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblBMSCorporateRateYear1"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateYear1 = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}
		if($_POST["dblBMSCorporateRateMaintenance"]){

			foreach ($_POST["dblBMSCorporateRateMaintenance"] as $QIID => $value) {
				$dblCorporateRateMaintenance = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateMaintenance = '$dblCorporateRateMaintenance' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}

		}

		if($_POST["dblIBCMaintenaceCost"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblIBCMaintenaceCost"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomIBCRate = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}

		if($_POST["dblCustomMapPlannerRate"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCustomMapPlannerRate"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomAssetMapPlannerRate = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}

		if($_POST["dblCustomMapAdminRate"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCustomMapAdminRate"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomAssetMapAdmin = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}

		if($_POST["dblCustomValuationRate"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCustomValuationRate"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomValuationRate = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}

		//print_rr($result);
		if($result->Error == 1){
			return $result->Message;
		}else{
			return "Details Saved. ";
		}
	}

	public static function SaveBMS($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		//print_rr($_POST); die;

		//truncate data first
		$xdb->doQuery("DELETE qi.*
							FROM slaQuoteItem qi INNER JOIN slaService s ON qi.refServiceID = s.ServiceID
							WHERE qi.refQuoteID = ".$xdb->qs($QuoteID)." AND (s.strType='Business Management Service' OR s.strType='Additional License') ");

		//20201012 - Save/Update presonalised Corporate Partner Prices - Rachel
		if($_POST["dblCorporateRateYear1"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCorporateRateYear1"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateYear1 = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}
		if($_POST["dblCorporateRateMaintenance"]){

			foreach ($_POST["dblCorporateRateMaintenance"] as $QIID => $value) {
				$dblCorporateRateMaintenance = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblRateMaintenance = '$dblCorporateRateMaintenance' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}

		}

		//Save Custom IBC Rate
		if($_POST["dblIBCMaintenaceCost"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblIBCMaintenaceCost"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomIBCRate = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}

		if($_POST["dblCustomMapPlannerRate"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCustomMapPlannerRate"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomAssetMapPlannerRate = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}
		if($_POST["dblCustomMapAdminRate"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCustomMapAdminRate"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomAssetMapAdmin = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}
		if($_POST["dblCustomValuationRate"]){
			// print_rr($_POST["dblCorporateRateYear1"]);
			foreach ($_POST["dblCustomValuationRate"] as $QIID => $value) {
				$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
				$xdb->doQuery("UPDATE slaQuoteItem SET dblCustomValuationRate = '$dblCorporateRateYear1' WHERE slaQuoteItem.QuoteItemID = ". $xdb->qs($QIID)."", 0);

			}
			
		}

		//save normal service choice

		$ServiceID = $_POST["refServiceID"];
		if($_POST["refServiceID"] != 0)
		{

			$db = new NemoDatabase("slaQuoteItem", 0, null, 0);

			$db->Fields["refQuoteID"] = $QuoteID;
			$db->Fields["refServiceID"] = qs($_POST["refServiceID"]);


			//20201012 - Save presonalised Corporate Partner Prices - Rachel
			if($_POST["dblBMSCorporateRateYear1"]){
				// print_rr($_POST["dblBMSCorporateRateYear1"]);
				foreach ($_POST["dblBMSCorporateRateYear1"] as $QIID => $value) {
					$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
					
					$dblRateYear1 = qs($dblCorporateRateYear1);
					$dblRateYear1 = str_replace(",", "", $dblRateYear1);

				}


				
			}else{
				$dblRateYear1 = qs($_POST["dblRateYear1"][$ServiceID]);
				$dblRateYear1 = str_replace(",", "", $dblRateYear1);
			}
			if($_POST["dblBMSCorporateRateMaintenance"]){

				foreach ($_POST["dblBMSCorporateRateMaintenance"] as $QIID => $value) {
					$dblCorporateRateMaintenance = str_replace(array("R",","), "", $value);
					$dblRateMaintenance = qs($dblCorporateRateMaintenance);
					$dblRateMaintenance = str_replace(",", "", $dblRateMaintenance);
				}

			}else{
				$dblRateMaintenance = qs($_POST["dblRateMaintenance"][$ServiceID]);
				$dblRateMaintenance = str_replace(",", "", $dblRateMaintenance);
			}

			// $dblRateYear1 = qs($_POST["dblRateYear1"][$ServiceID]);
			// $dblRateYear1 = str_replace(",", "", $dblRateYear1);
			$db->Fields["dblRateYear1"] = $dblRateYear1;

			// $dblRateMaintenance = qs($_POST["dblRateMaintenance"][$ServiceID]);
			// $dblRateMaintenance = str_replace(",", "", $dblRateMaintenance);
			$db->Fields["dblRateMaintenance"] = $dblRateMaintenance;

			$db->Fields["strRateType"] = qs($_POST["strRateType"]);
			$db->Fields["strLastUser"] = $_SESSION['USER']->USERNAME;

			$result = $db->Save(0,0);

			self::updateQuoteTotalCost($QuoteID);
		}

		//save xplan choice
		// save refServiceIDXPlan
		if(isset($_POST["refServiceIDXPlan"]))
		{
			$ServiceID = $_POST["refServiceIDXPlan"];

			$dbXPlan = new NemoDatabase("slaQuoteItem", 0, null, 0);

			$dbXPlan->Fields["refQuoteID"] = $QuoteID;
			$dbXPlan->Fields["refServiceID"] = $_POST["refServiceIDXPlan"];

			//20201012 - Save presonalised Corporate Partner Prices - Rachel
			if($_POST["dblXPlanCorporateRateYear1"]){
				// print_rr($_POST["dblBMSCorporateRateYear1"]);
				foreach ($_POST["dblXPlanCorporateRateYear1"] as $QIID => $value) {
					$dblCorporateRateYear1 = str_replace(array("R",","), "", $value);
					
					$dblRateYear1 = qs($dblCorporateRateYear1);
					$dblRateYear1 = str_replace(",", "", $dblRateYear1);

				}


				
			}else{
				$dblRateYear1 = qs($_POST["dblRateYear1"][$ServiceID]);
				$dblRateYear1 = str_replace(",", "", $dblRateYear1);
			}
			if($_POST["dblXPlanCorporateRateMaintenance"]){

				foreach ($_POST["dblXPlanCorporateRateMaintenance"] as $QIID => $value) {
					$dblCorporateRateMaintenance = str_replace(array("R",","), "", $value);
					$dblRateMaintenance = qs($dblCorporateRateMaintenance);
					$dblRateMaintenance = str_replace(",", "", $dblRateMaintenance);
				}

			}else{
				$dblRateMaintenance = qs($_POST["dblRateMaintenance"][$ServiceID]);
				$dblRateMaintenance = str_replace(",", "", $dblRateMaintenance);
			}

			// $dblRateYear1 = $_POST["dblRateYear1"][$ServiceID];
			// $dblRateYear1 = str_replace(",", "", $dblRateYear1);
			$dbXPlan->Fields["dblRateYear1"] = $dblRateYear1;

			// $dblRateMaintenance = $_POST["dblRateMaintenance"][$ServiceID];
			// $dblRateMaintenance = str_replace(",", "", $dblRateMaintenance);
			$dbXPlan->Fields["dblRateMaintenance"] = $dblRateMaintenance;

			$dbXPlan->Fields["strRateType"] = $_POST["strRateTypeXPlan"];
			$dbXPlan->Fields["strLastUser"] = $_SESSION['USER']->USERNAME;
			$result = $dbXPlan->Save(0,0);

			self::updateQuoteTotalCost($QuoteID);
		}

		if(isset($_POST["refServiceIDValuation"]))
		{
			$ServiceID = $_POST["refServiceIDValuation"];

			$dbValuationPlan = new NemoDatabase("slaQuoteItem", 0, null, 0);

			$dbValuationPlan->Fields["refQuoteID"] = $QuoteID;
			$dbValuationPlan->Fields["refServiceID"] = $_POST["refServiceIDValuation"];

			$dblRateYear1 = $_POST["dblRateYear1"][$ServiceID];
			$dblRateYear1 = str_replace(",", "", $dblRateYear1);
			$dbValuationPlan->Fields["dblRateYear1"] = $dblRateYear1;

			$dblRateMaintenance = $_POST["dblRateMaintenance"][$ServiceID];
			$dblRateMaintenance = str_replace(",", "", $dblRateMaintenance);
			$dbValuationPlan->Fields["dblRateMaintenance"] = $dblRateMaintenance;

			$dbValuationPlan->Fields["strRateType"] = $_POST["strRateTypeValuation"];
			$dbValuationPlan->Fields["strLastUser"] = $_SESSION['USER']->USERNAME;
			$result = $dbValuationPlan->Save(0,0);

			self::updateQuoteTotalCost($QuoteID);
		}

		if($_POST["radEnableAdditionalLicenses"] == 1)
		{
			foreach ($_POST["chkAdditionalService"] as $intRowGroup => $rowServiceQuoteItem)
			{

				$row = $xdb->getRowSQL("SELECT max(intRowGroup) as 'intNewRowGroup' FROM slaQuoteItem");
				$intNewRowGroup = $row->intNewRowGroup + 1;

				foreach ($rowServiceQuoteItem as $ServiceID => $rowQuoteItem)
				{
					 $dbAdditionalLicenses = new NemoDatabase("slaQuoteItem", 0, null, 0);

					$dbAdditionalLicenses->Fields["refQuoteID"] = $QuoteID;
					$dbAdditionalLicenses->Fields["refServiceID"] = $ServiceID;

					$dbAdditionalLicenses->Fields["strPlannerName"] = $_POST["strPlannerName"][$intRowGroup];
					$dbAdditionalLicenses->Fields["intRowGroup"] = $intRowGroup;

					if($intRowGroup < 0)
					{
						$dbAdditionalLicenses->Fields["intRowGroup"] = $intNewRowGroup;
					}

					$dblRateYear1 = $_POST["dblRateYear1"][$ServiceID];
					$dblRateYear1 = str_replace(",", "", $dblRateYear1);
					$dbAdditionalLicenses->Fields["dblRateYear1"] = $dblRateYear1;

					$dblRateMaintenance = $_POST["dblRateMaintenance"][$ServiceID];
					$dblRateMaintenance = str_replace(",", "", $dblRateMaintenance);
					$dbAdditionalLicenses->Fields["dblRateMaintenance"] = $dblRateMaintenance;

					$dbAdditionalLicenses->Fields["strRateType"] = "Maintenance";
					$dbAdditionalLicenses->Fields["strLastUser"] = $_SESSION['USER']->USERNAME;

					$result = $dbAdditionalLicenses->Save(0,0);
				}
			}
			self::updateQuoteTotalCost($QuoteID);
		}

		//print_rr($result);
		if($result->Error == 1){
			return $result->Message;
		}else{
			return "Details Saved. ";
		}
	}

	public static function DuplicateQuote(&$QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;
		//duplicate Quote
		$row = $xdb->getRowSQL("SELECT * FROM slaQuote WHERE QuoteID = ".$xdb->qs($QuoteID));

		//default values //status is set to Draft, Version is incrimented
		$QuoteIDOld = $QuoteID; //used for copying quote items
		$strVersion = $row->strVersion;

		//if the quote already has a timestamp in it, remove it and save a new one
		if (preg_match('/_\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', $row->strQuote))
		{
			$strQuote = $row->strQuote;
			$strQuote = substr($strQuote, 0, -20);
			$strQuote =  $strQuote."_".date("Y-m-d G:i:s");
		}
		else
		{
			$strQuote = $row->strQuote."_".date("Y-m-d G:i:s");
		}

		$strStatus = "Draft";
		$dtCreationDate = date("Y-m-d");
		$strLastUser = "Duplicate Quote - ".$_SESSION["USER"]->USERNAME;

		//check if string is a float or integer and incriment appropriately
		if(is_numeric($row->strVersion))
		{
			if(strpos($row->strVersion,'.') !== false)//if a float
			{
				$strVersion = (float)((float)$row->strVersion + 0.1);
			}
			else
			{
				$strVersion = ((int)$row->strVersion + 1);
			}
		}

		//$strQuote = $row->strQuote ."$strVersion";

		$db = new NemoDatabase("slaQuote", 0, null, 0);

		$db->Fields["refWPSID"] = $row->refWPSID;
		$db->Fields["strQuote"] = $strQuote;
		$db->Fields["strStatus"] = $strStatus;
		$db->Fields["strVersion"] = $strVersion;
		$db->Fields["strPartner"] = $row->strPartner;
		$db->Fields["strPartnerType"] = $row->strPartnerType;
		$db->Fields["strClient"] = $row->strClient;
		$db->Fields["strTel"] = $row->strTel;
		$db->Fields["strEmail"] = $row->strEmail;
		$db->Fields["txtAddress"] = $row->txtAddress;
		$db->Fields["dtCreationDate"] = date("Y-m-d");
		$db->Fields["dtAgreementStartDate"] = "NULL";
		$db->Fields["dblTotalCostPerPlannerMaintenance"] = $row->dblTotalCostPerPlannerMaintenance;
		$db->Fields["dblTotalCostPerPlannerYear1"] = $row->dblTotalCostPerPlannerYear1;
		$db->Fields["dblTotalCostMaintenance"] = $row->dblTotalCostMaintenance;
		$db->Fields["dblTotalCostYear1"] = $row->dblTotalCostYear1;
		$db->Fields["txtNotes"] = $row->txtNotes;
		$db->Fields["strLastUser"] = $strLastUser;

		$result = $db->Save(0,0);
		$QuoteID = $db->ID["QuoteID"];

		// $xdb->doQuery("INSERT INTO slaQuote
		//          (refWPSID, strQuote, strStatus, strVersion, strPartner, strPartnerType, strClient, strTel, strEmail, txtAddress, dtCreationDate, dblTotalCostYear1, dblTotalCostMaintenance, dblTotalCostPerPlannerYear1, dblTotalCostPerPlannerMaintenance, txtNotes, strLastUser)
		//    SELECT refWPSID, strQuote, '$strVersion', '$strStatus', strPartner, strPartnerType, strClient, strTel, strEmail, txtAddress, '$dtCreationDate', dblTotalCostYear1, dblTotalCostMaintenance, dblTotalCostPerPlannerYear1, dblTotalCostPerPlannerMaintenance, txtNotes, 'Duplicate Quote - ".$_SESSION["USER"]->USERNAME."'
		//    FROM slaQuote
		//    WHERE QuoteID = ".$xdb->qs($QuoteID));


		//print_rr($result);
		if($result->Error == 1)
		{
			return $result->Message;
		}
		else
		{

			$xdb->doQuery("INSERT INTO slaQuoteItem
			(refQuoteID, refServiceID, strPlannerName, strRateType, dblRateYear1, dblRateMaintenance, strLastUser)
			SELECT ".$db->ID["QuoteID"].", refServiceID, strPlannerName, strRateType, dblRateYear1, dblRateMaintenance, '$strLastUser'
			FROM slaQuoteItem
			WHERE refQuoteID = ".$xdb->qs($QuoteIDOld),0);

			return "Quote Copied. ";
		}
	}

	//20160314 - Finalize depreciated as status is now ALWAYS proposal - Christiaan
	// public static function Finalize($QuoteID)
	// {
	//    global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

	//    //save total to Quote
	//    $xdb->doQuery("UPDATE slaQuote SET strStatus = 'Proposal'
	//                      WHERE QuoteID = ".$xdb->qs($QuoteID));

	//    return "Proposal Finalized. ";
	// }

	public static function updateQuoteTotalCost($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		$dblTotalCost = 0;

		$rowQuote = $xdb->getRowSQL("SELECT slaQuote.*, vieWPS.strWPS
												FROM slaQuote INNER JOIN vieWPS on slaQuote.refWPSID = vieWPS.WPSID
												WHERE QuoteID = ".$xdb->qs($QuoteID),0);
		// print_rr($rowQuote);
		//go
		$rowQuoteItem = $xdb->getRowSQL("
			SELECT SUM(dblRateYear1) as 'dblCostYear1',SUM(dblRateMaintenance) as 'dblCostMaintenance'
			FROM slaQuoteItem
			WHERE refQuoteID=".$xdb->qs($QuoteID)."",0);


		$dblTotalCostYear1 = $rowQuoteItem->dblCostYear1;
		$dblTotalCostMaintenance = $rowQuoteItem->dblCostMaintenance;

		$intPercentDiscount = 0;
		if($rowQuote->strPartnerType == Quote::$STRATEGIC_PARTNER)
		{
			$intPercentDiscount += $SystemSettings["SLADiscountStratPartner"];
		}

		if($intPlannerCount > 9)
		{
			$intPercentDiscount += $SystemSettings["SLADiscount10Planners"];
		}
		else if($intPlannerCount > 4)
		{
			$intPercentDiscount += $SystemSettings["SLADiscount5Planners"];
		}

		if($intPercentDiscount > 0)
		{
			$dblDiscount = round(($intPercentDiscount / 100) * $dblCost);
			$dblTotalCostYear1 = $dblTotalCostYear1 - $dblDiscount;
			$dblCostMaintenance = $dblTotalCostMaintenance - $dblDiscount;
		}

		$dblTotalCostPerPlannerYear1 = round($dblTotalCostYear1/12);
		$dblTotalCostPerPlannerMaintenance = round($dblTotalCostMaintenance/12);

		//save total to Quote
		$xdb->doQuery("UPDATE slaQuote SET dblTotalCostYear1 = $dblTotalCostYear1, dblTotalCostMaintenance = $dblTotalCostMaintenance, dblTotalCostPerPlannerYear1 = $dblTotalCostPerPlannerYear1,dblTotalCostPerPlannerMaintenance = $dblTotalCostPerPlannerMaintenance
								WHERE QuoteID = ".$xdb->qs($QuoteID));
	}

	public static function updateQuoteFileName($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		$strFileName = self::getFileName($QuoteID);

		//save total to Quote
		$xdb->doQuery("UPDATE slaQuote SET strFileName = '$strFileName'
								WHERE QuoteID = ".$xdb->qs($QuoteID));
	}

	public static function addQuoteItem($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		$db = new NemoDatabase("slaQuoteItem", 0, null, 0);

		$db->Fields["refQuoteID"] = $QuoteID;
		$db->Fields["refServiceID"] = 0;
		$db->Fields["dblRateYear1"] = 0;
		$db->Fields["dblRateMaintenance"] = 0;
		$db->Fields["strRateType"] = "Year 1";

		$db->Fields["strLastUser"] = $_SESSION['USER']->USERNAME;
		$result = $db->Save(0,0);

		//print_rr($result);
		if($result->Error == 1){
			return $result->Message;
		}else{
			return "Item Added. ";
		}
	}

	public static function Delete($chkSelect)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;
		//print_rr($chkSelect);
		if(count($chkSelect) > 0){
		foreach($chkSelect as $key => $value)
		{
			$xdb->doQuery("DELETE FROM slaQuote WHERE QuoteID = ". $xdb->qs($key));
			//$xdb->doQuery("UPDATE slaQuote SET blnActive = 0 WHERE QuoteID = ". $xdb->qs($key));
			 $xdb->doQuery("DELETE FROM slaQuoteItem WHERE refQuoteID = ". $xdb->qs($key));
		}
			return "Records Deleted. ";
		}
	}

	public static function DeleteQuoteItem($QuoteItemID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		// print_rr($_POST); die;

		//check if the page has been reloaded on the delete
		$row = $xdb->getRowSQL("SELECT QuoteItemID FROM slaQuoteItem WHERE QuoteItemID = ". $xdb->qs($QuoteItemID));
		if($row)
		{
			$xdb->doQuery("DELETE FROM slaQuoteItem WHERE QuoteItemID = ". $xdb->qs($QuoteItemID));

			return "Record Deleted. ";
		}
		else
		{
			return "Record does not exist or may have already been deleted.";
		}
	}

	public static function DeleteAdditionalLicense($QuoteID, $intDeletedRowGroup)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;
		// print_rr($_POST); die;

		//Preload array
		$arrService = array();
		$rstService = $xdb->doQuery("SELECT * FROM slaService WHERE slaService.strType='Additional License' ORDER BY intDisplayOrder,strService DESC",0);

		while($rowService = $xdb->fetch_object($rstService))
		{
			$arrService[$rowService->ServiceID] = $rowService;
		}
		//print_rr($arrService); //die;

		//go
		$rstQI = $xdb->doQuery("
			SELECT `intRowGroup`,`refServiceID`,QuoteItemID, slaQuoteItem.strPlannerName
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Additional License')
			ORDER BY intRowGroup,ServiceID",0);

		while($rowQI = $xdb->fetch_object($rstQI))
		{
			$arrServiceGroup[$rowQI->intRowGroup][$rowQI->refServiceID] = $rowQI->QuoteItemID;
		}

		foreach ($arrServiceGroup[$intDeletedRowGroup] AS $ServiceID => $QuoteItem)
		{
			$xdb->doQuery("DELETE FROM slaQuoteItem WHERE QuoteItemID = $QuoteItem");
		}

		return "Record(s) Deleted. ";
	}

	public static function generateQuoteSummaryContentHTML($QuoteID, $blnPDF=0, $strXPlanSummary)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		$rowServiceIBC = $xdb->getRowSQL("SELECT * FROM slaService WHERE blnIBC = 1", 0); //20181126 - IBC Course - pj

		$rowServiceAssetMapPlanner = $xdb->getRowSQL("SELECT * FROM slaService WHERE blnAssetMapPlanner = 1", 0); //20181126 - IBC Course - pj

		$rowServiceAssetMapAdmin = $xdb->getRowSQL("SELECT * FROM slaService WHERE blnAssetMapAdmin = 1", 0); //20181126 - IBC Course - pj



		//used mainly to calculate the discount
		$rowQuote = $xdb->getRowSQL("
			SELECT slaQuote.*, vieWPS.strWPS
			FROM slaQuote INNER JOIN vieWPS on slaQuote.refWPSID = vieWPS.WPSID
			WHERE QuoteID = ".$xdb->qs($QuoteID)
			, 0);

		//20191121 - Add 5% increase as of 1 January 2020 - Rachel
		//Pricing Increase effective as of 1 April 2020
		$intPriceIncreaseMultiply = 1;
		if(strtotime($rowQuote->dtAgreementStartDate) >= strtotime("2020-07-01")){
				$intPriceIncreaseMultiply = 1.05; //5% incre
		}

		$dblTotalRateYear1 = 0;
		$dblTotalRateMaintenance = 0;
		$dblTotalRatePerPlannerYear1 = 0;
		$dblTotalRatePerPlannerYear1 = 0;

		//Preload array   *****************************************************************
		$rstFP = $xdb->doQuery("
			SELECT slaQuoteItem.*, slaService.strService
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Financial Planner Service')
			ORDER BY slaQuoteItem.strPlannerName", 0);
		while($rowFP = $xdb->fetch_object($rstFP))
		{	
		// print_rr($rowFP);		
			$arrServiceFPS[$rowFP->QuoteItemID] = $rowFP;

			if($rowFP->intIBC != 0)
				$arrIBC[$rowFP->strPlannerName] = $rowFP->strPlannerName; //20181126 - IBC Course - pj

			if($rowFP->intAssetMapPlanner != 0)
				$arrAssetMapPlanner[$rowFP->strPlannerName] = $rowFP->strPlannerName; //20191120 - Asset Map Pilot Planner License - Rachel	

			if($rowFP->intAssetMapAdmin != 0)
				$arrAssetMapAdmin[$rowFP->strPlannerName] = $rowFP->strPlannerName; //20191120 - Asset Map Pilot Planner License - Rachel				

		}//print_rr(arrServiceFPS); print_rr($arrIBC);

		if(!$arrServiceFPS){ //Corporate Partner

			$rstFP = $xdb->doQuery("
				SELECT slaQuoteItem.*
				FROM slaQuoteItem 
				WHERE refQuoteID=".$xdb->qs($QuoteID)." AND refServiceID =0
				ORDER BY slaQuoteItem.strPlannerName", 0);
			while($rowFP = $xdb->fetch_object($rstFP))
			{	
			// print_rr($rowFP);		
				$arrServiceFPS[$rowFP->QuoteItemID] = $rowFP;

				if($rowFP->intIBC != 0)
					$arrIBC[$rowFP->strPlannerName] = $rowFP->strPlannerName; //20181126 - IBC Course - pj

				if($rowFP->intAssetMapPlanner != 0)
					$arrAssetMapPlanner[$rowFP->strPlannerName] = $rowFP->strPlannerName; //20191120 - Asset Map Pilot Planner License - Rachel	

				if($rowFP->intAssetMapAdmin != 0)
					$arrAssetMapAdmin[$rowFP->strPlannerName] = $rowFP->strPlannerName; //20191120 - Asset Map Pilot Planner License - Rachel				

			}//print_rr(arrServiceFPS); print_rr($arrIBC);


		}

		if(!$arrAssetMapPlanner && !$arrAssetMapAdmin){
			$rowMap = $xdb->getRowSQL("SELECT * 
			FROM slaQuoteItem 
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (intAssetMapPlanner = 1 OR intAssetMapAdmin = 1)
			ORDER BY slaQuoteItem.strPlannerName",0);

			if($rowMap->intAssetMapPlanner == 1){
				$arrServiceFPS[$rowMap->QuoteItemID] = $rowMap;
				$arrAssetMapPlanner[$rowMap->strPlannerName] = $rowMap->strPlannerName;
			}

			if($rowMap->intAssetMapAdmin == 1){
				$arrServiceFPS[$rowMap->QuoteItemID] = $rowMap;
				$arrAssetMapAdmin[$rowMap->strPlannerName] = $rowMap->strPlannerName;
			}

		}
// print_rr($arrAssetMapAdmin);
// print_rr($arrIBC);

		//select all BMS except Xplan (ID = 8)
		$rstBMS = $xdb->doQuery("
			SELECT slaQuoteItem.QuoteItemID,slaQuoteItem.strRateType,(slaQuoteItem.dblRateYear1*$intPriceIncreaseMultiply) AS dblRateYear1,(slaQuoteItem.dblRateMaintenance*$intPriceIncreaseMultiply) AS dblRateMaintenance,slaService.strService
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Business Management Service' AND slaService.ServiceID != 8 AND slaService.ServiceID != 34)
			ORDER BY intDisplayOrder",0);
		while($rowBMS = $xdb->fetch_object($rstBMS))
		{
			$arrServiceBMS[$rowBMS->QuoteItemID] = $rowBMS;
		}

		//select Xplan BMS (ID = 8)
		$rstXPlan = $xdb->doQuery("
			SELECT slaQuoteItem.QuoteItemID,slaQuoteItem.strRateType,(slaQuoteItem.dblRateYear1*$intPriceIncreaseMultiply) AS dblRateYear1,(slaQuoteItem.dblRateMaintenance*$intPriceIncreaseMultiply) AS dblRateMaintenance, dblCustomIBCRate, dblCustomAssetMapPlannerRate, dblCustomAssetMapAdmin,   slaService.strService
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Business Management Service' AND slaService.ServiceID = 8)
			ORDER BY intDisplayOrder",0);
		while($rowXPlan = $xdb->fetch_object($rstXPlan))
		{
			$arrServiceXPlan[$rowXPlan->QuoteItemID] = $rowXPlan;
		}

		//go
		//*************************************************************************************************
		//**************************** Financial Planning section        **********************************
		//*************************************************************************************************
		$dblSubTotalRate = 0;

		if(count($arrServiceFPS) == 0)
		{
			$arrServiceFPS[0] = "";
		}

		$strContentInnerDetailFP = "";
		// print_rr($arrServiceFPS);
		foreach ($arrServiceFPS AS $QuoteItemID => $rowQuoteItem)
		{

			$strPlannerName = $rowQuoteItem->strPlannerName;
			$strServiceDetail = $rowQuoteItem->strService." - ".$rowQuoteItem->strRateType;
			if($arrIBC[$strPlannerName]){//20181205 - IBC Course - pj :: changes/add
				// $strServiceDetail .= $BR. "*". $rowServiceIBC->strService;
			
				$strIBCService = $rowServiceIBC->strService;
				$strIBCServiceRateYear1 += $rowServiceIBC->dblCostYear1;
					

				$arrIBCPlanners[$strPlannerName]["IBCService"] = $rowServiceIBC->strService;

				$arrIBCPlanners[$strPlannerName]["QuoteItemID"] = $rowQuoteItem->QuoteItemID;
				if($rowQuoteItem->dblCustomIBCRate != "" && $rowQuoteItem->dblCustomIBCRate > 0){
					$arrIBCPlanners[$strPlannerName]["IBCCostMaintenance"] = $rowQuoteItem->dblCustomIBCRate;
				}else{
					$arrIBCPlanners[$strPlannerName]["IBCCostMaintenance"] = $rowServiceIBC->dblCostMaintenance;
				}

				$strIBCServiceRateMaintenance += $arrIBCPlanners[$strPlannerName]["IBCCostMaintenance"];


				$arrIBCPlanners[$strPlannerName]["IBCCostYear1"] = $rowServiceIBC->dblCostYear1;
				
			}
			$strAssetMapPlanner = $strPlannerName;
			
			if($arrAssetMapPlanner[$strPlannerName]){//20181205 - IBC Course - 
				
				$strAssetMapPlannerService = $rowServiceAssetMapPlanner->strService;
				$strAssetMapPlannerServiceRateYear1 = $rowServiceAssetMapPlanner->dblCostYear1;

				// print_rr($rowQuoteItem->dblCustomAssetMapPlannerRate);
				$AssetMapPlannerQuoteItemID = $rowQuoteItem->QuoteItemID;
				if($rowQuoteItem->dblCustomAssetMapPlannerRate != "" && $rowQuoteItem->dblCustomAssetMapPlannerRate > 0){
					$strAssetMapPlannerServiceRateMaintenance = $rowQuoteItem->dblCustomAssetMapPlannerRate;
				}else{
					$strAssetMapPlannerServiceRateMaintenance = $rowServiceAssetMapPlanner->dblCostMaintenance;
				}
				

				$arrAssetMapPlanner = "";

			}
			if($arrAssetMapAdmin[$strPlannerName]){//20181205 - IBC Course - pj :: changes/add
				// $strServiceDetail .= $BR. "*". $rowServiceIBC->strService;
				$AssetMapAdminQuoteItemID = $rowQuoteItem->QuoteItemID;

				$strAssetMapAdminService = $rowServiceAssetMapAdmin->strService;
				$strAssetMapAdminServiceRateYear1 = $rowServiceAssetMapAdmin->dblCostYear1;
				// $strAssetMapAdminServiceRateMaintenance = $rowServiceAssetMapAdmin->dblCostMaintenance;

				if($rowQuoteItem->dblCustomAssetMapAdmin != "" && $rowQuoteItem->dblCustomAssetMapAdmin > 0){
					$strAssetMapAdminServiceRateMaintenance = $rowQuoteItem->dblCustomAssetMapAdmin;
				}else{
					$strAssetMapAdminServiceRateMaintenance = $rowServiceAssetMapAdmin->dblCostMaintenance;
				}

			}

			$strRateYear1 = number_format($rowQuoteItem->dblRateYear1*$intPriceIncreaseMultiply,2, '.', ',');
			$strRateMaintenance = number_format($rowQuoteItem->dblRateMaintenance*$intPriceIncreaseMultiply,2, '.', ',');

			$strConcatServiceDetail = $strPlannerName ." - ". $strServiceDetail;

			if($QuoteItemID == 0 || $rowQuote->strPartnerType == "Strategic Partner (Acsis Legacy only)" || strpos($strConcatServiceDetail, '-  -') !== false)
			{
				$strPlannerName = "";
				$strServiceDetail = "n/a";
				$strRateYear1 = "0";
				$strRateMaintenance = "0";
				$strConcatServiceDetail = $strServiceDetail;
				//$strConcatServiceDetail = "Financial Planning Services - ".$strServiceDetail;
			}

			// $strContentInnerDetailFP .= "
			//       <tr>
			//          <td>
			//             <table style='margin:0;padding:0;border:0;border-collapse:collapse; height:100%;width:100%;'>
			//                <tr>
			//                   <td align='left' style='width:140px;'>
			//                      $strPlannerName
			//                   </td>
			//                   <td align='left' >
			//                      $strServiceDetail
			//                   </td>
			//                </tr>
			//             </table>
			//             </td>
			//          <td align='right' style='text-align:right;'>
			//             $strRateYear1
			//          </td>
			//          <td align='right' style='text-align:right;'>
			//             $strRateMaintenance
			//          </td>";
			if($rowQuote->strPartnerType == Quote::$CORPORATE_PARTNER && $strServiceDetail != "n/a" && $blnPDF != 1){

				$strContentInnerDetailFP .= "
						<tr>
							<td>
								$strConcatServiceDetail
							</td>
							<td></td>
							<td align='right' style='text-align:right;'>
								<input type='text' name='dblCorporateRateYear1[$rowQuoteItem->QuoteItemID]' value='R$strRateYear1'>
							</td>
							<td align='right' style='text-align:right;'>
							<input name='dblCorporateRateMaintenance[$rowQuoteItem->QuoteItemID]' value='R$strRateMaintenance'>
							</td>";

			}else{

				$strContentInnerDetailFP .= "
						<tr>
							<td>
								$strConcatServiceDetail
							</td>
							<td></td>
							<td align='right' style='text-align:right;'>
								R$strRateYear1
							</td>
							<td align='right' style='text-align:right;'>
								R$strRateMaintenance
							</td>";

			}

			$strContentInnerDetailFPPDF .= "
					<tr>
						<td align='left' >$strConcatServiceDetail
						</td>
						<td></td>
						<td align='right' style='text-align:right;'>
							R$strRateYear1
						</td>
						<td align='right' style='text-align:right;'>
							R$strRateMaintenance
						</td>
					</tr>";
// print_rr($arrIBCPlanners);
			if($rowQuoteItem->strRateType == "Maintenance")
			{
				$dblSubTotalRateYear1 +=($rowQuoteItem->dblRateMaintenance*$intPriceIncreaseMultiply);
				$dblTotalRateYear1 += ($rowQuoteItem->dblRateMaintenance*$intPriceIncreaseMultiply);
			}
			else
			{
				$dblSubTotalRateYear1 += ($rowQuoteItem->dblRateYear1*$intPriceIncreaseMultiply);
				$dblTotalRateYear1 +=($rowQuoteItem->dblRateYear1*$intPriceIncreaseMultiply);
			}

			$dblSubTotalRateMaintenance += ($rowQuoteItem->dblRateMaintenance*$intPriceIncreaseMultiply);
			$dblTotalRateMaintenance += ($rowQuoteItem->dblRateMaintenance*$intPriceIncreaseMultiply);
		}

		//20160210 show planner items -requested by Pj - done byChristiaan
		//Hide if Acsis Legacy only client
	// if($rowQuote->strPartnerType != "Strategic Partner (Acsis Legacy only)"){
		if($blnPDF == 1)
		{
			$strContentDetail .= "
			<tr>
				<td><b>Financial Planning Services</b>
				</td>
				<td> Fees per Planner
				</td>
				<td>
				</td>
				<td>
				</td>
			</tr>";
		  $strContentDetail .= "$strContentInnerDetailFPPDF";
			// <tr>
			//    <th align='left' style='text-align:left;'>
			//    </th>
			//    <th align='right' style='text-align:right;'>
			//       ".number_format($dblSubTotalRateYear1,0, '.', ',')."
			//    </th>
			//    <th align='right' style='text-align:right;'>
			//       ".number_format($dblSubTotalRateMaintenance,0, '.', ',')."
			//    </th>
			// </tr>";
		}
		else
		{
			$strContentDetail .= "
			<tr>
				<td><b>Financial Planning Services</b>
				</td>
				<td>Fees per Planner
				</td>
				<td>
				</td>
				<td>
				</td>
			</tr>";
			$strContentDetail .= "$strContentInnerDetailFP";
			// <tr>
			//    <th align='right' style='text-align:right;'>Sub Total</th>
			//    <th align='right' style='text-align:right;'>
			//       ".number_format($dblSubTotalRateYear1,0, '.', ',')."
			//    </th>
			//    <th align='right' style='text-align:right;'>
			//       ".number_format($dblSubTotalRateMaintenance,0, '.', ',')."
			//    </th>
			// </tr>";
		}
	// }

		//*************************************************************************************************
		//****************************             BMS section           **********************************
		//*************************************************************************************************

		$dblSubTotalRateYear1 = 0;
		$dblSubTotalRateMaintenance = 0;

		$blServiceBMS = true;
		if(count($arrServiceBMS) == 0)
		{
			$arrServiceBMS[0] = "";
			$blServiceBMS = false;

		}

		$strContentInnerDetailBMS = "";
		$strServiceDetailPDF = "";
		foreach ($arrServiceBMS AS $QuoteItemID => $rowQuoteItem)
		{

			$strPlannerName = $rowQuoteItem->strPlannerName;
			$strServiceDetail = $rowQuoteItem->strService." - ".$rowQuoteItem->strRateType;
			$strRateYear1 = number_format($rowQuoteItem->dblRateYear1,2, '.', ',');
			$strRateMaintenance = number_format($rowQuoteItem->dblRateMaintenance  ,2, '.', ',');
			$strServiceDetailPDF = "- ".$strServiceDetail;

			if($QuoteItemID == 0)
			{
				$strPlannerName = "";
				$strServiceDetail = "n/a";
				$strServiceDetailPDF = "";
				$strRateYear1 = "0";
				$strRateMaintenance = "0";
			}


			if($rowQuote->strPartnerType == Quote::$CORPORATE_PARTNER 
				&& $strServiceDetail != "n/a" && $blnPDF != 1){

				$strContentInnerDetailBMS .= "
						<tr>
							<td>
								$strServiceDetail
							</td>
							<td></td>
							<td align='right' style='text-align:right;'>
								<input type='text' name='dblBMSCorporateRateYear1[$rowQuoteItem->QuoteItemID]' value='R$strRateYear1'>
							</td>
							<td align='right' style='text-align:right;'>
							<input name='dblBMSCorporateRateMaintenance[$rowQuoteItem->QuoteItemID]' value='R$strRateMaintenance'>
							</td>";

			}else{

				$strContentInnerDetailBMS .= "
						<tr>
							<td>
								$strServiceDetail
							</td>
							<td></td>
							<td align='right' style='text-align:right;'>
								R$strRateYear1
							</td>
							<td align='right' style='text-align:right;'>
								R$strRateMaintenance
							</td>";

			}


			if($rowQuoteItem->strRateType == "Maintenance")
			{
				$dblSubTotalRateYear1 +=$rowQuoteItem->dblRateMaintenance;
				$dblTotalRateYear1 += $rowQuoteItem->dblRateMaintenance;
			}
			else
			{
				$dblSubTotalRateYear1 += $rowQuoteItem->dblRateYear1;
				$dblTotalRateYear1 +=$rowQuoteItem->dblRateYear1;
			}

			$dblSubTotalRateMaintenance += $rowQuoteItem->dblRateMaintenance;
			$dblTotalRateMaintenance += $rowQuoteItem->dblRateMaintenance;
		}

		// if($blnPDF == 1)
		// {
		//    $strContentDetail .= "
		//       <tr>
		//          <td align='left' style='text-align:left;'>Business Management Services (BMS) $strServiceDetailPDF
		//          </td>
		//          <td align='right' style='text-align:right;'>
		//             ".number_format($dblSubTotalRateYear1,0, '.', ',')."
		//          </td>
		//          <td align='right' style='text-align:right;'>
		//             ".number_format($dblSubTotalRateMaintenance,0, '.', ',')."
		//          </td>
		//       </tr>";
		// }
		// else
		// {

		if( ($rowQuote->strPartnerType != "Strategic Partner (Acsis Legacy only)" && $blServiceBMS !== false) || $strContentInnerDetailBMS !="")
		{
			$strContentDetail .= "
			<tr>
				<td><b>Business Management Services (BMS)</b>
				</td>
				<td>Fees per Practice
				</td>
				<td>
				</td>
				<td>
				</td>
			</tr>";

			$strContentDetail .= "
			$strContentInnerDetailBMS";
		}
  

	//*************************************************************************************************
	//****************************  Additional Licenses *Individual*  **********************************
	//*************************************************************************************************

		//Preload array
		$arrService = array();
		$rstService = $xdb->doQuery("SELECT * FROM slaService WHERE slaService.strType='Additional License' ORDER BY intDisplayOrder,strService DESC",0);

		while($rowService = $xdb->fetch_object($rstService))
		{
			$arrService[$rowService->ServiceID] = $rowService;
		}
		// //print_rr($arrService);

		$row = $xdb->getRowSQL("
			SELECT ServiceID, count(ServiceID) as 'intServiceCount', strService,SUM(dblRateYear1*$intPriceIncreaseMultiply) as 'dblRateYear1', SUM(dblRateMaintenance*$intPriceIncreaseMultiply) as 'dblRateMaintenance'
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Additional License')
			GROUP BY ServiceID",0);
		if($row)
		{
			foreach($arrService AS $ServiceID => $rowService)
			{
				$arrServiceAL = array();
				$rstAL = $xdb->doQuery("
					SELECT slaQuoteItem.QuoteItemID,slaQuoteItem.strPlannerName,slaQuoteItem.strRateType,(slaQuoteItem.dblRateYear1*$intPriceIncreaseMultiply) AS dblRateYear1,(slaQuoteItem.dblRateMaintenance*$intPriceIncreaseMultiply) AS dblRateMaintenance,slaService.strService
					FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
					WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Additional License') AND ServiceID=$ServiceID
					ORDER BY intDisplayOrder",0);

				while($rowAL = $xdb->fetch_object($rstAL))
				{
					$arrServiceAL[$rowAL->QuoteItemID] = $rowAL;
				}

				$strContentInnerDetailAL = "";
				foreach ($arrServiceAL AS $QuoteItemID => $rowQuoteItem)
				{
					$strPlannerName = $rowQuoteItem->strPlannerName;
					$strServiceDetail = $rowQuoteItem->strService.($strPlannerName==""?"":" - ".$strPlannerName);
					$strRateYear1 = number_format($rowQuoteItem->dblRateYear1,2, '.', ',');
					$strRateMaintenance = number_format($rowQuoteItem->dblRateMaintenance  ,2, '.', ',');


					if($QuoteItemID == 0)
					{
						$strPlannerName = "";
						$strServiceDetail = "$rowService->strService";

						$strRateYear1 = "0";
						$strRateMaintenance = "0";
					}
					$strContentInnerDetailAL .= "
							<tr>
								<td>
									$strServiceDetail
								</td>
								<td></td>
								<td align='right' style='text-align:right;'>
									R$strRateYear1
								</td>
								<td align='right' style='text-align:right;'>
									R0
								</td>";

					$dblTotalRateYear1 += $rowQuoteItem->dblRateYear1;
					//$dblTotalRateMaintenance += $rowQuoteItem->dblRateMaintenance;
				}
				$strContentInnnerDetail .= "
				<tr>
					$strContentInnerDetailAL
				</tr>";
			}
					// <tr>
					// 	<td><b>Additional Licenses</b>
					// 	</td>
					// 	<td>
					// 	</td>
					// 	<td>
					// 	</td>
					// 	<td>
					// 	</td>
					// </tr>
			$strContentDetail .= "

					$strContentInnnerDetail";
		}
		else
		{
			 // $strContentDetail .= "
				// <tr>
				// 	<td><b>Additional Licenses</b>
				// 	</td>
				// 	<td>
				// 	</td>
				// 	<td>
				// 	</td>
				// 	<td>
				// 	</td>
				// </tr>
				// <tr>
				// 	<td align='left'>n/a</td>
				// 	<td align='right'>
					  
				// 	</td>
				// 	<td align='right'>
					  
				// 	</td>
				// 	<td align='right'>
					  
				// 	</td>
				// </tr>";
		}


		//*************************************************************************************************
		//****************************             XPLAN section           **********************************
		//*************************************************************************************************
		$dblSubTotalRateYear1 = 0;
		$dblSubTotalRateMaintenance = 0;

		if(count($arrServiceXPlan) == 0)
		{
			$arrServiceXPlan[0] = "";
		}

		//print_rr($arrServiceXPlan);

		$strContentInnerDetailXPlan = "";
		foreach ($arrServiceXPlan AS $QuoteItemID => $rowQuoteItem)
		{

			$strPlannerName = $rowQuoteItem->strPlannerName;
			$strServiceDetail = $rowQuoteItem->strService." - ".$rowQuoteItem->strRateType;
			$strRateYear1 = number_format($rowQuoteItem->dblRateYear1,2, '.', ',');

			$strRateMaintenance = number_format($rowQuoteItem->dblRateMaintenance,2, '.', ',');

			if($QuoteItemID == 0)
			{
				$strPlannerName = "";
				$strServiceDetail = "n/a";
				$strRateYear1 = "";
				$strRateMaintenance = "";

				if($rowQuote->strPartnerType != Quote::$STRATEGIC_PARTNER)
				{
					$strRateYear1 = "";
					$strRateMaintenance = "";
				}
			}

			// $strContentInnerDetailXPlan .= "
			//       <tr>
			//           <td>
			//             <table style='margin:0;padding:0;border:0;border-collapse:collapse; height:100%;width:100%;'>
			//                <tr>
			//                   <td style='width:140px;'>
			//                      $SP
			//                   </td>
			//                   <td>
			//                      $strServiceDetail
			//                   </td>
			//                </tr>
			//             </table>
			//          </td>
			//          <td align='right' style='text-align:right;'>
			//             $strRateYear1
			//          </td>
			//          <td align='right' style='text-align:right;'>
			//             $strRateMaintenance
			//          </td>";

			if($rowQuote->strPartnerType == Quote::$CORPORATE_PARTNER && $blnPDF != 1){

				$strContentInnerDetailXPlan .= "
						<tr>
							<td>
								$strServiceDetail
							</td>
							<td></td>
							<td align='right' style='text-align:right;'>
								<input type='text' name='dblXPlanCorporateRateYear1[$rowQuoteItem->QuoteItemID]' value='R$strRateYear1'>
							</td>
							<td align='right' style='text-align:right;'>
							<input name='dblXPlanCorporateRateMaintenance[$rowQuoteItem->QuoteItemID]' value='R$strRateMaintenance'>
							</td>";

			}else{

				$strContentInnerDetailXPlan .= "
						<tr>
							<td>
								$strServiceDetail
							</td>
							<td></td>
							<td align='right' style='text-align:right;'>
								R$strRateYear1
							</td>
							<td align='right' style='text-align:right;'>
								R$strRateMaintenance
							</td>";

			}



			if($rowQuoteItem->strRateType == "Maintenance")
			{
				$dblSubTotalRateYear1 +=$rowQuoteItem->dblRateMaintenance;
				$dblTotalRateYear1 += $rowQuoteItem->dblRateMaintenance;
			}
			else
			{
				$dblSubTotalRateYear1 += $rowQuoteItem->dblRateYear1;
				$dblTotalRateYear1 +=$rowQuoteItem->dblRateYear1;
			}

			$dblSubTotalRateMaintenance += $rowQuoteItem->dblRateMaintenance;
			$dblTotalRateMaintenance += $rowQuoteItem->dblRateMaintenance;

			if($strServiceDetail != "n/a"){
				$XplanSelected = "true";
			}else{
				$XplanSelected = "false";
			}


		}

		// if($blnPDF == 1)
		// {
		//    $strContentDetail .= "
		//    <tr>
		//       <td align='left' style='text-align:left;'>Old Mutual Wealth Xplan Multi-site (CRMIntegrator)
		//       </td>
		//       <td align='right' style='text-align:right;'>
		//          ".number_format($dblSubTotalRateYear1,0, '.', ',')."
		//       </td>
		//       <td align='right' style='text-align:right;'>
		//          ".number_format($dblSubTotalRateMaintenance,0, '.', ',')."
		//       </td>
		//    </tr>";
		// }
		// else
		// {
		//20180326 - remove all mention of (CRMIntegrator) and replace with "OM Wealth Xplan Multi-site" - CL
		if($XplanSelected == "true"){
			$strContentDetail .= "
			<tr>
				<td><b>Client Relationship Management (CRM) Tools</b>
				</td>
				<td> Fees per Practice
				</td>
				<td>
				</td>
				<td>
				</td>
			</tr>";
			$strContentDetail .= "$strContentInnerDetailXPlan";
		}
			// <tr>
			//    <th align='right' style='text-align:right;'>Sub Total</th>
			//    <th align='right' style='text-align:right;'>
			//       ".number_format($dblSubTotalRateYear1,0, '.', ',')."
			//    </th>
			//    <th align='right' style='text-align:right;'>
			//       ".number_format($dblSubTotalRateMaintenance,0, '.', ',')."
			//    </th>
			// </tr>";
		//}


		//*************************************************************************************************
		//****************************               totals              **********************************
		//*************************************************************************************************

		//1. check the discount

		$arrDiscount = array();
		$blnPercentDiscountCheck = 0;
		$trDiscount = "";
		$intPlannerCount = count($arrServiceFPS);

		$dblTotalPreDiscountYear1 = $dblTotalRateYear1;
		$dblTotalPreDiscountMaintenance = $dblTotalRateMaintenance;

		if($rowQuote->strPartnerType == Quote::$STRATEGIC_PARTNER)
		{
			$arrDiscount[1]->strPercentDiscount += "".($SystemSettings["SLADiscountStratPartner"] * 100);
			$arrDiscount[1]->intPercentDiscount += $SystemSettings["SLADiscountStratPartner"];
			$arrDiscount[1]->strDiscountDescription = "Less ".$arrDiscount[1]->strPercentDiscount."% (Strategic Partner Discount)";
			$blnPercentDiscountCheck = 1;
		}

		if($intPlannerCount > 9)
		{
			$arrDiscount[2]->strPercentDiscount += "".($SystemSettings["SLADiscount10Planners"] * 100);
			$arrDiscount[2]->intPercentDiscount += $SystemSettings["SLADiscount10Planners"];
			$arrDiscount[2]->strDiscountDescription = "Less ".$arrDiscount[2]->strPercentDiscount."% (10 Planners or more)";
			$blnPercentDiscountCheck = 1;
		}
		else if($intPlannerCount > 4)
		{
			$arrDiscount[2]->strPercentDiscount += "".($SystemSettings["SLADiscount5Planners"] * 100);
			$arrDiscount[2]->intPercentDiscount += $SystemSettings["SLADiscount5Planners"];
			$arrDiscount[2]->strDiscountDescription = "Less ".$arrDiscount[2]->strPercentDiscount."% (5 Planners or more)";
			$blnPercentDiscountCheck = 1;
		}

		if($blnPercentDiscountCheck == 1)
		{
			$trDiscount .= "<tr>
						<th colspan='2' align='right' style='text-align:right;border-top:2px solid black;'>Sub Total</th>
						<th align='right' style='text-align:right;border-top:2px solid black;'>R".number_format($dblTotalRateYear1,2, '.', ',')."
						</th>
						<th align='right' style='text-align:right;border-top:2px solid black;'>R".number_format($dblTotalRateMaintenance,2, '.', ',')."
						</th>
					</tr>";

			$dblTotalDiscountYear1 = 0;
			$dblTotalDiscountMaintenance = 0;
			foreach($arrDiscount AS $intCount => $rowDiscount)
			{
				//print_rr($rowDiscount);
				$dblDiscountYear1 = $rowDiscount->intPercentDiscount * $dblTotalPreDiscountYear1;
				$dblDiscountMaintenance = $rowDiscount->intPercentDiscount * $dblTotalPreDiscountMaintenance;

				$dblTotalDiscountYear1 = $dblDiscountYear1;
				$dblTotalDiscountMaintenance = $dblDiscountMaintenance;

				$dblTotalRateYear1 = $dblTotalRateYear1 - $dblTotalDiscountYear1;
				$dblTotalRateMaintenance = $dblTotalRateMaintenance - $dblTotalDiscountMaintenance;

				$trDiscount .= "<tr>
									<th colspan='2' align='right' style='text-align:right;border-top:2px solid black;'>$rowDiscount->strDiscountDescription</th>
									<th align='right' style='text-align:right;border-top:2px solid black;'>R-".number_format($dblTotalDiscountYear1,2, '.', ',')."
									</th>
									<th align='right' style='text-align:right;border-top:2px solid black;'>R-".number_format($dblTotalDiscountMaintenance,2, '.', ',')."
									</th>
								</tr>";
			}
		}

		//20180320 - Add if Statement to make VAT 14% if createDate of Proposal is < "20180401"
		$VAT = $SystemSettings[VAT];
		if(strtotime($rowQuote->dtCreationDate) < strtotime("2018-04-01") && strtotime(date("Y-m-d")) >= strtotime("2018-04-01"))
		{
			$VAT = 0.14;
		}

		$strTotalPayableAmountY1 = $dblTotalRateYear1;
		$strTotalPayableAmountOngoing = $dblTotalRateMaintenance;

		//Exclude Map Asset from VAT
		$strTotalPayableY1VAT = ( $strTotalPayableAmountY1 / (1 + $VAT)) * $VAT;

		$strTotalPayableOngoingVAT = ($strTotalPayableAmountOngoing / (1 + $VAT)) * $VAT;



		$strMonthlyDebitAmountY1 = round( ($strTotalPayableAmountY1)  /12 , 2);
		$strMonthlyDebitAmountOngoing = round(($strTotalPayableAmountOngoing) /12 , 2);

		$strAverageMonthlyPerPlannerY1 = round(($strMonthlyDebitAmountY1/$intPlannerCount),2);
		$strAverageMonthlyPerPlannerOngoing = round(($strMonthlyDebitAmountOngoing/$intPlannerCount),2);

		$trDiscount .= "<tr>
								<th colspan='2' align='right' style='text-align:right;border-top:2px solid black;'><b>Total Basic Services</b></th>
								<th align='right' style='text-align:right;border-top:2px solid black;'>R".number_format($dblTotalRateYear1,2, '.', ',')."
								</th>
								<th align='right' style='text-align:right;border-top:2px solid black;'>R".number_format($dblTotalRateMaintenance,2, '.', ',')."
								</th>
							</tr>
						<tr>
							<th colspan='2' align='right' style='text-align:right;border-top:2px solid black;'>
								Monthly Debit Order Amount
							</th>
							<th align='right' style='text-align:right;border-top:2px solid black;'>R".number_format($strMonthlyDebitAmountY1,2, '.', ',')."
							</th>
							<th align='right' style='text-align:right;border-top:2px solid black;'>
							R".number_format($strMonthlyDebitAmountOngoing,2, '.', ',')."
								
							</th>
						</tr>
						<tr bgcolor='#fff'>
							<th colspan='2' align='right' style='text-align:right;border-top:2px solid black;'>
								Average monthly fee Per Planner
							</th>
							<th align='right' style='text-align:right;border-top:2px solid black;'>R".number_format( $strAverageMonthlyPerPlannerY1 ,2, '.', ',')."
							</th>
							<th align='right' style='text-align:right;border-top:2px solid black;'>R".number_format($strAverageMonthlyPerPlannerOngoing,2, '.', ',')."
							</th>
						</tr>";

		//2. get the totals
		$intPlannerCount = count($arrServiceFPS) != 0?count($arrServiceFPS):1;

		$dblTotalRateMonthlyDebitYear1 = round ($dblTotalRateYear1 / 12);
		$dblTotalRateMonthlyDebitMaintenance = round ($dblTotalRateMaintenance / 12);

		$dblTotalRatePerPlannerYear1 = round($dblTotalRateMonthlyDebitYear1 /$intPlannerCount);
		$dblTotalRatePerPlannerMaintenance = round($dblTotalRateMonthlyDebitMaintenance /$intPlannerCount);

		$strTotalRatePerPlannerYear1 = number_format($dblTotalRatePerPlannerYear1,2, '.', ',');
		$strTotalRatePerPlannerMaintenance = number_format($dblTotalRatePerPlannerMaintenance,2, '.', ',');



		if($intPlannerCount == 0 || isset($arrServiceFPS[0]))
		{
			$strTotalRatePerPlannerYear1 = "0";
			$strTotalRatePerPlannerMaintenance = "0";
		}

		$dblTotalVATYear1 = ($dblTotalRateYear1 / (1 + $VAT)) * $VAT;
		$dblTotalVATMaintenance = ($dblTotalRateMaintenance / (1 + $VAT)) * $VAT;

		$strContentTotals =  "
								<tr>
									<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
									<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
									<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
								</tr>
								R$trDiscount
								";
// "								<tr>
// 									<th colspan='2' align='right' style='text-align:right;'><b>Monthly debit order amount</b></th>
// 									<th align='right' style='text-align:right;'>
// 										".number_format($dblTotalRateMonthlyDebitYear1,0, '.', ',')."
// 									</th>
// 									<th align='right' style='text-align:right;'>
// 										".number_format($dblTotalRateMonthlyDebitMaintenance,0, '.', ',')."
// 									</th>
// 								</tr>
// 								<tr>
// 									<th colspan='2' align='right' style='text-align:right;border-top:2px solid black;'><i>Average monthly fee per planner</i></th>
// 									<th align='right' style='text-align:right;border-top:2px solid black;'>
// 										$strTotalRatePerPlannerYear1
// 									</th>
// 									<th align='right' style='text-align:right;border-top:2px solid black;'>
// 										$strTotalRatePerPlannerMaintenance
// 									</th>
// 								</tr>"



		//20181126 - IBC Course - pj
		//20181205 - IBC Course - pj :: changes/removed
		// $strIBC = "";
		// if(count($arrIBC) > 0)
		// {
		// 	foreach($arrIBC as $strPlannerName){

		// 		$strIBC .= "<li>$strPlannerName - $rowServiceIBC->strService</li>";
		// 	}
		// 	$strIBC = "
								
		// 		<ul>
		// 			$strIBC
		// 		</ul>";

		// 	//if(count($arrIBC) > 1){
		// 		$dblRate = round(10000 / 12, 2); //vd($dblRate);
		// 		$strIBC .= "
		// 		<i>*Note that the fees for the above course, R10 000 per person (including VAT), will be deducted by means of an additional debit order, over 12 months
		// 		, at a rate of R". number_format($dblRate, 2,'.',',')." per person per month
		// 		, starting in <b>December 2018</b> and ending in <b>November 2019</b>.</i>";
		// 	//}
		// 


	//**********************Additional Services**************
	$strAdditionalServicesContent = "";
	if($strIBCService){
		// print_rr($arrIBCPlanners);
		foreach ($arrIBCPlanners as $Planner => $rowPlanner) {
			// print_rr($rowPlanner["IBCCostMaintenance"]);
			// print_rr($rowPlanner[""]);
			
			if($rowQuote->strPartnerType == Quote::$CORPORATE_PARTNER && $blnPDF != 1){

					$strAdditionalServicesContent .= "
						<tr bgcolor='#fff'>
							<td>
								".str_replace("(Cape Town): R10,000", "($Planner)",$rowServiceIBC->strService)."

							</td>
							<td>Fees per Planner</td>
							<!--<td align='right' style='text-align:right;'>R".number_format($rowPlanner->IBCCostYear1,2, '.', ',')."

							</td> -->
							<td align='right' style='text-align:right;'><input name='dblIBCMaintenaceCost[".$rowPlanner["QuoteItemID"]."]' value='R".number_format($rowPlanner["IBCCostMaintenance"],2, '.', ',')."'> 
								
							</td>
						</tr>";
			}else{

					$strAdditionalServicesContent .= "
						<tr bgcolor='#fff'>
							<td>
								".str_replace("(Cape Town): R10,000", "($Planner)",$rowServiceIBC->strService)."

							</td>
							<td>Fees per Planner</td>
							<!--<td align='right' style='text-align:right;'>R".number_format($rowPlanner->IBCCostYear1,2, '.', ',')."

							</td> -->
							<td align='right' style='text-align:right;'>R".number_format($rowPlanner["IBCCostMaintenance"],2, '.', ',')."
								
							</td>
						</tr>";
			}
			// $rowQuote->strPartnerType == Quote::$CORPORATE_PARTNER

		}
	}

	// if($strIBCService){
	// 	$strAdditionalServicesContent .= "
	// 				<tr bgcolor='#fff'>
	// 					<td>
	// 						".str_replace("(Cape Town): R10,000", "($strAssetMapPlanner)",$rowServiceIBC->strService)."

	// 					</td>
	// 					<td>Fees per Planner</td>
	// 					<!--<td align='right' style='text-align:right;'>R".number_format($strIBCServiceRateYear1,2, '.', ',')."

	// 					</td> -->
	// 					<td align='right' style='text-align:right;'>R".number_format($strIBCServiceRateMaintenance,2, '.', ',')."
							
	// 					</td>
	// 				</tr>";
	// }

	if($strAssetMapPlannerService){

		if($rowQuote->strPartnerType == Quote::$CORPORATE_PARTNER && $blnPDF != 1){
				$strAdditionalServicesContent .= "
				<tr bgcolor='#fff'>
					<td>
						".$rowServiceAssetMapPlanner->strService. " ($strAssetMapPlanner)"  ."

					</td>
					<td height='100'>Fees per Planner</td>
					<!--<td align='right' style='text-align:right;'>R".number_format($strAssetMapPlannerServiceRateYear1,2, '.', ',')."

					</td> -->
					<td align='right' style='text-align:right;'><input type='text' name='dblCustomMapPlannerRate[$AssetMapPlannerQuoteItemID]' value='R".number_format($strAssetMapPlannerServiceRateMaintenance,2, '.', ',')."'>
						
					</td>
				</tr>";
		}else{
				$strAdditionalServicesContent .= "
				<tr bgcolor='#fff'>
					<td>
						".$rowServiceAssetMapPlanner->strService. " ($strAssetMapPlanner)"  ."

					</td>
					<td height='100'>Fees per Planner</td>
					<!--<td align='right' style='text-align:right;'>R".number_format($strAssetMapPlannerServiceRateYear1,2, '.', ',')."

					</td> -->
					<td align='right' style='text-align:right;'>R".number_format($strAssetMapPlannerServiceRateMaintenance,2, '.', ',')."
						
					</td>
				</tr>";
		}

	}

	if($strAssetMapAdminService){

		if($rowQuote->strPartnerType == Quote::$CORPORATE_PARTNER && $blnPDF != 1){

		$strAdditionalServicesContent .= "
					<tr>
						<td>
							".$rowServiceAssetMapAdmin->strService."

						</td>
						<td height='100'>Fees per Administrator</td>
						<!-- <td align='right' style='text-align:right;'>R".number_format($strAssetMapAdminServiceRateYear1,2, '.', ',')."

						</td> -->
						<td align='right' style='text-align:right;'>
						<input type='text' name='dblCustomMapAdminRate[$AssetMapAdminQuoteItemID]' value='R".number_format($strAssetMapAdminServiceRateMaintenance,2, '.', ',')."'>

						
							
						</td>
					</tr>";

		}else{
			$strAdditionalServicesContent .= "
						<tr>
							<td>
								".$rowServiceAssetMapAdmin->strService."

							</td>
							<td height='100'>Fees per Administrator</td>
							<!-- <td align='right' style='text-align:right;'>R".number_format($strAssetMapAdminServiceRateYear1,2, '.', ',')."

							</td> -->
							<td align='right' style='text-align:right;'>R".number_format($strAssetMapAdminServiceRateMaintenance,2, '.', ',')."
								
							</td>
						</tr>";
		}

	}


	$rstValuationService = $xdb->doQuery("
			SELECT slaQuoteItem.QuoteItemID,slaQuoteItem.strRateType,(slaQuoteItem.dblRateYear1*$intPriceIncreaseMultiply) AS dblRateYear1,(slaQuoteItem.dblRateMaintenance*$intPriceIncreaseMultiply) AS dblRateMaintenance,dblCustomValuationRate,slaService.strService
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Business Management Service' AND slaService.ServiceID = 34)
			ORDER BY intDisplayOrder
			LIMIT 1",0);
	$strValuationServiceRateYear1 = 0;
	$strValuationServiceRateMaintenance = 0;
	while($rowValuation = $xdb->fetch_object($rstValuationService))
	{
			$arrServiceValuation[$rowValuation->QuoteItemID] = $rowValuation;
			$strValuationServiceRateYear1 = $rowValuation->dblRateYear1;
			$strValuationServiceRateMaintenance = $rowValuation->dblRateMaintenance;

			if($rowValuation->dblCustomValuationRate != ""  && $rowValuation->dblCustomValuationRate > 0){
				$strValuationServiceRateOngoing = $rowValuation->dblCustomValuationRate;

			}else{
				$strValuationServiceRateOngoing = $strValuationServiceRateYear1/12;
			}
			
			if($rowQuote->strPartnerType == Quote::$CORPORATE_PARTNER && $strServiceDetail != "n/a" && $blnPDF != 1){

				$strAdditionalServicesValuationContent .= "
							<tr bgcolor='#fff'>
								<td>
									".$rowValuation->strService."

								</td>
								<td>Fees per Practice</td>
								<!--<td align='right' style='text-align:right;'>R".number_format($rowValuation->dblRateYear1,2, '.', ',')."

								</td> -->
								<td align='right' style='text-align:right;'>
								<input type='text' name='dblCustomValuationRate[$rowValuation->QuoteItemID]' value='R".number_format($strValuationServiceRateOngoing,2, '.', ',')."'>
								
									
								</td>
							</tr>";
			}else{

				$strAdditionalServicesValuationContent .= "
						<tr bgcolor='#fff'>
							<td>
								".$rowValuation->strService."

							</td>
							<td>Fees per Practice</td>
							<!--<td align='right' style='text-align:right;'>R".number_format($rowValuation->dblRateYear1,2, '.', ',')."

							</td> -->
							<td align='right' style='text-align:right;'>R".number_format($strValuationServiceRateOngoing,2, '.', ',')."
								
							</td>
						</tr>";
			}


	}

	$intAdditionalServicesY1 = $strIBCServiceRateYear1+$strAssetMapPlannerServiceRateYear1+$strAssetMapAdminServiceRateYear1+$strValuationServiceRateYear1;


	$intAdditionalServicesOngoing = $strIBCServiceRateMaintenance+$strAssetMapPlannerServiceRateMaintenance+$strAssetMapAdminServiceRateMaintenance+$strValuationServiceRateOngoing;
		$strAddionalServicesContentTotal = "<tr>
						<td colspan='2' align='right'>
							<b>Total Additional Services</b>
						</td>
						<!-- <td align='right' style='text-align:right;'>
						<b>R".number_format($intAdditionalServicesY1,2, '.', ',')."</b>
						</td> -->
						<td align='right' style='text-align:right;'>
							<b>R".number_format($intAdditionalServicesOngoing,2, '.', ',')."</b>
						</td>
					</tr>";

		if($strAssetMapAdminService || $strAssetMapPlannerService || $strIBCService || isset($arrServiceValuation)){
			$AdditionalServicesTable = "<div>
							<table cellpadding=2 cellspacing=1 border=1 width='100%' style='width:100%;margin:0px;border-collapse:collapse;margin-bottom: 4px;'>
								<tr bgcolor='#8E2C48'>
									<th style='text-align:left;background-color:#8E2C48;' align=left ><span style='color:white;'>Additional Services</span></th>
									<th width='100px' style='width:100px; text-align:center;background-color:#8E2C48;'><span style='color:white;'>Details</span></th>
									<!-- <th width='100px' style='width:100px; text-align:center;'>Once off</th> -->
									<th width='100px' style='width:100px; text-align:center;background-color:#8E2C48;'><span style='color:white;'>Monthly cost</span></th>
								</tr>
								<tr><td colspan=3><span style='color:#000000;'></span></td></tr>
								$strAdditionalServicesContent
								$strAdditionalServicesValuationContent
								$strAddionalServicesContentTotal
							</table>";
		}
		

//********************Summary of fees table**************

if($rowQuote->strPartnerType != "Strategic Partner (Acsis Legacy only)"){
	$trAdditionalServices = "					<tr>
						<td colspan='2' align='right'>
							Additional Services
						</td>
						<td align='right' style='text-align:right;'>R".
							number_format($intAdditionalServicesY1,2, '.', ',')."
						</td>
						<td align='right' style='text-align:right;'>R".
						number_format($intAdditionalServicesOngoing,2, '.', ',')."
							
						</td>
					</tr>";
}
		$strFeeSummaryContentTotal = "<tr bgcolor='#fff'>
						<td colspan='2' width='454px' align='right'>
							Basic Services
						</td>
						<td align='right' style='text-align:right;'>
							R".number_format($dblTotalRateYear1,2, '.', ',')."
						</td>
						<td align='right' style='text-align:right;'>
							R".number_format($dblTotalRateMaintenance,2, '.', ',')."
						</td>
					</tr>
					<tr>
						<td colspan='2' align='right'>
							<b>Total Fee payable (including ".($VAT*100)."&#37; VAT)</b>
						</td>
						<td align='right' style='text-align:right;'>
							<b>R".
							number_format($strTotalPayableAmountY1,2, '.', ',')."</b>
						</td>
						<td align='right' style='text-align:right;'>
							<b>R".
						number_format($strTotalPayableAmountOngoing,2, '.', ',')."</b>
						</td>
					</tr>
					<tr></tr>
					<tr>
						<td colspan='2' align='right'>
							Monthly Debit Order Amount
						</td>
						<td align='right' style='text-align:right;'>R".number_format($strMonthlyDebitAmountY1,2, '.', ',')."
						</td>
						<td align='right' style='text-align:right;'>
						R".number_format($strMonthlyDebitAmountOngoing,2, '.', ',')."
							
						</td>
					</tr>
					<tr>
						<td colspan='2' align='right'>
							Average monthly fee Per Planner
						</td>
						<td align='right' style='text-align:right;'>R".number_format( $strAverageMonthlyPerPlannerY1 ,2, '.', ',')."
						</td>
						<td align='right' style='text-align:right;'>R".number_format($strAverageMonthlyPerPlannerOngoing,2, '.', ',')."
						</td>
					</tr>";

		$FeeSummaryTable = "<div>
							<table cellpadding=2 cellspacing=1 border=1 width='100%' style='width:100%;margin:0px;border-collapse:collapse;margin-bottom: 4px;'>
								<tr bgcolor='#d3d3d3'>
									<th colspan='4' style='text-align:center;' align=center >Summary of Fees</th>
								</tr>
								$strFeeSummaryContentTotal
							</table>";

		//*************************************************************************************************
		//****************************          OUTPUT CONTENT           **********************************
		//*************************************************************************************************
		$dtAgreementStartDate = ($rowQuote->dtAgreementStartDate == "" ? date("Y-m-d"): $rowQuote->dtAgreementStartDate);
		$strContent = "
						<div>
							<table cellpadding=2 cellspacing=1 border=1 width='100%' style='width:100%;margin:0px;border-collapse:collapse;margin-bottom: 4px;'>
								<caption>Fee Summary</caption>
								<tr bgcolor='#8E2C48'>
									<th  style='text-align:left;background-color:#8E2C48;' align=left ><span style='color:white;'>Basic Services</span></th>
									<th width='100px' style='width:100px; text-align:center;background-color:#8E2C48;'><span style='color:white;'>Details</span></th>
									<th width='100px' style='width:100px; text-align:center;background-color:#8E2C48;'><span style='color:white;'>Fees Year 1</span></th>
									<th width='100px' style='width:100px; text-align:center;background-color:#8E2C48;'><span style='color:white;'>Fees Ongoing</span></th>
								</tr>
								<tr><td colspan=4><span style='color:#000000;'></span></td></tr>
								$strContentDetail
								$strContentTotals
							</table>
							$AdditionalServicesTable $BR<p>*All pricing includes VAT &#64;".($VAT*100)."&#37; except for the Asset Map licence fee (if selected) Year 1 (R ".number_format($strTotalPayableY1VAT,2, '.', ',').") Ongoing (R ".number_format($strTotalPayableOngoingVAT,2, '.', ',').").			
							</p>
							<p>
							*Your monthly debit order will be adjusted to recover the costs for the additional services. 
							</p>";


if($rowQuote->strPartnerType != "Strategic Partner (Acsis Legacy only)" && $strIBCService){
	$strContent .= "
							<p>*The Integrated Behavioural Coaching Course has a duration of twelve months only. Your debit order will be adjusted once the full R10,000 cost per planner has been recovered.  
							</p>
						"; //&#37 = %; &#64;= @
	}

if($strAssetMapAdminService || $strAssetMapPlannerService){
	$strContent .=	"
							<p>*Asset Map licence fee is a reduced fee that we have negotiated on behalf of our partners. The provider, Work that Matters is not registered for VAT and all fees recovered wil be paid over to them for your licence. Should you wish to cancel your licence please inform us before the 20th of the month to adjust your debit order timeously.
							</p>
						"; //&#37 = %; &#64;= @
}
if($strValuationServiceRateYear1 != ""){
	$strContent .=	"
							<p>*The Valuation Service has a cost of R8000 per client book being valued. Your debit order will be adjusted once the full R8,000 has been recovered. 
							</p>
						"; //&#37 = %; &#64;= @
}
$strContent .= "</div>";


		if($XplanSelected == "true"){
			return $strContent;
		}elseif ($XplanSelected == "false" && $strXPlanSummary != "") {
			return "";
		}else{
			return $strContent;
		}
		
	}

	public static function generateQuoteFinancialPlanningContentHTML($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		//Preload array   *****************************************************************
		$rowQuote = $xdb->getRowSQL("SELECT * FROM slaQuote WHERE QuoteID = '$QuoteID'");
		$intPriceIncreaseMultiply = 1;
		if(strtotime($rowQuote->dtAgreementStartDate) >= strtotime("2020-07-01")){
				$intPriceIncreaseMultiply = 1.05; //5% incre
		}

		$rowServiceIBC = $xdb->getRowSQL("SELECT ServiceID, strType, (dblCostYear1) AS dblRateYear1, '0' AS dblRateMaintenance, strService  FROM slaService WHERE blnIBC = 1", 0); //20181126 - IBC Course - pj
		$rowServiceMapAssetAdmin = $xdb->getRowSQL("SELECT ServiceID, strType, (dblCostYear1) AS dblRateYear1, (dblCostMaintenance) AS dblRateMaintenance, strService  FROM slaService WHERE blnAssetMapAdmin = 1", 0);
		$rowServiceMapAssetPlanner = $xdb->getRowSQL("SELECT ServiceID, strType, (dblCostYear1) AS dblRateYear1, (dblCostMaintenance) AS dblRateMaintenance, strService FROM slaService WHERE blnAssetMapPlanner = 1 ", 0); 

		$rstFP = $xdb->doQuery("
			SELECT slaQuoteItem.intAssetMapAdmin,intIBC, intAssetMapPlanner, slaQuoteItem.QuoteItemID,slaQuoteItem.strRateType,slaQuoteItem.strPlannerID,(slaQuoteItem.dblRateYear1*$intPriceIncreaseMultiply) AS dblRateYear1,(slaQuoteItem.dblRateMaintenance*$intPriceIncreaseMultiply) AS dblRateMaintenance,slaQuoteItem.strPlannerName, slaService.strService
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Financial Planner Service')
			ORDER BY slaQuoteItem.strPlannerName",0);
		while($rowFP = $xdb->fetch_object($rstFP))
		{

			$arrServiceFPS[$rowFP->QuoteItemID] = $rowFP;
			if($rowFP->intIBC == 1){
				// print_rr($rowFP);
				$arrServiceFPS[$rowFP->strPlannerName] = $rowServiceIBC;
				$arrServiceFPS[$rowFP->strPlannerName]->strPlannerName = $rowFP->strPlannerName;
			}

			if($rowFP->intAssetMapPlanner == 1){
				$arrServiceFPS[$rowServiceMapAssetPlanner->ServiceID] = $rowServiceMapAssetPlanner;
				$arrServiceFPS[$rowServiceMapAssetPlanner->ServiceID]->strPlannerName = $rowFP->strPlannerName;

			}
			if($rowFP->intAssetMapAdmin == 1){
				$arrServiceFPS[$rowServiceMapAssetAdmin->ServiceID] = $rowServiceMapAssetAdmin;
				$arrServiceFPS[$rowServiceMapAssetAdmin->ServiceID]->strPlannerName = $rowFP->strPlannerName;
			}

		}
		// print_rr($arrServiceFPS);


		if(!$arrServiceFPS){
			$rstFP = $xdb->doQuery("
				SELECT slaQuoteItem.intAssetMapAdmin,intIBC, intAssetMapPlanner, slaQuoteItem.QuoteItemID,slaQuoteItem.strRateType,slaQuoteItem.strPlannerID,(slaQuoteItem.dblRateYear1*$intPriceIncreaseMultiply) AS dblRateYear1,(slaQuoteItem.dblRateMaintenance*$intPriceIncreaseMultiply) AS dblRateMaintenance,slaQuoteItem.strPlannerName
				FROM slaQuoteItem 
				WHERE refQuoteID=".$xdb->qs($QuoteID)." AND refServiceID = 0
				ORDER BY slaQuoteItem.strPlannerName",0);
			while($rowFP = $xdb->fetch_object($rstFP))
			{

				// $arrServiceFPS[$rowFP->QuoteItemID] = $rowFP;
				if($rowFP->intIBC == 1){
					// print_rr($rowFP);
					$arrServiceFPS[$rowFP->strPlannerName] = $rowServiceIBC;
					$arrServiceFPS[$rowFP->strPlannerName]->strPlannerName = $rowFP->strPlannerName;
				}

				if($rowFP->intAssetMapPlanner == 1){
					$arrServiceFPS[$rowServiceMapAssetPlanner->ServiceID] = $rowServiceMapAssetPlanner;
					$arrServiceFPS[$rowServiceMapAssetPlanner->ServiceID]->strPlannerName = $rowFP->strPlannerName;

				}
				if($rowFP->intAssetMapAdmin == 1){
					$arrServiceFPS[$rowServiceMapAssetAdmin->ServiceID] = $rowServiceMapAssetAdmin;
					$arrServiceFPS[$rowServiceMapAssetAdmin->ServiceID]->strPlannerName = $rowFP->strPlannerName;
				}

			}

		}

		//go
		$dblSubTotalRateYear1 = 0;
		$dblSubTotalRateMaintenance = 0;

		if(count($arrServiceFPS) == 0)
		{
			$arrServiceFPS[0] = "";
		}

		// print_rr($arrServiceFPS);

		$strContentDetail = "";
		foreach ($arrServiceFPS AS $QuoteItemID => $rowQuoteItem)
		{

			$strPlannerName = $rowQuoteItem->strPlannerName;
			$strServiceDetail = ucwords($rowQuoteItem->strService);
			$strPlannerID = $rowQuoteItem->strPlannerID;

			if((strpos($strServiceDetail, 'Integrated Behavioural Coaching Course') !== false))
			{
				$strServiceDetail =str_replace("(Cape Town): R10,000", "",$strServiceDetail);
			}

			$strRateYear1 = number_format($rowQuoteItem->dblRateYear1,2, '.', ',');

			if((strpos($strServiceDetail, 'Asset Map') !== false))
			{
				$strRateMaintenance = number_format($rowQuoteItem->dblRateYear1,2, '.', ',');

			}else{

				$strRateMaintenance = number_format($rowQuoteItem->dblRateMaintenance,2, '.', ',');
			}
			

			if($QuoteItemID == 0 && !is_string($QuoteItemID))
			{
				$strPlannerName = "n/a";
				$strServiceDetail = "n/a";
				$strPlannerID = "n/a";
				$strRateYear1 = "0";
				$strRateMaintenance = "0";
			}


			$strContentDetail .= "
					<tr>
						<td>
							$strPlannerName
						</td>
						<td>
							$strServiceDetail
						</td>
						<td align='right' style='text-align:right;'>
							R$strRateYear1
						</td>
						<td align='right' style='text-align:right;'>
							R$strRateMaintenance
						</td>";

			$dblSubTotalRateYear1 += $rowQuoteItem->dblRateYear1;
			if((strpos($strServiceDetail, 'Asset Map') !== false))
			{
				$dblSubTotalRateMaintenance += $rowQuoteItem->dblRateYear1;
			}else{
				$dblSubTotalRateMaintenance += $rowQuoteItem->dblRateMaintenance;
			}
			
		}

		$strContentTotals =  "
								<tr>
									<td align='right' colspan='4' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
								</tr>
								<tr>
									<th align='right' colspan='2' style='text-align:right;border-top:1px solid black;'>Total</th>
									<th align='right' style='text-align:right;border-top:1px solid black;'>R
										 ".number_format($dblSubTotalRateYear1,2, '.', ',')."
									</th>
									<th align='right' style='text-align:right;border-top:1px solid black;'>R
										 ".number_format($dblSubTotalRateMaintenance,2, '.', ',')."
									</th>
								</tr>
								";


		//*************************************************************************************************
		//****************************          OUTPUT CONTENT           **********************************
		//*************************************************************************************************


		$strContent = "
						<span>
							<table cellpadding=2 cellspacing=1 border=1 width='100%' style='width:100%;margin:0px;border-collapse:collapse;margin-bottom: 4px;'>
								<tr bgcolor='#8E2C48'>

									<th width='200px' align='left' style='width:200px; text-align:left;'><span style='color:white;'>Planner Name</span></th>
									<th align='left' style='text-align:left;color:white;'><span style='color:white;'>Service Option</span></th>
									<th width='100px' align='left' style='width:100px; text-align:left;color:white;'><span style='color:white;'>Year 1</span></th>
									<th width='100px' align='left' style='width:100px; text-align:left;color:white;'><span style='color:white;'>Ongoing</span></th>
								</tr>

								<tr bgcolor='#ffffff'><td colspan='4'><span style='color:#000000;'></span></td></tr>
								$strContentDetail
								$strContentTotals
							</table>
						</span>"; //&#37 = %; &#64;= @


		return $strContent;
	}

	public static function generateQuoteBMSContentHTML($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		//Preload array   *****************************************************************
		$rowQuote = $xdb->getRowSQL("SELECT * FROM slaQuote WHERE QuoteID = '$QuoteID'");
		$intPriceIncreaseMultiply = 1;
		if(strtotime($rowQuote->dtAgreementStartDate) >= strtotime("2020-07-01")){
				$intPriceIncreaseMultiply = 1.05; //5% incre
		}

		$rstBMS = $xdb->doQuery("
			SELECT slaQuoteItem.QuoteItemID,slaQuoteItem.strRateType,(slaQuoteItem.dblRateYear1*$intPriceIncreaseMultiply) AS dblRateYear1,(slaQuoteItem.dblRateMaintenance*$intPriceIncreaseMultiply) AS dblRateMaintenance, slaService.strService
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Business Management Service' AND slaService.ServiceID != 8 )
			GROUP BY QuoteItemID, refQuoteID
			ORDER BY intDisplayOrder
			",0);

		while($rowBMS = $xdb->fetch_object($rstBMS))
		{
			$arrServiceBMS[$rowBMS->QuoteItemID] = $rowBMS;
		}

		//go
		$dblSubTotalRateYear1 = 0;
		$dblSubTotalRateMaintenance = 0;

		if(count($arrServiceBMS) == 0)
		{
			$arrServiceBMS[0] = "";
			return "";
		}

		$strContentDetail = "";
		foreach ($arrServiceBMS AS $QuoteItemID => $rowQuoteItem)
		{
			$strServiceDetail = $rowQuoteItem->strService;
			// switch($rowQuoteItem->strRateType)
			// {
			//    case "Year 1";
			//       $strRateYear1 = number_format($rowQuoteItem->dblRate,0, '.', ',');
			//       $strRateMaintenance = "";
			//    break;
			//    case "Maintenance":
			//       $strRateYear1 = "";
			//       $strRateMaintenance = number_format($rowQuoteItem->dblRate,0, '.', ',');
			//    break;
			// }
			$strRateYear1 = number_format($rowQuoteItem->dblRateYear1,2, '.', ',');
			$strRateMaintenance = number_format($rowQuoteItem->dblRateMaintenance,2, '.', ',');

			if($QuoteItemID == 0)
			{
				$strServiceDetail = "n/a";
				$strRateYear1 = "0";
				$strRateMaintenance = "0";
			}
			$strContentDetail .= "
					<tr>
						<td>
							$strServiceDetail
						</td>
						<td align='right' style='text-align:right;'>
							R$strRateYear1
						</td>
						<td align='right' style='text-align:right;'>
							R$strRateMaintenance
						</td>";

			$dblSubTotalRateYear1 += $rowQuoteItem->dblRateYear1;
			$dblSubTotalRateMaintenance += $rowQuoteItem->dblRateMaintenance;
		}


		$strContentTotals =  "
								<tr>
									<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
									<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
									<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
								</tr>
								<tr>
									<th align='right' style='text-align:right;border-top:1px solid black;'>Total</th>
									<th align='right' style='text-align:right;border-top:1px solid black;'>
										 R".number_format($dblSubTotalRateYear1,2, '.', ',')."
									</th>
									<th align='right' style='text-align:right;border-top:1px solid black;'>
										 R".number_format($dblSubTotalRateMaintenance,2, '.', ',')."
									</th>
								</tr>
								";


		//*************************************************************************************************
		//****************************          OUTPUT CONTENT           **********************************
		//*************************************************************************************************


		$strContent = "
						<span>
							<table cellpadding=2 cellspacing=1 border=1 width='100%' style='width:100%;margin:0px;border-collapse:collapse;margin-bottom: 4px;'>
								<tr bgcolor='#8E2C48'>
									<th align='left' style='text-align:left;'><span style='color:#ffffff;'>Service Option</span></th>
									<th width='100px' align='left' style='width:100px; text-align:left;'><span style='color:#ffffff;'>Year 1</span></th>
									<th width='100px' align='left' style='width:100px; text-align:left;'><span style='color:#ffffff;'>Ongoing</span></th>
								</tr>
								<tr bgcolor='#ffffff'><td colspan='3'><span style='color:#000000;'></span></td></tr>
								$strContentDetail
								$strContentTotals
							</table>
						</span>"; //&#37 = %; &#64;= @


		return $strContent;
	}

	public static function generateQuoteXPlanContentHTML($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		//Preload array   *****************************************************************
		$rowQuote = $xdb->getRowSQL("SELECT * FROM slaQuote WHERE QuoteID = '$QuoteID'");
		$intPriceIncreaseMultiply = 1;
		if(strtotime($rowQuote->dtAgreementStartDate) >= strtotime("2020-07-01")){
				$intPriceIncreaseMultiply = 1.05; //5% incre
		}
		//select Xplan BMS (ID = 8)
		$rstXPlan = $xdb->doQuery("
			SELECT slaQuoteItem.QuoteItemID,slaQuoteItem.strRateType,(slaQuoteItem.dblRateYear1*$intPriceIncreaseMultiply) AS dblRateYear1,(slaQuoteItem.dblRateMaintenance*$intPriceIncreaseMultiply) AS dblRateMaintenance, slaService.strService
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Business Management Service' AND slaService.ServiceID = 8 )
			ORDER BY intDisplayOrder",0);
		while($rowXPlan = $xdb->fetch_object($rstXPlan))
		{
			$arrServiceXPlan[$rowXPlan->QuoteItemID] = $rowXPlan;
		}

		//go
		$dblSubTotalRateYear1 = 0;
		$dblSubTotalRateMaintenance = 0;

		if(count($arrServiceXPlan) == 0)
		{
			$arrServiceXPlan[0] = "";
		}

		$strContentDetail = "";
		foreach ($arrServiceXPlan AS $QuoteItemID => $rowQuoteItem)
		{
			$strServiceDetail = $rowQuoteItem->strService;
			// switch($rowQuoteItem->strRateType)
			// {
			//    case "Year 1";
			//       $strRateYear1 = number_format($rowQuoteItem->dblRate,2, '.', ',');
			//       $strRateMaintenance = "";
			//    break;
			//    case "Maintenance":
			//       $strRateYear1 = "";
			//       $strRateMaintenance = number_format($rowQuoteItem->dblRate,2, '.', ',');
			//    break;
			// }
			$strRateYear1 = number_format($rowQuoteItem->dblRateYear1,2, '.', ',');
			$strRateMaintenance = number_format($rowQuoteItem->dblRateMaintenance,2, '.', ',');

			if($QuoteItemID == 0)
			{
				$strServiceDetail = "n/a";
				$strRateYear1 = "0";
				$strRateMaintenance = "0";
			}
			$strContentDetail .= "
					<tr>
						<td>
							$strServiceDetail
						</td>
						<td align='right' style='text-align:right;'>
							$strRateYear1
						</td>
						<td align='right' style='text-align:right;'>
							$strRateMaintenance
						</td>";

			$dblSubTotalRateYear1 += $rowQuoteItem->dblRateYear1;
			$dblSubTotalRateMaintenance += $rowQuoteItem->dblRateMaintenance;
		}


		$strContentTotals =  "
								<tr>
									<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
									<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
									<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
								</tr>
								<tr>
									<th align='right' style='text-align:right;border-top:1px solid black;'>Total</th>
									<th align='right' style='text-align:right;border-top:1px solid black;'>
										 ".number_format($dblSubTotalRateYear1,2, '.', ',')."
									</th>
									<th align='right' style='text-align:right;border-top:1px solid black;'>
										 ".number_format($dblSubTotalRateMaintenance,2, '.', ',')."
									</th>
								</tr>
								";


		//*************************************************************************************************
		//****************************          OUTPUT CONTENT           **********************************
		//*************************************************************************************************


		$strContent = "
						<span>
							<table cellpadding=2 cellspacing=1 border=1 width='100%' style='width:100%;margin:0px;border-collapse:collapse;margin-bottom: 4px;'>
								<tr bgcolor='#8E2C48'>
									<th align='left' style='text-align:center;'><span style='color:#ffffff;'>Service Option</span></th>
									<th width='100px' align='left' style='width:100px; text-align:center;'><span style='color:#ffffff;'>Year 1</span></th>
									<th width='100px' align='left' style='width:100px; text-align:center;'><span style='color:#ffffff;'>Ongoing</span></th>
								</tr>
								<tr bgcolor='#ffffff'><td colspan='3'><span style='color:#000000;'></span></td></tr>
								$strContentDetail
								$strContentTotals
							</table>
						</span>"; //&#37 = %; &#64;= @


		return $strContent;
	}

	public static function generateQuoteAdditionalLicensesContentHTML($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		//Preload array   *****************************************************************
		$rowQuote = $xdb->getRowSQL("SELECT * FROM slaQuote WHERE QuoteID = '$QuoteID'");
		$intPriceIncreaseMultiply = 1;
		if(strtotime($rowQuote->dtAgreementStartDate) >= strtotime("2020-07-01")){
				$intPriceIncreaseMultiply = 1.05; //5% incre
		}

		$arrService = array();
		$rstService = $xdb->doQuery("SELECT * FROM slaService WHERE slaService.strType='Additional License' ORDER BY intDisplayOrder,strService DESC",0);

		while($rowService = $xdb->fetch_object($rstService))
		{
			$arrService[$rowService->ServiceID] = $rowService;
		}
		//print_rr($arrService); //die;

		//go
		$rstQI = $xdb->doQuery("
			SELECT `intRowGroup`,`refServiceID`,QuoteItemID, slaQuoteItem.strPlannerName
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Additional License')
			ORDER BY strPlannerName, intRowGroup,ServiceID",0);
		//preload
		$intRowGroup = $intUniqueID;
		while($rowQI = $xdb->fetch_object($rstQI))
		{
			$arrServiceGroup[$rowQI->intRowGroup][$rowQI->refServiceID] = $rowQI->QuoteItemID;
		}

		$intCounter = 0;
		foreach($arrServiceGroup AS $intRowGroup => $rowQuoteService)
		{
			$trContentInner = "";
			$intCounter++;

			foreach($arrService AS $ServiceID => $rowService)
			{
				//$QuoteItemID = $intUniqueID;
				if(isset($rowQuoteService[$ServiceID]))
				{
					$row = $xdb->getRowSQL("
					SELECT slaQuoteItem.*
					FROM slaQuoteItem
					WHERE QuoteItemID=".$rowQuoteService[$ServiceID],0);

					$strPlannerName = $row->strPlannerName;

					$trContentInner .= "
							<td align='center'>
								<span style='color:#018671;'>Yes</span>
							</td>";

					${"dblTotalCostMaintenance".$ServiceID} += ($row->dblRateMaintenance*$intPriceIncreaseMultiply) ;
				}
				else
				{
					$trContentInner .= "
					<td align='center'>
						<span style='color:black;'>No</span>
					</td>";
				}
			}
			$trContent .= "
			<tr>
				<td><span style='color:black;'>$strPlannerName</span></td>
				$trContentInner
			</tr>";
		}

		//build heading
		$tdHeading = "";
		foreach ($arrService AS $ServiceID => $rowService)
		{
			//print_rr($rowService);
			$tdHeading .= "
			<th width='140px' align='left' style='text-align:left;'>
				".$rowService->strService." (R".number_format($rowService->dblCostYear1*$intPriceIncreaseMultiply,2, '.', ',')." per License)
			</th>";

			if(count($arrServiceGroup) == 0)
			{
				//leave 0 on a new line as the pdf engine has issues reading it next to the tags on one line -christiaan
				$tdTotalDetailInner .="<th align='right'>
					0
				</th>";
				$trContentBlankInner .= "
					<td align='right'>
						0
					</td>";
			}
			else
			{
				$tdTotalDetailInner .="<th align='right'><span style='color:black;'>".(number_format(${"dblTotalCostMaintenance".$ServiceID},2, '.', ','))."</span></th>";
			}
		}

		if(count($arrServiceGroup) == 0)
		{
			$trContent .= "
			<tr>
				<td><span style='color:black;'>n/a</span></td>
				$trContentBlankInner
			</tr>";
		}

		$trTotal = "
					<tr>
						<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
						<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
						<td align='right' style='border-top:2px solid black;height:1px;margin:0;padding:0;'></td>
					</tr>
					<tr>
						<th align='right' style='text-align:right;border-top:1px solid black;'><span style='color:black;'>Totals</span></th>
						$tdTotalDetailInner
					</tr>";

		if(count($arrServiceGroup) != 0){
			return "
				<span>
					<table cellpadding=2 cellspacing=1 border=1 width='100%' style='width:100%;margin:0px;border-collapse:collapse;margin-bottom: 4px;'>
						<tr>
							<th align='left' style='text-align:left;'><span style='color:black;'>Name</span></th>
							$tdHeading
						</tr>
						$trContent
						$trTotal
					</table>
				</span>";

			}else{
				return "";
			}
	}

	//dont delete this method unless we are sure that we cant use it later.
	//This method creates an alternative style of list using a table instead of <li>
	// Yes! It actually works. Its not a complete hack, it looks decent. - Christiaan
	public static function generateQuoteFinancialPlanningTermsHTML($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		//20181126 - IBC Course - pj
		$blnIBC = false;
		$blnAssetMapAdmin = false;
		$blnAssetMapPlanner = false;
		$rowServiceIBC = $xdb->getRowSQL("SELECT * FROM slaService WHERE blnIBC = 1", 0); //20181126 - IBC Course - pj
		$rowServiceMapAsset = $xdb->getRowSQL("SELECT * FROM slaService WHERE blnAssetMapAdmin = 1 OR blnAssetMapPlanner = 1 LIMIT 1", 0); 

		//Preload array   *****************************************************************
		$rstFP = $xdb->doQuery("
			SELECT slaQuoteItem.*, slaService.*
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Financial Planner Service')
			ORDER BY slaService.intDisplayOrder", 0); //die("ksdffno");

		while($rowFP = $xdb->fetch_object($rstFP))
		{
			$arrServiceFPS[$rowFP->ServiceID] = $rowFP;
			if($rowFP->intIBC == 1){
				$blnIBC = true;
			}
			if($rowFP->intAssetMapAdmin == 1){
				$blnAssetMapAdmin = true;
			}
			if($rowFP->intAssetMapPlanner == 1){
				$blnAssetMapPlanner = true;
			}
		}

		if (!$arrServiceFPS) {
			$rstFP = $xdb->doQuery("
				SELECT slaQuoteItem.*
				FROM slaQuoteItem 
				WHERE refQuoteID=".$xdb->qs($QuoteID)." AND refServiceID = 0
				", 0); //die("ksdffno");

			while($rowFP = $xdb->fetch_object($rstFP))
			{
				$arrServiceFPS[$rowFP->ServiceID] = $rowFP;
				if($rowFP->intIBC == 1){
					$blnIBC = true;
				}
				if($rowFP->intAssetMapAdmin == 1){
					$blnAssetMapAdmin = true;
				}
				if($rowFP->intAssetMapPlanner == 1){
					$blnAssetMapPlanner = true;
				}
			}
	    }

		if($blnIBC){
			$arrServiceFPS[$rowServiceIBC->ServiceID] = $rowServiceIBC;
		}

		if($blnAssetMapPlanner || $blnAssetMapAdmin){
			
			$arrServiceFPS[$rowServiceMapAsset->ServiceID] = $rowServiceMapAsset;

		}

//print_rr($arrServiceFPS); die("lsjkdfjnd");
		//go
		if(count($arrServiceFPS) == 0)
		{
			return "";
		}

		$strContentDetail = "";
		foreach ($arrServiceFPS AS $ServiceID => $rowQuoteItem)
		{
			$strTermItems = str_replace("</li>", "", $rowQuoteItem->txtReportTerms);
			$strTermItems = str_replace("<ul>", "", $strTermItems);
			$strTermItems = str_replace("</ul>", "", $strTermItems);

			$arrTermItems = explode("<li>", $strTermItems);

			//20181126 - Only unset if array value is null, otherwise some of the terms are lost - Rachel
			//unset($arrTermItems[0]);
			if(ctype_space($arrTermItems[0])){
				unset($arrTermItems[0]);
			}

			$strContentDetailInner = "";
			foreach($arrTermItems AS $ID => $strReportTermItem)
			{
				//20181206 - $arrTermItems[0] is always a paragraph, make an exception not to add a bullet and do not indent - Rachel
				if($ID != 0){
					$strContentDetailInner .= "
						<tr>
							<td width='15px' VALIGN='top' style='vertical-align:top;'>". htmlentities("•")."</td>
							<td align='left'>".mynl2br($strReportTermItem)."</td>
						</tr>";

				}else{


					$strContentDetailInner .= "
					</table>
					". mynl2br($strReportTermItem)."
					<table width='100%' style='width:100%;'>";

				}				

			}

// $blnIBC

			if(strpos($rowQuoteItem->strService, "Asset Map") !== false)
			{
				$strContentDetail .= "<b>".str_replace(": ADMIN LICENCE FEE", "",  str_replace(': PLANNER LICENCE FEE', "", strtoupper("ASSET MAP LICENCE")))."</b>
								<table width='100%' style='width:100%;margin-top:0;padding-top:0;top:0;'>
									</tr> 
									$strContentDetailInner
								</table>";
			}else{

				$strContentDetail .= "<div style='margin-top:0;padding-top:0;bottom:0;'><b>".str_replace(": ADMIN LICENCE FEE", "",  str_replace(': PLANNER LICENCE FEE', "", strtoupper(mynl2br($rowQuoteItem->strService))))."</b></div>
								<table width='100%' style='width:100%;margin-top:0;padding-top:0;top:0;'>
									</tr> 
									$strContentDetailInner
								</table>";
			}
		}


		$strContentDetailInner = "";
		$row = $xdb->getRowSQL("
			SELECT slaService.ServiceID,slaService.strService,slaService.txtReportTerms
			FROM slaService
			WHERE ServiceID=-1",0);

		$strTermItems = str_replace("</li>", "", $row->txtReportTerms);
		$strTermItems = str_replace("<ul>", "", $strTermItems);
		$strTermItems = str_replace("</ul>", "", $strTermItems);

		$arrTermItems = explode("<li>", $strTermItems);
		 unset($arrTermItems[0]);

		foreach($arrTermItems AS $ID => $strReportTermItem)
		{
			$strContentDetailInner .= "
				<tr>
					<td width='15px' VALIGN='top' style='vertical-align:top;'>". htmlentities("•")."</td>
					<td align='left'>".mynl2br($strReportTermItem)."</td>
				</tr>";
		}

		$strContentDetail .= "<b>".strtoupper(mynl2br($row->strService))."</b>
		<table width='100%' style='width:100%;'>
			</tr>
			$strContentDetailInner
		</table>";

		//OUTPUT CONTENT
		$strContent = "$strContentDetail";
		return $strContent;
	}

	//generate terms using LI instead of a table
	public function xgenerateQuoteFinancialPlanningTermsHTML($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		//Preload array   *****************************************************************
		$rstFP = $xdb->doQuery("
			SELECT slaQuoteItem.QuoteItemID, slaService.ServiceID,slaService.strService,slaService.txtReportTerms
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Financial Planner Service')
			ORDER BY slaService.intDisplayOrder",0);

		while($rowFP = $xdb->fetch_object($rstFP))
		{
			$arrServiceFPS[$rowFP->ServiceID] = $rowFP;
		}

		//go
		if(count($arrServiceFPS) == 0)
		{
			return "";
		}

		$strContentDetail = "";
		foreach ($arrServiceFPS AS $ServiceID => $rowQuoteItem)
		{
			$strContentDetail .= "
				<label>
					<b>".mynl2br($rowQuoteItem->strService)."</b>
				</label>
					".mynl2br($rowQuoteItem->txtReportTerms);
		}

		$strContentDetailInner = "";
		$row = $xdb->getRowSQL("
			SELECT slaService.ServiceID,slaService.strService,slaService.txtReportTerms
			FROM slaService
			WHERE ServiceID=-1",0);

		$strContentDetail .= "
			<label>
				<b>".mynl2br($row->strService)."</b>
			</label>
				".mynl2br($row->txtReportTerms);

		//OUTPUT CONTENT
		$strContent = "
					$strContentDetail";
		return $strContent;
	}


	public static function generateQuoteBMSTermsHTML($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		//Preload array   *****************************************************************
		$rstBMS = $xdb->doQuery("
			SELECT slaQuoteItem.QuoteItemID, slaService.ServiceID,slaService.strService,slaService.txtReportTerms
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Business Management Service' AND slaService.ServiceID != 8 )
			ORDER BY strPlannerName",0);

		while($rowBMS = $xdb->fetch_object($rstBMS))
		{
			$arrServiceBMS[$rowBMS->ServiceID] = $rowBMS;
		}

		//go
		if(count($arrServiceBMS) == 0)
		{
			return "";
		}

		$strContentDetail = "";
		foreach ($arrServiceBMS AS $ServiceID => $rowQuoteItem)
		{
			$strTermItems = str_replace("</li>", "", $rowQuoteItem->txtReportTerms);
			$strTermItems = str_replace("<ul>", "", $strTermItems);
			$strTermItems = str_replace("</ul>", "", $strTermItems);

			$arrTermItems = explode("<li>", $strTermItems);
			unset($arrTermItems[0]);
			$strContentDetailInner = "";
			foreach($arrTermItems AS $ID => $strReportTermItem)
			{
				$strContentDetailInner .= "
					<tr>
						<td width='15px' VALIGN='top' style='vertical-align:top;'>". htmlentities("•")."</td>
						<td align='left'>".mynl2br($strReportTermItem)."</td>
					</tr>";
			}

			$strContentDetail .= "<b>".strtoupper(mynl2br($rowQuoteItem->strService))."</b>
							<table width='100%' style='width:100%;'>
								</tr>
								$strContentDetailInner
							</table>";
		}

		//OUTPUT CONTENT
		$strContent = "$strContentDetail";

		return $strContent;
	}

	public static function generateQuoteXPlanTermsHTML($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		//Preload array   *****************************************************************
		$rstXPlan = $xdb->doQuery("
			SELECT slaQuoteItem.QuoteItemID, slaService.ServiceID,slaService.strService,slaService.txtReportTerms
			FROM slaQuoteItem INNER JOIN slaService on refServiceID = ServiceID
			WHERE refQuoteID=".$xdb->qs($QuoteID)." AND (slaService.strType='Business Management Service' AND slaService.ServiceID = 8)
			ORDER BY strPlannerName",0);

		while($rowXPlan = $xdb->fetch_object($rstXPlan))
		{
			$arrServiceXPlan[$rowXPlan->ServiceID] = $rowXPlan;
		}

		//go
		if(count($arrServiceXPlan) == 0)
		{
			return "";
		}

		$strContentDetail = "";
		foreach ($arrServiceXPlan AS $ServiceID => $rowQuoteItem)
		{
			$strTermItems = str_replace("</li>", "", $rowQuoteItem->txtReportTerms);
			$strTermItems = str_replace("<ul>", "", $strTermItems);
			$strTermItems = str_replace("</ul>", "", $strTermItems);

			$arrTermItems = explode("<li>", $strTermItems);
			unset($arrTermItems[0]);
			$strContentDetailInner = "";
			foreach($arrTermItems AS $ID => $strReportTermItem)
			{
				$strContentDetailInner .= "
					<tr>
						<td width='15px' VALIGN='top' style='vertical-align:top;'>". htmlentities("•")."</td>
						<td align='left'>".mynl2br($strReportTermItem)."</td>
					</tr>";
			}

			$strContentDetail .= "<b>".strtoupper(mynl2br($rowQuoteItem->strService))."</b>
							<table width='100%' style='width:100%;'>
								</tr>
								$strContentDetailInner
							</table>";
		}

		$strContentDetailInner = "";
		$row = $xdb->getRowSQL("
			SELECT slaService.ServiceID,slaService.strService,slaService.txtReportTerms
			FROM slaService
			WHERE ServiceID=-3",0);

		$strTermItems = str_replace("</li>", "", $row->txtReportTerms);
		$strTermItems = str_replace("<ul>", "", $strTermItems);
		$strTermItems = str_replace("</ul>", "", $strTermItems);

		$arrTermItems = explode("<li>", $strTermItems);
		unset($arrTermItems[0]);

		foreach($arrTermItems AS $ID => $strReportTermItem)
		{
			$strContentDetailInner .= "
				<tr>
					<td width='15px' VALIGN='top' style='vertical-align:top;'>". htmlentities("•")."</td>
					<td align='left'>".mynl2br($strReportTermItem)."</td>
				</tr>";
		}

		$strContentDetail .= "<b>".strtoupper(mynl2br($row->strService))."</b>
		<table width='100%' style='width:100%;'>
			</tr>
			$strContentDetailInner
		</table>";

		//OUTPUT CONTENT
		$strContent = "$strContentDetail";
		return $strContent;
	}


	public static function previewQuote($QuoteID)
	{
		return self::generateQuoteSummaryContentHTML($QuoteID,0,"");
	}

	public static function generateQuotePDF($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		$rowQuote = $xdb->getRowSQL("SELECT slaQuote.*, vieWPS.strWPS ,vieWPS.strEmail as 'strWPSEmail'
												FROM slaQuote INNER JOIN vieWPS on slaQuote.refWPSID = vieWPS.WPSID
												WHERE QuoteID = ".$xdb->qs($QuoteID), 0);

		include_once('./../htmltopdf/html2fpdf.php');
		include_once('./../htmltopdf/toc.php');
		include_once('./../htmltopdf/bookmark.php');

		$pdf = new HTML2FPDF();

		$pdf->startPageNums();

		$pdf->SetTopMargin(20);
		$pdf->AddPage();
		$pdf->_numPageNum = 1;//fixes issue with fotter numbers being wrong
		$pdf->FooterNumPages = 0; //fixes issue with page 2 not having a footer
		//$pdf->AliasNbPages();
		$pdf->SetAutoPageBreak(false);
		$pdf->setBlnFooterTextOnly(1);
		$pdf->setSystem("Proposal PDF");

		//constants to check if the page content is too large by adding a page break
		$height_of_cell = 60; // mm
		$page_height = 286.93; // mm (portrait letter)
		$page_max_height = $page_height - ($page_height/3);

		$strStatusText = "";
		//20160314 - Finalize depreciated as status is now ALWAYS proposal - Christiaan
		//switch($rowQuote->strStatus)
		//{
		//   case "Draft":
		//      $strStatusText = "$BR$BR"."DRAFT PROPOSAL";
		//       $strStatusTextFooter = "DRAFT PROPOSAL";
		//    break;
		//    case "Proposal":
		//       $strStatusText = "$BR$BR"."PROPOSAL";
		//       $strStatusTextFooter = "PROPOSAL";
		//    break;
		// }

		$pdf->bMargin = 10;
		$pdf->FooterText = "Annexure D: Partner Programme Customised Benefit Statement $strStatusTextFooter for ".$_SESSION['PN']." as at ".date("d F Y")."";

		$_SESSION['PN'] = $rowQuote->strPartner; //Practice Name used in html2fpdf for the footer generation: $this->FooterText for $_SESSION['PN'] as date("d F Y")

		// if(file_exists("./../tools/images/layers/CelestisBATpdfimage.jpg"))
		//    $pdf->Image("./../tools/images/layers/CelestisBATpdfimage.jpg",50,$pdf->GetY(),190);
		// if(file_exists("./images/SLA_PDF_Cover_Small.jpg"))
		// $pdf->Image("./images/SLA_PDF_Cover_Small.jpg",40,$pdf->GetY(),190);
		// if(file_exists("./images/SLA_PDF_Cover_Small_New1.jpg"))
		// $pdf->Image("./images/SLA_PDF_Cover_Small_New1.jpg",60,$pdf->GetY(),190);
		if(file_exists("./images/SLA_PDF_Cover_Small_New1.jpg"))
		$pdf->Image("./images/SLA_PDF_Cover_Small_New1.jpg",0,0,210);

		$pdf->fontsize = "24";
		$pdf->SetFont('Arial','',20);

		$strOutput = "$BR
					<span style='color:#000000;font-size:27px;'><b>ANNEXURE \"D\"$BR$BR</b>CUSTOMISED BENEFIT STATEMENT $strStatusText </span>
				  ";
		$pdf->WriteHTML($strOutput);

		// $pdf->fontsize = "14";
		// $pdf->SetFont('Arial','',14);

		// //$pdf = getPdfPreparedFor($pdf,$PracticeID, $this->BATVERSION);

		// //$pdf->WriteHTML($strOutput);
		$pdf->fontsize = "14";
		$pdf->SetFont('Arial','',14);

		 //20160314 - Finalize depreciated as status is now ALWAYS proposal - Christiaan
		$strVersion = "";
		if($rowQuote->strVersion != "")
		{
			$strVersion = "Version: $rowQuote->strVersion";
		}

		$strOutput = " $BR $BR
							<span width='100%'>
								<b><u></u></b>
							</span>";//$rowQuote->strQuote -  - $rowQuote->strStatus

		$pdf->WriteHTML($strOutput);

		$pdf->fontsize = "9";
		$pdf->SetFont('Arial','',9);

		//20181207 - Removed width from both tds TO accomodate longer emails - Rachel
		$strOutput = "$BR $BR
			<table width='100%' cellspacing='0' cellpadding='0'>
				<tr >
					<!-- 20181207 - Removed width from both tds TO accomodate longer emails - Rachel -->
					<td colspan='2' style='font-size:18px; font-weight:bold;'><span style='color:#018671;'><b>Prepared for:</b></span></td>
					<td colspan='2' style='font-size:18px; font-weight:bold;'><span style=''><b>Prepared by:</b></span></td>
				</tr>
				<tr>
					<td colspan='4' height='0px'></td>
				</tr>
				<tr>
					<td valign='top'>
						<b style='color:#000000;'>Name:</b>
					</td>
					<td valign='top'>
						".mynl2br($rowQuote->strPartner)."
					</td>
					<td valign='top' colspan='2'>
						<span style='color:#018671;'>Old Mutual Wealth Services Company (Pty) Ltd</span>
					</td>
				</tr>
				<tr>
					<td valign='top'>
						<b style='color:black;'>Contact:</b>
					</td>
					<td valign='top'>
						".mynl2br($rowQuote->strClient)."
					</td>
					<td valign='top'>
						<b>Reg No.</b>
					</td>
					<td valign='top'>
						2012/100073/07
					</td>
				</tr>
				<tr>
					<td valign='top'>
						<b>Email:</b>
					</td>
					<td valign='top'>
						".mynl2br($rowQuote->strEmail)."
					</td>
					<td valign='top'>
						<span style='font-size:18px;'><b>Prepared By:</b></span>
					</td>
					<td valign='top' margin='200px'>
						".mynl2br($rowQuote->strWPS)." 
					</td>
				</tr>
				<tr>
					<td valign='top'>
						<b>Tel:</b>
					</td>
					<td valign='top'>
						".mynl2br($rowQuote->strTel)."
					</td>
					<td valign='top'>
						<b>Email:</b>
					</td>
					<td valign='top'>
						 ".mynl2br($rowQuote->strWPSEmail)."
					</td>
				</tr>
				<tr>
					<td valign='top'>
						<b>Type:</b>
					</td>
					<td valign='top'>
						".mynl2br($rowQuote->strPartnerType)."
					</td>
					<td valign='top' colspan='2'>

					</td>
				</tr>
				<tr>
					<td valign='top'>
						<b>Date:</b>
					</td>
					<td valign='top'>
						".mynl2br(date("j F Y"))."
					</td>
					<td valign='top' colspan='2'>

					</td>
				</tr>
			</table>";

		$pdf->WriteHTML($strOutput);

		if (file_exists("./../images/layers/Footer.jpg"))
		{
			$pdf->Image("./../images/layers/Footer.jpg", 10, 270, 190);
		}

		if (file_exists("./images/Report_Banner_bottom.png"))
        {
            // $pdf->Image("./images/layers/Report_Banner_bottom.png", 30, 257, 60);
            $pdf->Image("./images/Report_Banner_bottom.png",3,264,185);

        }

		//**************************************f*****************************************************************************************************************
		//** Summary and signature
		//*******************************************************************************************************************************************************

		$pdf->AddPage();

		//$pdf->TOC_Entry('Agreement Summary', 0);
		//$pdf->Bookmark('Agreement Summary');

		$pdf->fontsize = "18";
		$pdf->SetFont('Arial','',18);
		$strOutputSummary = "
				<div align='left' width='100%' cellspacing='0' margin='0' style='text-align:left;width:100%; color:#8E2C48;'>
					FEE SUMMARY
				</div>
				$BR";
		$pdf->WriteHTML($strOutputSummary);
		$pdf->fontsize = "8";
		$pdf->SetFont('Arial','',8);

		$strOutputSummary = "
			<table width='100%' cellspacing='0' cellpadding='0'>
				<tr>
					<td colspan = 2  style='font-size:18px; font-weight:bold;'><span style='color:#8E2C48;'><b>Prepared for:</b></span></td>
				</tr>
				<tr>
					<td align='left' valign='top' width='100px'>
						<b style='color:#000000;'>Name:</b>
					</td>
					<td align='left' valign='top' >
						".mynl2br($rowQuote->strPartner)."
					</td>
				</tr>
				<tr>
					<td align='left' valign='top' width='100px'>
						<b style='color:black;'>Contact Person:</b>
					</td>
					<td align='left' valign='top'>
						".mynl2br($rowQuote->strClient)."
					</td>
				</tr>
				<tr>
					<td align='left' valign='top' width='100px'>
						<b>Type:</b>
					</td>
					<td align='left' valign='top'>
						".mynl2br($rowQuote->strPartnerType)."
					</td>
				</tr>
			</table>
			$BR";
		$pdf->WriteHTML($strOutputSummary);


		$strOutputSummary = self::generateQuoteSummaryContentHTML($QuoteID,1,"");
		$pdf->WriteHTML($strOutputSummary);

		$strOutputSummary = "
				$BR
				<table width='100%' style='width:100%;'>
					<tr>
						<td align='left' style='text-align:left;'>
							Commencement date year 1: "
							.($rowQuote->dtAgreementStartDate != ""? $rowQuote->dtAgreementStartDate:"_________________________")
						."</td>
					</tr>
					<tr>
						<td align='left' style='text-align:left;'>
							Commencement date ongoing: "
							.($rowQuote->dtAgreementStartDate != ""? date("Y-m-d",strtotime("$rowQuote->dtAgreementStartDate + 1 year")):"_________________________")
						."</td>
					</tr>
				</table>
				$BR $BR $BR";
		// $strOutputSummary .= "<div align='left' width='100%' style='text-align:left;width:100%;'>
		//          Signed at ___________ on this <u>".date("jS")."</u> day of <u>".date("F")." ".date("Y")."</u>
		//       </div>";
		$strOutputSummary .= "
				<div align='left' width='100%' style='text-align:left;width:100%;'>
					<b>Signed by:</b> ____________________________  <b>Signature:</b> _________________________________
					$BR $BR
					<b>At</b> _____________________________ <b>on this</b> ___________________<b>day</b> _________________
				</div>";
		$pdf->WriteHTML($strOutputSummary);

		//*******************************************************************************************************************************************************
		//** SERVICE DETAILS BEGIN
		//*******************************************************************************************************************************************************
// if($rowQuote->strPartnerType != "Strategic Partner (Acsis Legacy only)"){
		$pdf->AddPage();
		$pdf->fontsize = "18";
		$pdf->SetFont('Arial','',18);
		$strOutputServiceDetails = "
				<div align='left' width='100%' cellspacing='0' margin='0' style='text-align:left;width:100%; color:#8E2C48;'>
					SERVICE DETAILS
				</div>
				$BR";
		$pdf->WriteHTML($strOutputServiceDetails);

		//*******************************************************************************************************************************************************
		//** Financial Planning Services
		//*******************************************************************************************************************************************************

		//$pdf->WriteHTML($strOutput);
		//$pdf->AddPage();

		//$pdf->TOC_Entry('Financial Planning Services', 0);
		//$pdf->Bookmark('Financial Planning Services');

		$pdf->fontsize = "18";
		$pdf->SetFont('Arial','',18);

		$strOutputFP = "
				<div align='left' width='100%' style='text-align:left;width:100%; color:#8E2C48;'>
					FINANCIAL PLANNING SERVICES
				</div>
				$BR";
		$pdf->WriteHTML($strOutputFP);

		$pdf->fontsize = "8";
		$pdf->SetFont('Arial','',8);
		$strOutputFP = "
				<div align='left' width='100%' style='text-align:left;width:100%;'>Services are delivered per planner and include 1 support staff per planner $BR
				</div>";
		$pdf->WriteHTML($strOutputFP);
	

		$strOutputFP = self::generateQuoteFinancialPlanningContentHTML($QuoteID);
		$pdf->WriteHTML($strOutputFP);

		$strOutputFP = self::generateQuoteFinancialPlanningTermsHTML($QuoteID);
		$pdf->WriteHTML($strOutputFP);
	

		// die("Die");

		//*******************************************************************************************************************************************************
		//** BMS
		//*******************************************************************************************************************************************************



		//$pdf->TOC_Entry('Business Managment Services (BMS)', 0);
		//$pdf->Bookmark('Business Managment Services (BMS)');
$strOutputBMS = self::generateQuoteBMSContentHTML($QuoteID);
	if($strOutputBMS != ""){

		//20180322 - Add page break infront of BMS section at PJ's request - CL
		$pdf->AddPage();
		$pdf->WriteHTML($blank);
		if($page_max_height < $pdf->GetY())
		{
			$pdf->AddPage();
		}

		$pdf->fontsize = "18";
		$pdf->SetFont('Arial','',18);
		$strOutputBMS = "
				<div align='left' width='100%' style='text-align:left;width:100%; color:#8E2C48;'>
					BUSINESS MANAGEMENT SERVICES
				</div>
				$BR";
		$pdf->WriteHTML($strOutputBMS);

		$pdf->fontsize = "8";
		$pdf->SetFont('Arial','',8);
		$strOutputBMS = "
				<div align='left' width='100%' style='text-align:left;width:100%;'>
					Services are delivered per practice $BR
				</div>";
		$pdf->WriteHTML($strOutputBMS);

		if($page_max_height < $pdf->GetY())
		{
			$pdf->AddPage();
		}

		$strOutputBMS = self::generateQuoteBMSContentHTML($QuoteID);
		$pdf->WriteHTML($strOutputBMS);

		$strOutputBMS = self::generateQuoteBMSTermsHTML($QuoteID);
		$pdf->WriteHTML($strOutputBMS);

		$strOutputBMS = $BR;
		$pdf->WriteHTML($strOutputBMS);
	}
// }

		//*******************************************************************************************************************************************************
		//** Additional Licenses
		//*******************************************************************************************************************************************************
		$pdf->WriteHTML($blank);
		if($page_max_height < $pdf->GetY() || $rowQuote->strPartnerType == "Strategic Partner (Acsis Legacy only)")
		{
			$pdf->AddPage();
		}


		//$pdf->TOC_Entry('Additional Licenses', 0);
		//$pdf->Bookmark('Additional Licenses');

		if(self::generateQuoteAdditionalLicensesContentHTML($QuoteID) != ""){
			$pdf->fontsize = "12";
			$pdf->SetFont('Arial','',12);
			$strOutputAdditionalLicenses = "
					<div align='left' width='100%' style='text-align:left;width:100%; font-weight:bold; color:#018671;'>
						ADDITIONAL LICENSES
					</div>
					$BR";

			$pdf->WriteHTML($strOutputAdditionalLicenses);

			$pdf->fontsize = "8";
			$pdf->SetFont('Arial','',8);

			$strOutputAdditionalLicenses = self::generateQuoteAdditionalLicensesContentHTML($QuoteID);
			$pdf->WriteHTML($strOutputAdditionalLicenses);
		}




		//*******************************************************************************************************************************************************
		//** X PLAN
		//*******************************************************************************************************************************************************

		//$pdf->AddPage();
		$pdf->WriteHTML($blank);
		if($page_max_height < $pdf->GetY())
		{
			$pdf->AddPage();
		}

		//$pdf->TOC_Entry('Old Mutual Wealth Xplan Multi-site (CRMIntegrator)', 0);
		//$pdf->Bookmark('Old Mutual Wealth Xplan Multi-site (CRMIntegrator)');


        $XPlanSelected = self::generateQuoteSummaryContentHTML($QuoteID , 0, "XPlanSummary");


        if($XPlanSelected != ""){
			$pdf->fontsize = "18";
			$pdf->SetFont('Arial','',18);
			//20180326 - remove all mention of (CRMIntegrator) and replace with "OM Wealth Xplan Multi-site" - CL
			$strOutputXPlan = "$BR
					<div align='left' width='100%' style='text-align:left;width:100%; color:#8E2C48;'>
						Client Relationship Management (CRM) Tools
					</div>
					$BR";

			$pdf->WriteHTML($strOutputXPlan);

			$pdf->fontsize = "8";
			$pdf->SetFont('Arial','',8);
			$strOutputXPlan = "
					<div align='left' width='100%' style='text-align:left;width:100%;margin-bottom:10px;'>
						Services are delivered per practice $BR
					</div>
					";
			$pdf->WriteHTML($strOutputXPlan);

			if($page_max_height < $pdf->GetY())
			{
				$pdf->AddPage();
			}

			$strOutputXPlan = self::generateQuoteXPlanContentHTML($QuoteID);
			$pdf->WriteHTML($strOutputXPlan);

			$strOutputXPlan = self::generateQuoteXPlanTermsHTML($QuoteID);
			$pdf->WriteHTML($strOutputXPlan);
		}


		

		//*******************************************************************************************************************************************************
		//** output
		//*******************************************************************************************************************************************************

		//$pdf->stopPageNums();

		//Generate and insert TOC at page 2
		//$pdf->insertTOC(2);

		$strLocation = "./documents/SLA/";
		$strFileName = self::getFileName($QuoteID);

		//20191117 - Set different footer on last page - Rachel
		$pdf->_numberingFooter = false;
		//20191117 - Set different footer on last page - Rachel
		if(file_exists("./images/Quote pdf footer.jpg")){
			if($page_max_height < $pdf->GetY() && $rowQuote->strPartnerType != "Strategic Partner (Acsis Legacy only)")
			{
				$pdf->AddPage();
			}
			$pdf->Image("./images/Quote pdf footer.jpg",0,230,200);
		}

		//output to file
		$pdf->Output($strLocation.$strFileName, 'F');
		self::updateQuoteFileName($QuoteID);

		//output to this current tab
		header("Content-type: application/pdf");
		$pdf->Output($strFileName, 'I');
	}

	public static function getFileName($QuoteID)
	{
		global $xdb, $TR, $SP, $HR, $BR, $SystemSettings;

		$rowQuote = $xdb->getRowSQL("SELECT slaQuote.* FROM slaQuote WHERE QuoteID = ".$xdb->qs($QuoteID),0);

		$strPartner = self::cleanFileName($rowQuote->strPartner);

		$strVersion = str_replace(" ","_",$rowQuote->strVersion);
		$strVersion = strtolower(qs($strVersion));

		$strStatus = str_replace(" ","_",$rowQuote->strStatus);
		$strStatus = strtolower($strStatus);

		//20180411 - Fix format of SLA filename - CL
		return "annex_d_".$strPartner."_v".$strVersion."_".$strStatus.".pdf"; //date("Ymd")
	}

	//20180411 - Add cleanFilename function to remove unwanted characters and format string correctly - CL
	public static function cleanFileName($string="")
	{
		$strCleanString = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
		$strCleanString = strtolower(qs($strCleanString));

		//step 1: replace specific characters
		$strCleanString = str_replace("\\", "", $strCleanString);
		$strCleanString = str_replace("/", "", $strCleanString);
		$strCleanString = str_replace('"', "", $strCleanString);
		$strCleanString = str_replace("'", "", $strCleanString);

		$strPartner = str_replace(" ","_",$rowQuote->strPartner); // spaces become underscores

		//replace ¹ , ² , ³
		$strCleanString = str_replace(chr(185), "1", $strCleanString);
		$strCleanString = str_replace(chr(178), "2", $strCleanString);
		$strCleanString = str_replace(chr(179), "3", $strCleanString);
		//replace curly quotes
		$strCleanString = str_replace(chr(145), "", $strCleanString);
		$strCleanString = str_replace(chr(146), "", $strCleanString);
		$strCleanString = str_replace(chr(147), "", $strCleanString);
		$strCleanString = str_replace(chr(148), "", $strCleanString);
		//replace – en and — em dash
		$strCleanString = str_replace(chr(150), "-", $strCleanString);
		$strCleanString = str_replace(chr(151), "-", $strCleanString);

		//step 2: Removes unwanted special chars.
		$strCleanString = preg_replace_callback("/[^a-zA-Z0-9_.-]/", function ($matches) {
				return "";
		  }, $strCleanString);

		return $strCleanString;
	}
}
?>