<?php

require_once __DIR__ . '/db_config.php';

$response = array();
$response["tasks"] = array();
$response["assigns"] = array();
$response["employees"] = array();
$tasks=array();
$employess=array();

if ( isset($_POST["mail"]) && isset($_POST["cname"]) && isset($_POST["role"]) ){
 
$mail= $_POST['mail'];
$cname=$_POST["cname"];
$role=$_POST["role"];
$id=$_POST["id"];
$tid=$_POST["tid"];
$status=$_POST["status"];
$responsible=$_POST["responsible"];
$employee=$_POST["employee"];

$tasks=json_decode($_POST["list"],true);

$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE) or die(mysql_error());

date_default_timezone_set('Asia/Calcutta');
$date=date('Y-m-d');

$taskQuery="SELECT * FROM tm_all_tasks WHERE t_project_id='$id' and (";

if($status=="unassigned"){
        $taskQuery=$taskQuery." t_status='unassigned' ";
}else if($status=="assigned"){
        $taskQuery=$taskQuery." t_status='assigned' ";
}else if($status=="underprogress"){
    $taskQuery=$taskQuery." (t_status='underprogress' AND t_end_date>='$date')";
}else if($status=="completed"){
        $taskQuery=$taskQuery." (t_status='completed' OR (t_status='underprogress' AND t_progress=90) )";
}else if($status=="late"){
    $taskQuery=$taskQuery." (t_status='underprogress' AND t_end_date<'$date') ";
}else if($status=="stalled"){
        $taskQuery=$taskQuery."  t_status='stalled' ";
}else if($status=="stopped"){
        $taskQuery=$taskQuery."  t_status='stopped' ";
}

if(count($tasks)!=0){
    $taskQuery=$taskQuery." OR (task_id='".implode("' OR  task_id='",$tasks)."'))";
}else{
   $taskQuery=$taskQuery." )"; 
}



if(!empty($employee)){
    $taskQuery=$taskQuery." employee='$employee' ";
}

    /*$taskQuery=$taskQuery." AND p_deleted='no' AND m_deleted='no' AND l_deleted='no' AND t_deleted='no' ";*/

$taskQuery=$taskQuery." GROUP BY task_id";

$taskResult=mysqli_query($con,$taskQuery);
if(!empty($taskResult) && mysqli_num_rows($taskResult) > 0){
    while ($row = mysqli_fetch_array($taskResult,MYSQLI_ASSOC)) {
        array_push($response["tasks"], $row);
        array_push($tasks, $row["task_id"]);
        array_push($employess,$row["employee"]);
    }
}

if(count($tasks)!=0){
$assignQuery="SELECT * FROM tm_all_assign WHERE (a_task_id='".implode("' OR  a_task_id='",$tasks)."')";
$assignResult=mysqli_query($con,$assignQuery);
if(!empty($assignResult) && mysqli_num_rows($assignResult) > 0){
    while ($row = mysqli_fetch_array($assignResult,MYSQLI_ASSOC)) {
        array_push($response["assigns"], $row);
    }
}
}

$employess=array_unique($employess);
$employeeQuery="SELECT employeename,emailid FROM signupdetails WHERE (emailid='".implode("' OR  emailid='",$employess)."')";
$employeeResult=mysqli_query($con,$employeeQuery);
if(!empty($employeeResult) && mysqli_num_rows($employeeResult) > 0){
    while ($row = mysqli_fetch_array($employeeResult,MYSQLI_ASSOC)) {
        array_push($response["employees"], $row);
    }
}

}

echo json_encode($response);


?>