
<?php
require ('../credentials.php');
 
 
$con=mysqli_connect(HOST, USERNAME, PASSWORD, DBNAME)or die("cannot connect"); 
        
if(isset($_REQUEST['user_id'])){

$mat_no =$_REQUEST['user_id'];
$level =$_REQUEST['level'];
$sex =$_REQUEST['sex'];
$department =$_REQUEST['department'];
$faculty =$_REQUEST['faculty'];
$month =$_REQUEST['month'];
$day =$_REQUEST['day'];
$who =$_REQUEST['who'];

$fac_query= " (target_faculty='All' or target_faculty='$faculty') ";
$dept_query= " (target_department='All' or target_department='$department') ";
$level_query= " (target_level='All' or target_level='$level') ";
$sex_query= " (target_sex='All' or target_sex='$sex') ";

if($who=='parent'){
	
	$queryToGetParentWards="SELECT * FROM parent_children JOIN student ON (parent_children.student_id=student.user_id) WHERE parent_id='$mat_no'";

	$result = mysqli_query($con, $queryToGetParentWards) or die("Error in Selecting " . mysqli_error($con));
	//create an array
	
	$fac_query= " (target_faculty='All' ";
	$dept_query= " (target_department='All' ";
	$level_query= " (target_level='All' ";
	$sex_query= " (target_sex='All' ";	

    while($row =mysqli_fetch_assoc($result)){
		$fac_query .= " or target_faculty='".$row['faculty']."'"; 
		$dept_query .= " or target_department='".$row['department']."'"; 
		$level_query .= " or target_level='".$row['level']."'"; 
		$sex_query .= " or target_sex='".$row['sex']."'"; 
		}
	
		$fac_query.= " ) ";
		$dept_query.= " ) ";
		$level_query.= " ) ";
		$sex_query.= " ) ";
		
		
	}

$newsByCategory= 	isset($_REQUEST['category']) ? " AND news.category='".$_REQUEST['category']."'" : "";
	
$sql= "SELECT * from news WHERE $fac_query AND $dept_query AND $level_query AND $sex_query AND target_user='$who' ";
$sql .=$newsByCategory;
$birthday=$day.'_'.$month;
$birthday2='ALL_'.$month;
$sql .= "UNION SELECT * from news WHERE birthday_target='$birthday' OR birthday_target= '$birthday2'";
$sql .=" ORDER BY date DESC";

//echo $sql;
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
//create an array
    $emparray = array();
    while($row =mysqli_fetch_assoc($result)){
		$emparray[] = $row;
		}
		
		
		
echo json_encode($emparray);

} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "no user_id found";
    echo json_encode($response);
}


mysqli_close($con);

?>
