<?php  
  include "include.php";
  session_start();

  
	$_ENV['MostSuitable'] = array();
	$_ENV['WellSuitable'] = array();
	$_ENV['Suitable'] = array();

$json = stripslashes($_GET["arrays"]);
$arrays	= json_decode($json);
$SelectedNeeds = $arrays->impairments;
$length = count($SelectedNeeds);

$SuitablePhones = array();
$FeaturesArray = array();
$PrePhonesArray = array();


$con = get_database_connection();
  
  //create array with values between commas of the selected values
if ($length == 0) {
	$_ENV['MostSuitable'] = $_SESSION['Phones'];
}
 
// loop through the SelectedNeeds  
for($x=0;$x<$length;$x++)
{
	
	$need = $SelectedNeeds[$x];

	//find the related FeatureID for each selected Requirement
	$result = mysqli_query($con,"SELECT Feature.FeatureID, Grouping FROM FeatureRequirement, Feature WHERE FeatureRequirement.FeatureID = Feature.FeatureID AND RequirementID ='".$need."' AND NOT DisplayOnly='Yes'");
	
	//echo "SELECT Feature.FeatureID, Grouping FROM FeatureRequirement, Feature WHERE FeatureRequirement.FeatureID = Feature.FeatureID AND RequirementID ='".$need."' AND NOT DisplayOnly='Yes'";
	
	$FeaturesArray[] = array();
	$SuitablePhones[] = array();
	$PrePhonesArray[] = array();
	$PhonesArray[] = array(1);

	//place it in the Ranked Features Array, along with its rank
	while($row = mysqli_fetch_array($result)){
		$ID = $row['FeatureID'];
		$grouping = $row['Grouping'];
		if ($grouping) $FeaturesArray[$x][] = $grouping;
		else $FeaturesArray[$x][] = $ID;
	}
	//Remove all duplicate entries
	$FeaturesArray[$x] = array_unique($FeaturesArray[$x]);

	
		
	
	foreach($FeaturesArray[$x] as $y){
		$searchQuery = "SELECT DISTINCT PhoneID FROM PhoneFeature WHERE FeatureID ='".$y."' AND Value !='0'";
		$result2 = mysqli_query($con,$searchQuery);
		//insert the first ranked phones into the PrePhonesArray
		while($row = mysqli_fetch_array($result2)){
			$PrePhonesArray[$x][] = $row['PhoneID'];
		}

		$searchQuery = "SELECT DISTINCT PhoneID FROM PhoneFeature, Feature WHERE Grouping ='".$y."' AND Feature.FeatureID = PhoneFeature.FeatureID AND Value !='0'";
	//echo $searchQuery;
		$result2 = mysqli_query($con,$searchQuery);
		//insert the first ranked phones into the PrePhonesArray
		while($row = mysqli_fetch_array($result2)){
			$PrePhonesArray[$x][] = $row['PhoneID'];
		}
		
	}
		
	//find the length of the FeaturesArray (aka the number of related features)
	$noOfFeatures = count($FeaturesArray[$x]);
	
	//find the count of the PhoneIDs in the SuitablePhonesArray
	$PhoneIDOccurence = array_count_values($PrePhonesArray[$x]);
	
	//If the length is the same as the count we have a MATCH
	$PhonesArray[$x+1] = array_keys($PhoneIDOccurence, $noOfFeatures);

}

	
	$_ENV['FirstPriority'] = array();
	$_ENV['SecondPriority'] = array();
	$_ENV['ThirdPriority'] = array();
	$_ENV['FourthPriority'] = array();
	$_ENV['FifthPriority'] = array();

	$tier1 = array();
	$tier2 = array();
	$tier3 = array();

if ($length >= 2) $Phones1And2 = array_intersect($PhonesArray[1], $PhonesArray[2]);

switch ($length) {
	
	case 0:
	   $tier1 = $_SESSION['Phones'];
	break;
	
	case 1:
		$tier1 = array_unique($PhonesArray[1]);
	break;	
	
	case 2: 
		$tier1 = $Phones1And2;
		$tier2 = array_diff($PhonesArray[1], $tier1);
	break;
	
	case 3:
		$tier1 = array_intersect($Phones1And2, $PhonesArray[3]);
		$tier2 = array_diff($Phones1And2, $tier1);
		$tier3 = array_diff($PhonesArray[1], $tier1, $tier2);
	break;
	
	case 4:
		$tier1 = array_intersect($Phones1And2, $PhonesArray[3], $PhonesArray[4]);
		$tier2 = array_diff($Phones1And2, $tier1);
		$tier3 = array_diff($PhonesArray[1], $tier1, $tier2);
	break;
		
	case 5:
		$tier1 = array_intersect($Phones1And2, $PhonesArray[3], $PhonesArray[4], $PhonesArray[5]);
		$tier2 = array_diff($Phones1And2, $tier1);
		$tier3 = array_diff($PhonesArray[1], $tier1, $tier2);
	break;
		
}
/** 

		Create Query Strings 
**/
	
		$_ENV['MostSuitable'] = $tier1;
		$_ENV['WellSuitable'] = $tier2;
		$_ENV['Suitable'] = $tier3;
	

$_SESSION['Most'] = array_intersect($_ENV['MostSuitable'],$_SESSION['Phones']);
$_SESSION['Well'] = array_intersect($_ENV['WellSuitable'],$_SESSION['Phones']);
$_SESSION['Suit'] = array_intersect($_ENV['Suitable'],$_SESSION['Phones']);

$_ENV['MostSuitable'] = $_SESSION['Most'];
$_ENV['WellSuitable'] = $_SESSION['Well'];
$_ENV['Suitable'] = $_SESSION['Suit'];

	
	foreach($_ENV['MostSuitable'] as $array_value){
		$query1String = "PhoneID = '".$array_value."' OR ";
		$string1 = $string1." ".$query1String;
	}
	
	
	//create Second Priority Query String
	foreach($_ENV['WellSuitable'] as $array_value){
	$query2String = "PhoneID = '".$array_value."' OR ";
	$string2 = $string2." ".$query2String;
	}
	
	foreach($_ENV['Suitable'] as $array_value){
	$query3String = "PhoneID = '".$array_value."' OR ";
	$string3 = $string3." ".$query3String;
	}
	
	
	$phoneCountID = 0;
	//FIRST RANKED PHONES			
	
	$result = mysqli_query($con,"SELECT COUNT(PhoneID) AS PhoneCount, Brand FROM `Phone`  WHERE ".$string1."PhoneID = '0' GROUP BY `Brand`");
	
	while($row = mysqli_fetch_array($result)){
		$phoneCountID++;
    $count = $row['PhoneCount'];
	$total = $total + $count;
	}
	echo "
	<div class='phone-panel'>
<div class='phone-listing'>
        <h3>Phone Recommendations</h3>
        <div class='most-suitable-box'>
        <div class='most-suitable-header'>
<div class='suitable-text'>First (".$total.")</div></div>
        <ul id='double' class='phone'>
            <span class='code-comment'><!--2 col--></span>";
	
	
	
	//Display the Brand Names, followed by the count of the models in brackets
	$result = mysqli_query($con,"SELECT COUNT(*) AS PhoneCount, Brand FROM `Phone`  WHERE ".$string1."PhoneID = '0' GROUP BY `Brand`");
	while($row = mysqli_fetch_array($result)){
			$count = $row['PhoneCount'];
			$brand = $row['Brand'];
			echo "<li class='phone'><a href='#' id='phonescroller.php?Brand=".$brand."&Priority=1&arrays=".$json."'>".$brand." (".$count.")</a></li>";
			
			
	}
	
			echo"</ul>";
			
			echo "</div>";  
		
			
			

	 //SECOND RANKED PHONES 
	 $result2 = mysqli_query($con,"SELECT COUNT(PhoneID) AS PhoneCount, Brand FROM `Phone`  WHERE ".$string2." PhoneID = '0' GROUP BY `Brand`");
	
	while($row = mysqli_fetch_array($result2)){
		$phoneCountID++;
    $count = $row['PhoneCount'];
	$total2 = $total2 + $count;
	
	
	
			$result2b = mysqli_query($con,"SELECT PhoneID, Brand FROM `Phone`  WHERE ".$string2." PhoneID = '0' AND (`Brand` ='".$brand."')");
			
	//generate query strings that is used to display the phones in boxes
			while($row = mysqli_fetch_array($result2b)){
				$phoneid = $row['PhoneID'];
				$phonequerystring2 = $phonequerystring2."OR PhoneID = '".$phoneid."' ";
				$brand = $row['Brand'];
			}
			$phonequerystring2 = $phonequerystring2." ) AND Brand = '".$brand."'";
	}
	echo "<div class='well-suited-box'>
        <div class='well-suited-header'>
<div class='suitable-text'>Second (".$total2.")</div></div>
        <ul id='double' class='phone'>
            <span class='code-comment'><!--2 col--></span>";
			
			$result = mysqli_query($con,"SELECT PhoneID, Brand FROM `Phone`  WHERE ".$string2." PhoneID = '0' AND (`Brand` ='".$brand."')");
	
			
			
	
	
	$result2c = mysqli_query($con,"SELECT COUNT(*) AS PhoneCount, Brand FROM `Phone`  WHERE ".$string2."PhoneID = '0' GROUP BY `Brand`");
	while($row = mysqli_fetch_array($result2c)){
			$count = $row['PhoneCount'];
			$brand = $row['Brand'];
			echo "<li class='phone'><a href='#' id='phonescroller.php?Brand=".$brand."&Priority=2&arrays=".$json."'>".$brand." (".$count.")</a></li>";
			
	}	
	
echo"</ul>";
	echo "</div>"; 

 //THIRD RANKED PHONES 
	 
	 $result3a = mysqli_query($con,"SELECT COUNT(*) AS PhoneCount, Brand FROM `Phone`  WHERE ".$string3."PhoneID = '0' GROUP BY `Brand`");
	
	while($row = mysqli_fetch_array($result3a)){
    $count = $row['PhoneCount'];
	$total3 = $total3 + $count;
	}
	echo "<div class='least-suited-box'>
        <div class='least-suited-header'>
<div class='suitable-text'>Third (".$total3.")</div></div>
        <ul id='double' class='phone'>
            <span class='code-comment'><!--2 col--></span>";
	
	
	$result3b = mysqli_query($con,"SELECT COUNT(*) AS PhoneCount, Brand, PhoneID FROM `Phone`  WHERE ".$string3."PhoneID = '0' GROUP BY `Brand`");
	while($row = mysqli_fetch_array($result3b)){
			$count = $row['PhoneCount'];
			$brand = $row['Brand'];
			$phoneid = $row['PhoneID'];
			echo "<li class='phone'><a href='#' id='phonescroller.php?Brand=".$brand."&Priority=3&arrays=".$json."'>".$brand." (".$count.")</a></li>";
	}

echo"</ul></div></div>";	

echo "<div id='populate-phones'></div>";

echo "</div>";
echo "</div>";
	?>
