<?php

// Global Functions

// Get Variables
function getVariables($admin,$page) {
	switch($admin) {
		case 'client':
				$fieldArray = array('clientName','clientAbbr','clientWebsite','clientContactName','clientContactTitle','clientContactEmail','clientContactPhone','clientContactMobile','clientAddressStreet','clientAddress2','clientAddressPO','clientAddressCity','clientState','clientAddressZip','clientSince ','subClientOf','clientSubCompany','clientStatus','ratePercent','rateHourly','clientSince','addContact','clientNotes','clientType','clientSupport');
				$excludeArray = array('submit','clientStatus','loginfo','adminType','page','section');
				$displayArray = array('clientID','clientName','clientAbbr','clientStatus','subClientOf','subName','subAbbr','clientWebsite','clientContactName','clientContactEmail','clientContactPhone','clientContactMobile','clientAddressStreet','clientAddress2','clientAddressPO','clientAddressCity','clientAddressCity','clientState','clientAddressZip','clientSince');
			break;
		case 'project':
			$fieldArray = array('projectID','projectName','projectDesc','website','loginfo','projectType','priority','projectCategory','clientID','projectAmount','projectStatus','projectStart','projectTargetComp','projectTimeEstimate','projectProgress','projectRate','currentRateID','rateHistory','projectDisp','projectCurrent','projectMaint','estID');
			$excludeArray = array('submit','projectDisp','projectTimeEstimate','existEstimateID','existRate','rateHist','adminType','page','section');
			if ($page == 'dash')
				$displayArray = array('projectID','projectName','projectTargetComp','clientID','projectCurrent','projectType');
			else 
				$displayArray = array('projectID','projectName','projectTargetComp','clientID','projectType','projectTargetComp','projectDisp','projectAmount');
			break;
		case 'loginfo':
			$fieldArray = array('infoID','infoDesc','compID','projectID','website','hostInfo','domainInfo','emailInfo','ftpInfo','dbInfo','socialInfo','cmsInfo','otherInfo','oldInfo','display');
			$displayArray = array('infoID','clientID','subClientOf','website','clientAbbr','clientName','infoDesc','projectName');
			$excludeArray = array('display','page','section'); 
			break;
		case 'todo':
			$fieldArray = array('todoID','todoName','todoNotes','clientID','projectID','addDate','dueDate','todoDone','display');
			$excludeArray = array('submit','adminType','page','section');
			if ($page == 'dash')
				$displayArray = array('todoID','todoName','todoNotes','clientID','projectID','addDate','dueDate');
			else 
				$displayArray = array('todoID','todoName','todoNotes','clientID','projectID','addDate','dueDate');
			$excludeArray = array('submit','adminType','page','section','display','todoDone'); 
			break;
		case 'task':
			$fieldArray = array('taskID','projectID','taskName','taskDesc','startDate','dueDate','editDate','priority','taskEstimate','taskStatus','taskProgress','display');
			$excludeArray = array('submit','display','adminType','page','section');
			if ($page == 'dash')
				$displayArray = array('taskID','taskName','projectID','taskEstimate','dueDate','clientID');
			else
				$displayArray = array('taskID','taskName','clientName','clientAbbr','dueDate','display','subClientOf','clientID','projectName','taskEstimate');
			break;
		case 'note':
			$fieldArray = array('noteID','noteDate','noteContent','clientID','projectID','display');
			$excludeArray = array('submit');
			$displayArray = array('noteID','noteDate','noteContent');
			break; 
		case 'ongoing':
			$fieldArray = array('feeID','feeDescID','clientID','feeAmt','feeDesc','currentRateID','feeStartDate','feeRecID','feeLastRec','feeNextRec','projectID','feeActive','display');
			$excludeArray = array('submit','feeActive','display','adminType','activateFee','page');
			$displayArray = array('feeID','noteDate','noteContent');
			break;
		case 'rate':
			$fieldArray = array('rateID','rateName','rateDesc','rateAmt','compPercent','clientID','rateEffective','oldRateID','newRateID','rateExpire','display','active');
			$excludeArray = array('submit','active','display','adminType');
			$displayArray = array('rateID','rateName','rateDesc','rateAmt','compPercent','clientID','rateEffective','rateExpire');
			break;
		default :
			$fieldArray = array();
			$excludeArray = array();
			$displayArray = array();
	}
	$vars = array('fieldArray'=>$fieldArray,'excludeArray'=>$excludeArray,'displayArray'=>$displayArray);
	return $vars; 
}

// Generate Secure Password
function generateHashWithSalt($password) {
	define("MAX_LENGTH", 25);
    $intermediateSalt = md5(uniqid(rand(), true));
    $salt = substr($intermediateSalt, 0, MAX_LENGTH);
   	$pw = hash("sha256", $password . $salt);
	$secPW = array('salt'=>$salt,'pw'=>$pw);
	return $secPW;
}

// Get Clients
function getCompany($compID,$con) {
	$selectID = $compID;
	$clients = '<select name="compID" data-rule-required="false" data-msg-required="Please Select a Client">
					<option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM clients WHERE clientStatus=2 ORDER BY clientName, clientAbbr';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$clName = $row['clientName'];
		if (!empty($row['clientAbbr']))
			$clName .= ' ('. $row['clientAbbr'] . ')';
		$clients .= '<option value="'. $row['clientID'] .'"';
		if ($row['clientID'] == $selectID)
			$clients .= ' selected';
		$clients .= '>'. $clName .'</option>';
	}
	$clients .= '</select>';
	return $clients;
}

// Get Parent Client
function getPclients($pclientID,$con) {
	$selectID = $pclientID;
	$pClients = '<select name="pclientID">
					<option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM clients WHERE subClientOf=0 ORDER BY clientName';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$clName = $row['clientName'];
		if (!empty($row['clientAbbr']))
			$clName .= ' ('. $row['clientAbbr'] . ')';
		$pClients .= '<option value="'. $row['clientID'] .'"';
		if ($row['clientID'] == $selectID)
			$pClients .= ' selected';
		$pClients .= '>'. $clName .'</option>';
	}
	$pClients .= '</select>';
	return $pClients;
}

// Get Parent Client Options
function getPclientOptions($pclientID,$con) {
	$selectID = $pclientID;
	$pClients = ''; 
	$query = 'SELECT * FROM clients WHERE subClientOf=0 ORDER BY clientName';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$clName = $row['clientName'];
		if (!empty($row['clientAbbr']))
			$clName .= ' ('. $row['clientAbbr'] . ')';
		$pClients .= '<option value="'. $row['clientID'] .'"';
		if ($row['clientID'] == $selectID)
			$pClients .= ' selected';
		$pClients .= '>'. $clName .'</option>';
	}
	return $pClients;
}

// Get Parent Client List
function getPclientArray($con) {
	$query = 'SELECT * FROM clients WHERE clientStatus=2 AND clientType=1 AND subClientOf=0 ORDER BY clientName';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$pClients[$row['clientID']] = $row['clientName']; 
	}
	return $pClients;
}

// Clean Client Name
function cleanClientName($filename) {
	$filename = $filename;
	$filename = preg_replace('/[^ A-Za-z0-9.]/', '_', $filename);   
	$filename = preg_replace('/[ \t\n\r]+/', '_', $filename);   
	$filename = str_replace(' ', '_', $filename);   
	$filename = preg_replace('/[ _]+/', '_', $filename); 
	return $filename;
}

// Get Auth
function getAuth($authID,$con) {
	$selectID = $authID;
	$auths = '<select name="authID">
					<option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM userAuthLevels ORDER BY authTitle';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$auths .= '<option value="'. $row['authID'] .'"';
		if ($row['authID'] == $selectID)
			$auths .= ' selected';
		$auths .= '>'. $row['authTitle'] .'</option>';
	}
	$auths .= '</select>';
	return $auths;
}

// Get Projects
function getProjects($projID,$projType,$con) {
	$selectID = $projID;
	//$projType = (($projType=='project') ? 1 : 2);
	if (empty($selectID))
		$allSel = ' selected';
	else 
		$allSel = '';
	$projects = '<select name="projects[]" multiple="multiple" size="10">
					<option value="all"'. $allSel .'>All Projects</option>'; 
	$query = 'SELECT p.projectID, p.projectName AS pname, c.clientName AS cname, c.clientAbbr FROM projects p LEFT JOIN clients c ON (p.clientID = c.clientID) WHERE projectDisp=1';
	if (!empty($projType))
		$query .= ' AND projectType='. $projType;
	
	$query .= '  ORDER BY cname, pname';
	$result = $con->query($query);
	
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$projectFullName = $row['cname'];
		if (!empty($row['clientAbbr']))
			$projectFullName .= ' ('. $row['clientAbbr'] .')';
		$projectFullName .= ' - '. $row['pname'];
	
		$projects .= '<option value="'. $row['projectID'] .'"';
		if ($row['projectID'] == $selectID)
			$stats .= ' selected';
		$projects .= '>'. $projectFullName  .'&nbsp;</option>';
	}
	$projects .= '</select>';
	return $projects;
}

// Get Project Lists
function getProjectLists($projID,$stat,$con) {
	$selectID = $projID;
	$allSel = ((empty($selectID)) ? ' selected' : '');
	$filter = ((!empty($stat)) ? ' AND projectStatus IN ('. $stat .')' : ' ');
	$projects = '<select name="projectID">
					<option value=""'. $allSel .'>&lt; select project &gt;</option>'; 
	$query = 'SELECT p.projectID, p.projectName AS pname, c.clientName AS cname, c.clientAbbr FROM projects p LEFT JOIN clients c ON (p.clientID = c.clientID) WHERE projectDisp=1'. $filter .'ORDER BY cname, pname';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		/*if (!empty($row['clientAbbr']))
			$projectFullName = $row['clientAbbr'];
		else
			$projectFullName = $row['cname'];*/
		$projectFullName = $row['cname'];
		$projectFullName .= ' - '. $row['pname'];
	
		$projects .= '<option value="'. $row['projectID'] .'"';
		if ($row['projectID'] == $selectID)
			$projects .= ' selected';
		$projects .= '>'. $projectFullName  .'&nbsp;</option>';
	}
	$projects .= '</select>';
	return $projects;
}
// Get Project
function getProject($projID,$projType,$con) {
	$selectID = $projID;
	$projType = $projType;
	if (empty($selectID))
		$allSel = ' selected';
	else 
		$allSel = '';
	$projects = '<select name="projectID">
					<option value=""'. $allSel .'>&lt; select project &gt;</option>'; 
	$query = 'SELECT p.projectID, p.projectName AS pname, c.clientName AS cname, c.clientAbbr FROM projects p LEFT JOIN clients c ON (p.clientID = c.clientID) WHERE projectDisp=1';
	if (!empty($projType))
		$query .= ' AND projectType='. $projType;
	$query .= '  ORDER BY cname, pname';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		if (!empty($row['clientAbbr']))
			$projectFullName = $row['clientAbbr'];
		else
			$projectFullName = $row['cname'];
		$projectFullName .= ' - '. $row['pname'];
	
		$projects .= '<option value="'. $row['projectID'] .'"';
		if ($row['projectID'] == $selectID)
			$projects .= ' selected';
		$projects .= '>'. $projectFullName  .'&nbsp;</option>';
	}
	$projects .= '</select>';
	return $projects;
}

// Get Client Name
function getClientName($cID,$con) {
	$selectID = $cID;
	$query = 'SELECT * FROM clients WHERE clientID='. $selectID;
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$clName = $row['clientName'];
		if (!empty($row['clientAbbr']))
			$clName .= ' ('. $row['clientAbbr'] . ')';
		$client = $clName;
	}
	return $client;
}
// Get Project Status
function getProjStatus($statID,$con) {
	$selectID = $statID;
	$stats = '<select name="projectStatus" data-rule-required="true" data-msg-required="Please Select a Status">
					<option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM projectStatus ORDER BY pstatDesc';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$stats .= '<option value="'. $row['pstatID'] .'"';
		if ($row['pstatID'] == $selectID)
			$stats .= ' selected';
		$stats .= '>'. $row['pstatDesc'] .'</option>';
	}
	$stats .= '</select>';
	return $stats;
}

// Get Project Current Status
function getProjCurrentStatus($pCurrent) {
	$selectID = $pCurrent;
	$stats = ''; 
	$stats .= '<option value="0"';
	if ($selectID == 0)
		$stats .= ' selected';
	$stats .= '>All Projects</option>';
	$stats .= '<option value="1"';
	if ($selectID == 1)
		$stats .= ' selected';
	$stats .= '>Current Projects</option>';
	return $stats;
}

// Get Project Stats
function getProjStats($statID,$con) {
	$selectID = $statID;
	$stats = ''; 
	$query = 'SELECT * FROM projectStatus ORDER BY pstatDesc';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$stats .= '<option value="'. $row['pstatID'] .'"';
		if ($row['pstatID'] == $selectID)
			$stats .= ' selected';
		$stats .= '>'. $row['pstatDesc'] .'</option>';
	}
	return $stats;
}

// Get Type
function getProjType($ptypeID,$con) {
	$selectID = $ptypeID;
	$types = '<select name="projectType" data-rule-required="true" data-msg-required="Please Select a Project Type">
					<option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM projectType ORDER BY ptypeDesc';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$types .= '<option value="'. $row['ptypeID'] .'"';
		if ($row['ptypeID'] == $selectID)
			$types .= ' selected';
		$types .= '>'. $row['ptypeDesc'] .'</option>';
	}
	$types .= '</select>';
	return $types;
}

// Get Project Category
function getProjCat($selectID,$con) {
	$types = '<select name="projectCategory" data-rule-required="true" data-msg-required="Please Select a Category">
					<option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM projectCategory WHERE display=1 ORDER BY catName';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$types .= '<option value="'. $row['catID'] .'"';
		if ($row['catID'] == $selectID)
			$types .= ' selected';
		$types .= '>'. $row['catName'] .'</option>';
	}
	$types .= '</select>';
	return $types;
}

// Get Project Client
function getProjClient($projectID,$con) {
	$query = 'SELECT c.clientName, c.clientAbbr FROM projects p LEFT JOIN clients c ON (p.clientID = c.clientID) WHERE projectID='. $projectID;
	$result = $con->query($query);
	$row = $result->fetch_array(MYSQLI_ASSOC);
	$client = $row['clientName'];
	if (!empty($row['clientAbbr']))  
		$client .= ' ('. $row['clientAbbr'] .')';
	return $client;
}

// Get Fee Type
function getFeeType($feeDescID,$con) {
	$selectID = $feeDescID;
	$feeTypes = '<select name="feeDescID">
					<option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM feeDesc ORDER BY feeDesc';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$feeTypes .= '<option value="'. $row['feeDescID'] .'"';
		if ($row['feeDescID'] == $selectID)
			$feeTypes .= ' selected';
		$feeTypes .= '>'. $row['feeDesc'] .'</option>';
	}
	$feeTypes .= '</select>';
	return $feeTypes;
}

// Get Project Priority
function getProjPriority($ppID,$con) {
	$selectID = $ppID;
	$options = '<option value="">&lt; select &gt;</option>';  
	$query = 'SELECT * FROM projectPriority ORDER BY ppOrder';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$options .= '<option value="'. $row['ppID'] .'"';
		if ($row['ppID'] == $selectID)
			$options .= ' selected';
		$options .= '>'. $row['ppName'] .'</option>';
	}
	return $options;
}

// Get Fee Recourrance
function getFeeRec($feeRecID,$con) {
	$selectID = $feeRecID;
	$feeRecs = '<select name="feeRecID">
					<option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM feeRec ORDER BY feeRecCalc';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$feeRecs .= '<option value="'. $row['feeRecID'] .'"';
		if ($row['feeRecID'] == $selectID)
			$feeRecs .= ' selected';
		$feeRecs .= '>'. $row['feeRecDesc'] .'</option>';
	}
	$feeRecs .= '</select>';
	return $feeRecs;
}

// Get Rate / Commission Plan
function getRates($currentRate,$con) {
	$selectID = $currentRate;
	$selField = '<select name="currentRateID" data-rule-required="true" data-msg-required="Please Select a Rate"><option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM clientRates WHERE display=1 ORDER BY rateName';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$selField .= '<option value="'. $row['rateID'] .'"';
		if ($row['rateID'] == $selectID)
			$selField .= ' selected';

		$rateInfo = ''; 
		if (!empty($row['rateAmt']))
			$rateInfo .= '$'. number_format($row['rateAmt']) . '/hour';
		if ( (!empty($row['rateAmt'])) && (!empty($row['compPercent'])) )
			$rateInfo .= '&nbsp;&nbsp;|&nbsp;&nbsp;'; 
		if (!empty($row['compPercent']))
			$rateInfo .= number_format($row['compPercent'],2,'.','') . '%';
		if (!empty($rateInfo))
			$rateInfo = ' ('. $rateInfo .')';

		$selField .= '>'. $row['rateName'] . $rateInfo .'</option>';
	}
	$selField .= '</select>';
	return $selField;
}

// Get Service Types
function getSvcType($serviceID,$con) {
	$selectID = $serviceID;
	$options = ''; 
	$query = 'SELECT * FROM serviceTypes WHERE display=1 ORDER BY serviceName';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$options .= '<option value="'. $row['serviceID'] .'"';
		if ($row['serviceID'] == $selectID)
			$options .= ' selected';
		$options .= '>'. $row['serviceName'] .'</option>';
	}
	return $options;
}

// Get Service Providers
function getSvcProvide($spID,$con) {
	$selectID = $spID;
	$options = ''; 
	$query = 'SELECT * FROM serviceProviders WHERE display=1 ORDER BY spName';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$options .= '<option value="'. $row['spID'] .'"';
		if ($row['spID'] == $selectID)
			$options .= ' selected';
		$options .= '>'. $row['spName'] .'</option>';
	}
	return $options;
}

// Get Service Owners
function getSvcOwner($ownerID,$con) {
	$selectID = $ownerID;
	$options = ''; 
	$query = 'SELECT * FROM serviceOwner WHERE display=1 ORDER BY ownerDesc';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$options .= '<input type="radio" class="radioBtn" name="svcOwner" style="width: 20px" value="'. $row['ownerID'] .'"';
		if ($row['ownerID'] == $selectID)
			$options .= ' checked';
		$options .= '>'. $row['ownerDesc'] .'<br>';
	}
	return $options;
}


// Get Estimates
function getEstimates($projID,$con) {
	$selectID = $projID;
	$estimates = '<select name="estID">
					<option value="0">&lt; select estimate &gt;</option>'; 
	$query = 'SELECT * FROM estimates ORDER BY estDate DESC';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$estimates .= '<option value="'. $row['estID'] .'"';
		if ($row['estID'] == $selectID)
			$estimates .= ' selected';
		$estimates .= '>'. $row['estName'] .'</option>';
	}
	$estimates .= '</select>';
	return $estimates;
}

// Get Estimate Total
function getEstimateTotal($estID,$con) {
	$selectID = $estID;
	$query = 'SELECT estTotalHours FROM estimates WHERE estID='. $selectID;
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$estimate = $row['estTotalHours'];
	}
	return $estimate;
}

// Get Client Type
function getCtypeSelect($typeID,$con) {
	$selectID = $typeID;
	$select = '<select name="clientType">
					<option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM clientType ORDER BY typeOrder';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$select .= '<option value="'. $row['typeID'] .'"';
		if ($row['typeID'] == $selectID)
			$select .= ' selected';
		$select .= '>'. $row['typeName'] .'</option>';
	}
	$select .= '</select>';
	return $select;
}

// Get Client Support
function getSupportSelect($supportID,$con) {
	$selectID = explode(',',$supportID);
	$select = '<select name="clientSupport[]" multiple size="5">';
	$select .= '<option value=""';
	$select .= ((empty($selectID) || array_sum($selectID) < 1) ? ' selected' : '');
	$select .= '>No Support Plan</option>'; 
	$query = 'SELECT sp.*, si.intName, c.clientName, c.clientAbbr FROM supportPlans sp LEFT JOIN supportIntervals si ON (sp.supportInterval = si.intID) LEFT JOIN clients c ON (sp.supportParentClient = c.clientID) ORDER BY sp.supportName';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$select .= '<option value="'. $row['supportID'] .'"';
		if (in_array($row['supportID'], $selectID))
			$select .= ' selected';
		$select .= '>'. $row['supportName'] .' ('. $row['clientAbbr'] .') $'. $row['supportRate'] .' '. $row['intName'] .'</option>';
	}
	$select .= '</select>';
	return $select;
}

// Defint Column Sort Variables for Sortable Tables
function defineSorts($num,$orderBy) {
	for ($i=1;$i<=$num;$i++) {
		$sortVar = 'sort'. $i;
		$orderVar = 'order'. $i;
		global $$sortVar, $$orderVar;
			
		$sortDir = substr($orderBy, 1);
		if ($sortDir == 'up')
			$sortRev = 'down';
		else
			$sortRev = 'up';
		$colTest = $i . $sortDir;
		
		if ($colTest == $orderBy) {
			$$sortVar = ' id="headerSel_'. $sortDir .'"';
			$$orderVar = 'orderBy='. $i . $sortRev; 
		}
		else {
			$$sortVar = 'class="tableHeader"';
			$$orderVar = 'orderBy='. $i .'down'; 
		}
	}
}	

// Get Estimate Status
function getEstStatus($statID,$con) {
	$selectID = $statID;
	$stats = '<select name="estStatus">
					<option value="">&lt; select &gt;</option>'; 
	$query = 'SELECT * FROM estimateStatus ORDER BY estStatID';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$stats .= '<option value="'. $row['estStatID'] .'"';
		if ($row['estStatID'] == $selectID)
			$stats .= ' selected';
		$stats .= '>'. $row['estStatDesc'] .'</option>';
	}
	$stats .= '</select>';
	return $stats;
}

// Get Task Status
function getTaskStatus($statID,$con) {
	$selectID = $statID;
	$stats = ''; 
	$query = 'SELECT * FROM taskStatus ORDER BY dispOrder';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$stats .= '<option value="'. $row['taskStatID'] .'"';
		if ($row['taskStatID'] == $selectID)
			$stats .= ' selected';
		$stats .= '>'. $row['taskStatDesc'] .'</option>';
	}
	return $stats;
}

// Get Tasks
function getTasks($projectID,$taskID,$con) {
	$selectID = $taskID;
	$query = 'SELECT * FROM tasks WHERE projectID='. $projectID .' ORDER BY dueDate DESC';
	$result = $con->query($query);
	$rows = mysqli_num_rows($result);
	
	if ($rows > 0) {
		$tasks = '<option value="0">&lt; select &gt;</option>'; 
		//while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
			$tasks .= '<option value="'. $row['taskID'] .'"';
			if ($row['taskID'] == $selectID)
				$tasks .= ' selected';
			$tasks .= '>'. $row['taskName'] .'</option>';
		}
	}
	return $tasks;
}

// Chect tio  see if Project Rate is Current
function checkRateCurrent($rID,$dtStart,$dtEnd,$con) {
	$query = 'SELECT rateAmt, compPercent, rateEffective, rateExpire, oldRateID, newRateID FROM clientRates WHERE rateID='. $rID;
	$result = $con->query($query);
	$row = $result->fetch_array(MYSQLI_ASSOC);
	if ( ($dtStart >= $row['rateEffective']) && ( ($dtEnd <= $row['rateExpire']) || (empty($row['rateExpire'])) ) ) {
		// This is the current rate
		$currentRates = array($row['rateAmt'], $row['compPercent']);
	}
	else {
		// Check for new Rates
		
		if ($dtStart < $row['rateEffective']) {
			if (!empty($rateReplaced)) {
				if (!empty($row['oldRateID'])) {
					$query = 'SELECT rateAmt, compPercent, rateEffective, rateExpire, oldRateID, newRateID FROM clientRates WHERE rateID='. $row['oldRateID'];
					$result = $con->query($query);
					$row=$result->fetch_array(MYSQLI_ASSOC);	
					if ( ($dtStart >= $row['rateEffective']) && ( ($dtEnd <= $row['rateExpire']) || (empty($row['rateExpire'])) ) ) {
						$currentRates = array($row['rateAmt'], $row['compPercent']);
					}
				}
			}
		}
		elseif ($dtStart > $row['rateExpire']) {
			if (!empty($row['newRateID'])) {
				$query = 'SELECT rateAmt, compPercent, rateEffective, rateExpire, oldRateID, newRateID FROM clientRates WHERE rateID='. $row['newRateID'];
				$result = $con->query($query);
				//$row = mysql_fetch_array($result);
				$row=$result->fetch_array(MYSQLI_ASSOC);
				if ( ($dtStart >= $row['rateEffective']) && ( ($dtEnd <= $row['rateExpire']) || (empty($row['rateExpire'])) ) ) {
					$currentRates = array($row['rateAmt'], $row['compPercent']);
				}
			}
		}
	}
	if (!isset($currentRates))
		$currentRates = array(); 
	return $currentRates;
}

// Get File Extension
function getFileExtension($str) {
	$i = strrpos($str,".");
    if (!$i) { return ""; }

    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);

    return $ext;
}

/**
 * Function to calculate date or time difference.
 * 
 * Function to calculate date or time difference. Returns an array or
 * false on error.
 *
 * @author       J de Silva                             <giddomains@gmail.com>
 * @copyright    Copyright &copy; 2005, J de Silva
 * @link         http://www.gidnetwork.com/b-16.html    Get the date / time difference with PHP
 * @param        string                                 $start
 * @param        string                                 $end
 * @return       array
 */
function get_time_difference( $start, $end )
{
    $uts['start']      =    strtotime( $start );
    $uts['end']        =    strtotime( $end );
    if( $uts['start']!==-1 && $uts['end']!==-1 )
    {
        if( $uts['end'] >= $uts['start'] )
        {
            $diff    =    $uts['end'] - $uts['start'];
            if( $days=intval((floor($diff/86400))) )
                $diff = $diff % 86400;
            if( $hours=intval((floor($diff/3600))) )
                $diff = $diff % 3600;
            if( $minutes=intval((floor($diff/60))) )
                $diff = $diff % 60;
            $diff    =    intval( $diff );            
            return( array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
        }
        else
        {
            trigger_error( "Ending date/time is earlier than the start date/time", E_USER_WARNING );
        }
    }
    else
    {
        trigger_error( "Invalid date/time data detected", E_USER_WARNING );
    }
    return( false );
}

// Date Class
class Date 
{
	/***
		$from_mask can be:
			s	seconds, with leading zeros
			i	minutes, with leading zeros
			m	month, with leading zeros
			H	24-hour format of an hour with leading zeros
			y	A two digit represenation of a year
			Y	A full numeric represenation of a year, 4 digits
		@author Mariusz Stankiewicz http://prettymad.net
	*/
	public static function convert($string, $from_mask, $to_mask='', $return_unix=false)
	//function convert($string, $from_mask, $to_mask='', $return_unix=false)
	{
		// define the valid values that we will use to check
		// value => length
		$all = array(
			's' => 'ss',
			'i' => 'ii',
			'H' => 'HH',
			'y' => 'yy',
			'Y' => 'YYYY', 
			'm' => 'mm', 
			'd' => 'dd'
		);

		// this will give us a mask with full length fields
		$from_mask = str_replace(array_keys($all), $all, $from_mask);

		$vals = array();
		foreach($all as $type => $chars)
		{
			// get the position of the current character
			if(($pos = strpos($from_mask, $chars)) === false)
				continue;

			// find the value in the original string
			$val = substr($string, $pos, strlen($chars));

			// store it for later processing
			$vals[$type] = $val;
		}

		foreach($vals as $type => $val)
		{
			switch($type)
			{
				case 's' :
					$seconds = $val;
				break;
				case 'i' :
					$minutes = $val;
				break;
				case 'H':
					$hours = $val;
				break;
				case 'y':
					$year = '20'.$val; // Year 3k bug right here
				break;
				case 'Y':
					$year = $val;
				break;
				case 'm':
					$month = $val;
				break;
				case 'd':
					$day = $val;
				break;
			}
		}
		
		if (!isset($hours)) {$hours = 0;}
		if (!isset($minutes)) {$minutes = 0;}
		if (!isset($seconds)) {$seconds = 0;}

		$unix_time = mktime(
			(int)$hours, (int)$minutes, (int)$seconds, 
			(int)$month, (int)$day, (int)$year);
		
		if($return_unix)
			return $unix_time;

		return date($to_mask, $unix_time);
	}
}

// Get the last Day of a month
function lastday($month, $year) {
   if (empty($month))
      $month = date('m');
   if (empty($year))
      $year = date('Y');
   $result = strtotime("{$year}-{$month}-01");
   $result = strtotime('-1 second', strtotime('+1 month', $result));
   return date('Y-m-d', $result);
}

// Add X Months to Date
function addMonths($today, $addAmt) {
	$updateMonth = strtotime(date('Y-m-d', strtotime($today)) . ' +'. $addAmt .' month');
	$updateMonth = date('Y-m-d', $updateMonth);
	return $updateMonth;
}

// Add X Daye to Date
function addDays($today, $addAmt) {
	$updateDay = strtotime(date('Y-m-d', strtotime($today)) . ' +'. $addAmt .' day');
	$updateDay = date('Y-m-d', $updateDay);
	return $updateDay;
}

// Remove a value from an array
function remove_element($arr, $val){
	foreach ($arr as $key => $value){
		if ($arr[$key] == $val){
			unset($arr[$key]);
		}
	}
	return $arr = array_values($arr);
}

/**
* word-sensitive substring function with html tags awareness
* @param text The text to cut
* @param len The maximum length of the cut string
* @returns string
**/
function substrws( $text, $len=180 ) {
    if( (strlen($text) > $len) ) {
        $whitespaceposition = strpos($text," ",$len)-1;
        if( $whitespaceposition > 0 )
            $text = substr($text, 0, ($whitespaceposition+1));

        // close unclosed html tags
        if( preg_match_all("|<([a-zA-Z]+)>|",$text,$aBuffer) ) {
            if( !empty($aBuffer[1]) ) {
                preg_match_all("|</([a-zA-Z]+)>|",$text,$aBuffer2);
                if( count($aBuffer[1]) != count($aBuffer2[1]) ) {
                    foreach( $aBuffer[1] as $index => $tag ) {
                        if( empty($aBuffer2[1][$index]) || $aBuffer2[1][$index] != $tag)
                            $text .= '</'.$tag.'>';
                    }
                }
            }
        }
    }
    return $text;
} 

//Remove Extra Spaces (created by CKeditor)
function removeExtra($string) {
	$string = preg_replace('/\s+/',' ',$string);
	return $string;
}

######################## Marketing #################################

// Populate Source select boxes
function get_sources($selectID,$con) {
	global $source;
	$source = '<option value="0">select</option>';
	$query = "SELECT * FROM prospect_source ORDER BY source_name"; 

	$result = $con->query($query);
	while($row = mysqli_fetch_object($result)){
		$sourceid = $row->sourceid;
		$source_name = $row->source_name;
		$source_abb = $row->source_abb;
		if (!empty($source_abb)) 
			$src_option = $source_abb;
		else 
		 	$src_option = $source_name;
		$source.= '<option value="'. $sourceid .'"';
		if ($sourceid == $selectID)
			$source.= ' selected';
		$source.= '>'. $src_option .'</option>';
	}
	return $source;
}

// Populate Campaign select boxes
function get_campaigns($selectID,$con) {
	global $options;
	$options = '<option value="0">select</option>';
	$query = "SELECT * FROM marketing_campaigns ORDER BY camp_date DESC"; 
	$result = $con->query($query);
	while($row = mysqli_fetch_object($result)){
		$campid = $row->campid;
		$camp_name = $row->camp_name;
		$camp_date = $row->camp_date;
		$options .= '<option value="'. $campid .'"';
		if ($campid == $selectID)
			$options .= ' selected';
		$options .= '>'. $camp_date .' '. $camp_name .'</option>';
	}
	return $options;
}

// Populate Campaign Type select boxes
function get_campaignTypes($selectID,$con) {
	global $options;
	$options = '<option value="0">select</option>';
	$query = "SELECT * FROM marketing_campaign_type ORDER BY type_desc DESC"; 
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$options .= '<option value="'. $row['typeid'] .'"';
		if ($row['typeid'] == $selectID)
			$options .= ' selected';
		$options .= '>'. $row['type_desc'] .'</option>';
	}
	return $options;
}

// Populate Campaign Contacts select boxes
function get_campContacts($selected,$con) {
	global $options;
	if (!empty($selected)) {
		$selected = explode(',',$selected);
		$selSelected = ''; 
	} else {
		$selected = array();
		$selSelected = ' selected'; 
	}
	$options = '<option value=""'. $selSelected .'>select</option>';
	$query = "SELECT contactID, lastname, firstname, company FROM marketing_contacts ORDER BY lastname DESC"; 
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$options .= '<option value="'. $row['contactID'] .'"';
		if (in_array($row['contactID'], $selected))
			$options .= ' selected';
		$options .= '>'. $row['lastname'] .',&nbsp;'. $row['firstname'] .'&nbsp;&nbsp;('. $row['company'] .')</option>';
	}
	return $options;
}

function newsrc_check($newsrc_name, $newsrc_abb, $newsrc_website,$con) {
	// Check to see if Source Exists
	$source_check = "SELECT sourceid FROM prospect_source WHERE source_name='". $newsrc_name ."' AND source_abb='". $newsrc_abb ."' AND source_website='". $newsrc_website ."' LIMIT 1";
	$result = $con->query($query);
	$source_num = mysqli_num_rows($source_result);
	while ($row = mysqli_fetch_object ($source_result)) {
		$sourceid = $row->sourceid;
	}
	return $sourceid;
}

// Get Page Category List
function getPageCatArray($con) {
	$query = 'SELECT * FROM page_cat WHERE display=1 ORDER BY dispOrder';
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$pCats[$row['pgcat_id']] = array('name'=>$row['pgcat_name'],'icon'=>$row['pgcat_icon']); 
	}
	return $pCats;
}

// Check For Ongoing Fee Billing Records
function checkOGF($checkFee,$con) {
	$query = 'SELECT * FROM ongoingFeesPaid WHERE ogfeeID='. $checkFee;
	$result = $con->query($query);
	if ($result) {
		$num_rows = mysqli_num_rows($result);
		if ($num_rows > 0) 
			$feeStarted = true;
		else
			$feeStarted = false;
	} else {
		$feeStarted = false;
	}
	return $feeStarted;
}

// Get Fee Recourrance Info
function getOGFrec($checkFee,$con) {
	$query = 'SELECT feeRecCalc FROM feeRec WHERE feeRecID='. $checkFee;
	$result = $con->query($query);
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$feeRecCalc = $row['feeRecCalc']; 
	}
	return $feeRecCalc;
}

// Get Project Hours
function getHours($projectID,$type,$con) {
	$filter = (($type == 'billable') ? ' AND billable=1' : (($type == 'non-billable') ? ' AND billable=1' : '' ));
	$query = 'SELECT SUM(h.hours) AS timeTotal FROM (SELECT timeAmount AS hours FROM projectTime WHERE projectID=' . $projectID .' AND timeDisp=1'. $filter .') h'; 
	$result = $con->query($query);
	$hrs = mysqli_fetch_array($result);
	return $hrs;
}

// Check Task Quick Display
function checkTaskDisplay($stat,$con) {
	$query = 'SELECT quickDisplay FROM taskStatus WHERE taskStatID='. $stat; 
	$result = $con->query($query);
	$arr = mysqli_fetch_array($result);
	$display = $arr['quickDisplay'];
	return $display;
}

// Get Project & Task Progress Bars
function getCurrentProgress($con) {
	$progress = '<ul class="dropdown-menu dropdown-tasks">';
	$query = "SELECT * FROM ((SELECT p.projectID AS id, p.projectName AS name, p.projectProgress AS progress, p.projectTargetComp AS due, p.table AS type, c.clientName AS client FROM projects p LEFT JOIN clients c ON (p.clientID = c.clientID) WHERE p.projectDisp=1 AND p.projectCurrent=1) UNION (SELECT t.taskID AS id, t.taskName AS name, t.taskProgress AS progress, t.dueDate AS due, t.table AS type, c.clientName AS client FROM tasks t LEFT JOIN projects p ON (t.projectID = p.projectID) LEFT JOIN clients c ON (p.clientID = c.clientID) WHERE t.display=1 AND t.taskStatus<=2)) f ORDER BY f.due DESC"; 
	$result = $con->query($query);
	$n = 1;
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		$link = (($row['type'] == 'project') ? '<a href="#" class="admin" data-toggle="modal" data-target="#adminModal" data-admintype="project-time" data-adminact="" data-page="'. $row['type'] .'" data-section="" data-editid="' . $row['id'] . '" title="Hours">' : '<a href="#" class="admin" data-toggle="modal" data-target="#adminModal" data-admintype="task-time" data-adminact="" data-page="'. $row['type'] .'" data-section="" data-editid="' . $row['id'] . '" title="Hours">');
		$class = (($row['type'] == 'project') ? 'progress-bar-info' : 'progress-bar-success');
		
		if ($n > 1) { $progress .= '<li class="divider"></li>'; }
		$progress .= '<li>'. $link .'<div><p class="clearfix"><strong>'. $row['name'] .'</strong> <em>'. $row['name'] .'</em><span class="pull-right text-muted">'. $row['progress'] .'% Complete</span></p><div class="progress progress-striped active"><div class="progress-bar '. $class .'" role="progressbar" aria-valuenow="'. $row['progress'] .'" aria-valuemin="0" aria-valuemax="100" style="width: '. $row['progress'] .'%"><span class="sr-only">'. $row['progress'] .'% Complete (success)</span></div></div></div></a></li>';
		$n++;
	}
	$progress .= '</ul><!-- /.dropdown-tasks -->';
	return $progress;
}

?>