<?php
	require_once '../../autoload.php';

	$result = array (
			"status"	=> 'KO',
			"id"	=> -1
	);

	$task_id		= $_POST["task_id"];

	error_log ( " task_id : " .$task_id );

	$pdo = getPDO ();
	
	if ( $pdo )
	{
		$result['status'] 	= 'OK';
		$result['task_id']  = -1;
		
		if ( $task_id != -1 )
		{
			$comment			= $_POST["comment"];
			$status_id			= $_POST["status_id"];
			$staff_member_id	= $_POST["staff_member_id"];

			$s1 = $pdo->prepare ( "update task_link set status_id=:status_id, comment=:comment, status_date=NOW() where task_id=:task_id and staff_member_id=:staff_member_id returning task_id" );
			$s1->bindParam ( ':task_id', 			$task_id 			);
			$s1->bindParam ( ':status_id', 			$status_id 			);
			$s1->bindParam ( ':staff_member_id',	$staff_member_id 	);
			$s1->bindParam ( ':comment', 			$comment 			);

			if ( $s1->execute () == true )
			{
				$result['status'] 	= 'OK';			
				$result['task_id']  = $s1->fetch(PDO::FETCH_ASSOC)['task_id'];

				$closing_type = -1;

				$s2 = $pdo->prepare ( "select closing_type from task t, task_master tm where t.task_master_id =tm.id and t.id=:task_id" );
				$s2->bindParam ( ':task_id', $task_id );

				if ( $s2->execute () == true )
				{
					$d2 = $s2->fetchAll ( PDO::FETCH_ASSOC );
					if ( count($d2) > 0 )
					{
						$closing_type = $d2[0]['closing_type'];
						error_log ( 'Closing type : ' .$closing_type );
						$sql = '';
						switch ( $closing_type )
						{
							case '0':
								$sql = "select case WHEN count(*)>0 then 1 else 0 end as res from task_link where status_id=4 and task_id=:task_id";
								break;

							case '1':
								$sql = "select case WHEN count(*)=0 then 1 else 0 end as res from task_link where status_id!=4 and task_id=:task_id";
								break;
						}

						if ( strlen($sql) > 0 )
						{
							$s3 = $pdo->prepare ( $sql );
							$s3->bindParam ( ':task_id', $task_id );

							if ( $s3->execute () == true )
							{
								$d3 = $s3->fetchAll ( PDO::FETCH_ASSOC );
								if ( count($d3) > 0 )
								{
									$sql = '';
									if ( $d3[0]['res'] == '1' )	// Ok, close task
										$sql = 'update task set status_id=4, closing_date=NOW() where id=:task_id';
									else
										$sql = 'update task set status_id=3, closing_date=null where id=:task_id';

									error_log ( "SQL : " .$sql );

									$s4 = $pdo->prepare ( $sql );
									$s4->bindParam ( ':task_id', $task_id );

									if ( $s4->execute () == false )
									{
										$result['status'] 	= 'OK';			
									}
								}

							}
						}
					}
				}
			}
		}

		
	}

	header('Content-type: application/json');
	
	echo json_encode ( $result );
?>