$repeatVLTestLastVLDate="$repeatVLTestLastVLDateYear-$repeatVLTestLastVLDateMonth-$repeatVLTestLastVLDateDay";
	}
	
	if($viralLoadTestingIndication=="vlTestingSuspectedTreatmentFailure") {
		$suspectedTreatmentFailureLastVLDateDay=validate($suspectedTreatmentFailureLastVLDateDay);
		$suspectedTreatmentFailureLastVLDateMonth=validate($suspectedTreatmentFailureLastVLDateMonth);
		$suspectedTreatmentFailureLastVLDateYear=validate($suspectedTreatmentFailureLastVLDateYear);
		$suspectedTreatmentFailureValue=validate($suspectedTreatmentFailureValue);
		$suspectedTreatmentFailureSampleTypeID=validate($suspectedTreatmentFailureSampleTypeID);
		$suspectedTreatmentFailureLastVLDate=0;
		$suspectedTreatmentFailureLastVLDate="$suspectedTreatmentFailureLastVLDateYear-$suspectedTreatmentFailureLastVLDateMonth-$suspectedTreatmentFailureLastVLDateDay";
	}
	
	//validate data
	$error=0;
	$error=checkFormFields("Form_Number::$formNumber Facility_Name::$facilityID Sample_Type::$sampleTypeID Current_Regimen::$currentRegimenID Treatment_Status::$treatmentStatusID Viral_Load_Testing::$viralLoadTestingID Pregnancy_Status::$pregnant Breastfeeding_Status::$breastfeeding Viral_Load_Testing::$viralLoadTestingID Whether_Patient_has_been_on_Treatment_for_last_6_months::$treatmentLast6Months");
	
	//to be edited: ensure lrCategory, lrEnvelopeNumber and lrNumericID are unique if supplied
	if($lrCategory && $lrEnvelopeNumber && $lrEnvelopeNumber!="Envelope #" && $lrNumericID) {
		if(getDetailedTableInfo2("vl_samples","lrCategory='$lrCategory' and lrEnvelopeNumber='$lrEnvelopeNumber' and lrNumericID='$lrNumericID' and id!='$modify' limit 1","id")) {
			$error.="<br /><strong>Duplicate ".($lrCategory=="V"?"Location":"Rejection")." ID '$lrCategory"."$lrEnvelopeNumber/$lrNumericID'.</strong><br />The ".($lrCategory=="V"?"Location":"Rejection")." ID <strong>$lrCategory"."$lrEnvelopeNumber/$lrNumericID</strong> was entered on <strong>".getFormattedDate(getDetailedTableInfo2("vl_samples","lrCategory='$lrCategory' and lrEnvelopeNumber='$lrEnvelopeNumber' and lrNumericID='$lrNumericID' and id!='$modify' limit 1","created"))."</strong> by <strong>".getDetailedTableInfo2("vl_samples","lrCategory='$lrCategory' and lrEnvelopeNumber='$lrEnvelopeNumber' and lrNumericID='$lrNumericID' and id!='$modify' limit 1","createdby")."</strong> <a href=\"#\" onclick=\"iDisplayMessage('/verify/preview/".getDetailedTableInfo2("vl_samples","lrCategory='$lrCategory' and lrEnvelopeNumber='$lrEnvelopeNumber' and lrNumericID='$lrNumericID' and id!='$modify' limit 1","id")."/1/noedit/')\">Click here to see the entry</a>.<br /> Kindly input this record with an alternative ".($lrCategory=="V"?"Location":"Rejection")." ID.<br />";
		}
	}

	//to be activated: ensure lrCategory, lrEnvelopeNumber and lrNumericID are supplied
	if(!$lrCategory && (!$lrEnvelopeNumber || $lrEnvelopeNumber==$default_envelopeNumber) && !$lrNumericID) {
		$error.="<br /><strong>".($lrCategory=="V"?"Location":"Rejection")." ID is Missing</strong><br />Kindly provide a ".($lrCategory=="V"?"Location or Rejection":"Rejection or Location")." ID<br />";
	}
	
	//to be edited: ensure envelope number is valid
	if($lrCategory && $lrEnvelopeNumber && $lrEnvelopeNumber!="Envelope #" && $lrNumericID) {
	$amplificationKitExpiryDateYear=validate($amplificationKitExpiryDateYear);
	$amplificationKitExpiryDate=0;
	$amplificationKitExpiryDate="$amplificationKitExpiryDateYear-$amplificationKitExpiryDateMonth-$amplificationKitExpiryDateDay";
	
	$assayDateDay=validate($assayDateDay);
	$assayDateMonth=validate($assayDateMonth);
	$assayDateYear=validate($assayDateYear);
	$assayDate=0;
	$assayDate="$assayDateYear-$assayDateMonth-$assayDateDay";
	
	$includeCalibrators=validate($includeCalibrators);

	//validate data
	$error=0;
	//$error=checkFormFields("Worksheet_Name::$worksheetName Worksheet_Reference_Number::$worksheetReferenceNumber Worksheet_Type::$worksheetType Machine_Type::$machineType Sample_Prep::$samplePrep Sample_Prep_Expiry_Date::$samplePrepExpiryDate Control::$control Control_Expiry_Date::$controlExpiryDate ".($type!="roche"?"Calibrator::$calibrator Calibrator_Expiry_Date::$calibratorExpiryDate":"")." Amplification_Kit::$amplificationKit Amplification_Kit_Expiry_Date::$amplificationKitExpiryDate");
	$error=checkFormFields("Worksheet_Reference_Number::$worksheetReferenceNumber Worksheet_Type::$worksheetType Machine_Type::$machineType Sample_Prep::$samplePrep Sample_Prep_Expiry_Date::$samplePrepExpiryDate Control::$control Control_Expiry_Date::$controlExpiryDate ".($type!="roche"?"Calibrator::$calibrator Calibrator_Expiry_Date::$calibratorExpiryDate":"")." Amplification_Kit::$amplificationKit Amplification_Kit_Expiry_Date::$amplificationKitExpiryDate");
	
	//is this Envelopes's envelopeNumber unique
	if(getDetailedTableInfo2("vl_samples_worksheetcredentials","worksheetType='$worksheetType' and worksheetName='$worksheetName' and worksheetReferenceNumber='$worksheetReferenceNumber' and id!='$modify' limit 1","id")) {
		$error.="<br />Another Worksheet with the same Name, Reference and Type i.e <strong>$worksheetName, $worksheetReferenceNumber and $worksheetType</strong> (resp) already exists.<br />Kindly select an alternative Name, Reference Number or Type<br />";
	}
	
	//input data
	if(!$error) {
		//log the changes
		//logTableChange("vl_samples_worksheetcredentials","worksheetName",$modify,getDetailedTableInfo2("vl_samples_worksheetcredentials","id='$modify'","worksheetName"),$worksheetName);
		logTableChange("vl_samples_worksheetcredentials","worksheetReferenceNumber",$modify,getDetailedTableInfo2("vl_samples_worksheetcredentials","id='$modify'","worksheetReferenceNumber"),$worksheetReferenceNumber);
		logTableChange("vl_samples_worksheetcredentials","worksheetType",$modify,getDetailedTableInfo2("vl_samples_worksheetcredentials","id='$modify'","worksheetType"),$worksheetType);
		logTableChange("vl_samples_worksheetcredentials","machineType",$modify,getDetailedTableInfo2("vl_samples_worksheetcredentials","id='$modify'","machineType"),$machineType);
		logTableChange("vl_samples_worksheetcredentials","samplePrep",$modify,getDetailedTableInfo2("vl_samples_worksheetcredentials","id='$modify'","samplePrep"),$samplePrep);
		logTableChange("vl_samples_worksheetcredentials","samplePrepExpiryDate",$modify,getDetailedTableInfo2("vl_samples_worksheetcredentials","id='$modify'","samplePrepExpiryDate"),$samplePrepExpiryDate);
$assayDateYear=validate($assayDateYear);

$includeCalibrators=validate($includeCalibrators);

if($proceed) {
	//validate data
	$samplePrepExpiryDate=0;
	$samplePrepExpiryDate="$samplePrepExpiryDateYear-$samplePrepExpiryDateMonth-$samplePrepExpiryDateDay";
	$bulkLysisBufferExpiryDate=0;
	$bulkLysisBufferExpiryDate="$bulkLysisBufferExpiryDateYear-$bulkLysisBufferExpiryDateMonth-$bulkLysisBufferExpiryDateDay";
	$assayDate=0;
	$assayDate="$assayDateYear-$assayDateMonth-$assayDateDay";

	//errors
	$error=0;
	$error=checkFormFields("Worksheet_Reference_Number::$worksheetReferenceNumber Worksheet_Type::$worksheetType Machine_Type::$machineType HI2CAP::$samplePrep HI2CAP_Expiry_Date::$samplePrepExpiryDate");
	
	//is this Envelopes's envelopeNumber unique
	if(getDetailedTableInfo2("vl_samples_worksheetcredentials","worksheetType='$worksheetType' and worksheetReferenceNumber='$worksheetReferenceNumber' limit 1","id")) {
		$error.="<br />Another Worksheet with the same Reference and Type i.e <strong>$worksheetReferenceNumber and $worksheetType</strong> (resp) already exists.<br />Kindly select an alternative Name, Reference Number or Type<br />";
	}
	
	//input data
	if(!$error) {
		//first time insertion
		mysqlquery("insert into vl_samples_worksheetcredentials 
						(worksheetReferenceNumber,worksheetType,samplePrep,samplePrepExpiryDate,
							bulkLysisBuffer,bulkLysisBufferExpiryDate,
							assayDate,includeCalibrators,machineType,created,createdby)
						values 
						('$worksheetReferenceNumber','$worksheetType','$samplePrep','$samplePrepExpiryDate',
				//array assignment
				$sampleResultHidden[]=getDetailedTableInfo2("vl_samples","vlSampleID='$q[$sampleIDField]'","id")."|".$worksheetUniqueID;
				$sampleResultCheckbox[]=getDetailedTableInfo2("vl_samples","vlSampleID='$q[$sampleIDField]'","id")."|".$worksheetUniqueID;
			} else {
				//array assignment
				$sampleResultHidden[]=$q["id"];
				$sampleResultCheckbox[]=$q["id"];
			}
		}
	}
}

if($saveDispatchDate) {
	//validate data
	$error=0;
	$error=checkFormFields("Dispatched_Date::$dispatchedDateYear Dispatched_Date::$dispatchedDateMonth Dispatched_Date::$dispatchedDateDay Facility::$facilityID");

	//ensure facility is valid
	if(!getDetailedTableInfo2("vl_facilities","id='$facilityID'","id")) {
		$error.="<br /><strong>Incorrect Facility '$facilityID'.</strong><br />Kindly select an existing Facility from the list or Request an Administrator to first add this Facility '$facilityID' to the System's Database before Proceeding.<br />";
	}
	
	//input data
	if(!$error) {
		//formate date
		$dispatchedDate=0;
		$dispatchedDate="$dispatchedDateYear-$dispatchedDateMonth-$dispatchedDateDay";
		
		//add or update
		$added=0;
		$updated=0;
$dispatchedDateYear=validate($dispatchedDateYear);
$facilityID=validate($facilityID);

$oldDispatchedDate=0;
$oldDispatchedDate=getDetailedTableInfo2("vl_forms_clinicalrequest_dispatch","refNumber='$refNumber' limit 1","dispatchDate");
$oldFacilityID=0;
$oldFacilityID=getDetailedTableInfo2("vl_forms_clinicalrequest_dispatch","refNumber='$refNumber' limit 1","facilityID");
$serialNumberStartValue=0;
$serialNumberStartValue=getDetailedTableInfo3("vl_forms_clinicalrequest","refNumber='$refNumber'","min(formNumber)","start");
$serialNumberEndValue=0;
$serialNumberEndValue=getDetailedTableInfo3("vl_forms_clinicalrequest","refNumber='$refNumber'","max(formNumber)","end");

if($saveDate) {
	//validate data
	$error=0;
	$error=checkFormFields("Dispatched_Date::$dispatchedDateYear Dispatched_Date::$dispatchedDateMonth Dispatched_Date::$dispatchedDateDay Facility::$facilityID Starting_Serial_Number::$serialNumberStart Ending_Serial_Number::$serialNumberEnd");
	
	//ensure ending serial number is greater than starting serial number
	if($serialNumberStart>=$serialNumberEnd) {
		$error.="Starting Serial Number should be less than the Ending Serial Number";
	}
	
	//ensure ending serial number does not exceed $serialNumberStart by more than $default_formsPerBook
	if(($serialNumberEnd-$serialNumberStart)>$default_formsPerBook) {
		$error.="Ending Serial Number should not exceed Starting Serial Number by more than $default_formsPerBook";
	}

	//ensure facility is valid
	if(!getDetailedTableInfo2("vl_facilities","id='$facilityID'","id")) {
		$error.="<br /><strong>Incorrect Facility '$facilityID'.</strong><br />Kindly select an existing Facility from the list or Request an Administrator to first add this Facility '$facilityID' to the System's Database before Proceeding.<br />";
	}
<?
//security check
if(!$GLOBALS['vlDC'] || !$_SESSION["VLEMAIL"]) {
	die("<font face=arial size=2>You must be logged in to view this page.</font>");
}

//validation
$modify=validate($modify);

if($saveEnvelope) {
	//validate data
	$error=0;
	$error=checkFormFields("Envelope_Number::$envelopeNumber Batch_Number::$batchNumber Facility_Name::$facilityID");

	//is this Envelopes's envelopeNumber unique
	if(getDetailedTableInfo2("vl_envelopes","envelopeNumber='$envelopeNumber' and id!='$modify' limit 1","id")) {
		$error.="<br />Another Envelope with the same Envelope Number <strong>$envelopeNumber</strong> already exists.<br />Kindly provide an alternative Envelope Number<br />";
	}
	
	//is this Batch's batchNumber unique
	if(getDetailedTableInfo2("vl_envelopes","batchNumber='$batchNumber' and id!='$modify' limit 1","id")) {
		$error.="<br />Another Envelope with the same Batch Number <strong>$batchNumber</strong> already exists.<br />Kindly provide an alternative Batch Number<br />";
	}
	
	//input data
	if(!$error) {
		//formate date
		$currentDateTime=0;
		$currentDateTime="$receivedDateYear-$receivedDateMonth-$receivedDateDay ".getFormattedTime(getDetailedTableInfo2("vl_envelopes","id='$modify' limit 1","created"));

		//log changes
//$artNumber=preg_replace("/\-/s","",$artNumber);
//$artNumber=preg_replace("/\./s","",$artNumber);
//$artNumber=preg_replace("/\//s","",$artNumber);
//$artNumber=preg_replace("/\s/s","",$artNumber);

$otherID=validate($otherID);
$gender=validate($gender);
$dateOfBirthDay=validate($dateOfBirthDay);
$dateOfBirthMonth=validate($dateOfBirthMonth);
$dateOfBirthYear=validate($dateOfBirthYear);
$patientPhone=validate($patientPhone);

if($savePatient) {
	//validate data
	$error=0;
	$error=checkFormFields("Gender::$gender");

	//is both ART and Other ID Number are missing
	if(!$artNumber && !$otherID) {
		$error.="<br /><strong>ART Number is Missing</strong><br />Kindly provide an ART Number<br />";
	}
	
	//date of birth missing?
	/* 7/Sept/15
	* Request from vbigira@clintonhealthaccess.org
	* Just got another urgent request from CPHL: They would like the VL database to have an additional entry for patients 
	* whose date of birth or age is not given by the facility. This was initially a 'must-have' option but with massive 
	* numbers of forms returning without this information, they would like to have the option of leaving it as a "Left blank". 
	* This can be put after the age variable.
	if(!$dateOfBirthDay || !$dateOfBirthMonth || !$dateOfBirthYear) {
		$error.="<br /><strong>Date of Birth Missing</strong><br />Kindly provide the Date of Birth<br />";
if($envelopeNumberFrom && $envelopeNumberTo) {
	$searchQueryFrom=validate(vlDecrypt($envelopeNumberFrom));
	$searchQueryTo=validate(vlDecrypt($envelopeNumberTo));
	$searchQueryCurrentPosition=getDetailedTableInfo3("vl_samples y","y.vlSampleID='".getDetailedTableInfo2("vl_samples","id='$id'","vlSampleID")."'","(select count(x.id) from vl_samples x where concat(x.lrCategory,x.lrEnvelopeNumber)>='$searchQueryFrom' and concat(x.lrCategory,x.lrEnvelopeNumber)<='$searchQueryTo' and x.vlSampleID<=y.vlSampleID order by if(x.lrCategory='',1,0),x.lrCategory, if(x.lrEnvelopeNumber='',1,0),x.lrEnvelopeNumber, if(x.lrNumericID='',1,0),x.lrNumericID,x.created desc)","position");
	if($searchQueryCurrentPosition) {
		$searchQueryNextPosition=getDetailedTableInfo2("vl_samples","id not in (select sampleID from vl_samples_verify) and concat(lrCategory,lrEnvelopeNumber)>='$searchQueryFrom' and concat(lrCategory,lrEnvelopeNumber)<='$searchQueryTo' order by if(lrCategory='',1,0),lrCategory, if(lrEnvelopeNumber='',1,0),lrEnvelopeNumber, if(lrNumericID='',1,0),lrNumericID,created desc limit $searchQueryCurrentPosition,1","id");
		if(!$searchQueryNextPosition) {
			$searchQueryNextPosition=getDetailedTableInfo2("vl_samples","id not in (select sampleID from vl_samples_verify) and id!='$id' and concat(lrCategory,lrEnvelopeNumber)>='$searchQueryFrom' and concat(lrCategory,lrEnvelopeNumber)<='$searchQueryTo' order by if(lrCategory='',1,0),lrCategory, if(lrEnvelopeNumber='',1,0),lrEnvelopeNumber, if(lrNumericID='',1,0),lrNumericID,created desc limit 1","id");
		}
	}
}

if($saveChangesReturn || $saveChangesProceed) {
	//validate data
	$error=0;
	$error=checkFormFields("Received_Status::$outcome");

	//is gender male and pregnancy set to yes?
	if($outcome=="Rejected" && !$outcomeReasonsID) {
		$error.="<br /><strong>Received Status is Rejected but no Rejection Reason Provided.<br />";
	}

	//input data
	if(!$error) {
		//log status

    //MODEL:: WHERE THE DATABASE CAPTURES THE APPROVAL DETAILS .....STARTS HERE
		mysqlquery("insert into vl_samples_verify 
						(sampleID,outcome,outcomeReasonsID,comments,created,createdby) 
						values 
						('$id','$outcome','$outcomeReasonsID','$comments','$datetime','$trailSessionUser')");