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

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

	$id				= $_POST["id"];

	error_log ( " id : " .$id );

	$pdo = getPDO ();
	
	if ( $pdo )
	{
		$result['status'] = 'OK';
		$s1 = null;
		if ( $id == -1 )
		{
			$s1 = $pdo->prepare ( "insert into task_master(title,start_date,recurrence, day_of_week) values ('New master task', NOW(), 0, -1 ) returning id" );
		}
		else
		{
			$dep_id			= $_POST["dep_id"];
			$title			= $_POST["title"];
			$description	= $_POST["description"];
			$start_date		= $_POST["start_date"];
			$end_date		= $_POST["end_date"];
			$recurrence		= $_POST["recurrence"];
			$day 			= $_POST["day"];
			$active			= $_POST["active"];
			$closing_type	= $_POST["closing_type"];
			$staff_members	= (isset($_POST['staff_members']) )? $_POST['staff_members'] : '';

			$sm_array  		= ( $staff_members != '' )? json_decode ( $_POST["staff_members"], true ) : null;

			if ( $recurrence == 0 || $recurrence == 1 )	// Unique or Daily
				$day = -2;	// N.A.

			error_log ( "active : " .$active );

			$s1 = $pdo->prepare ( "update task_master set dep_id=:dep_id, title=:title, description=:description, start_date=:start_date, end_date=:end_date, recurrence=:recurrence, day_of_week=:day, active=:active, closing_type=:closing_type where id=:id returning id" );
			$s1->bindParam ( ':id', 			$id 			);
			$s1->bindParam ( ':dep_id',			$dep_id			);
			$s1->bindParam ( ':title', 			$title 			);
			$s1->bindParam ( ':description', 	$description	);
			$s1->bindParam ( ':start_date', 	$start_date		);
			$s1->bindParam ( ':end_date', 		$end_date		);
			$s1->bindParam ( ':recurrence',		$recurrence		);
			$s1->bindParam ( ':day',			$day			);
			$s1->bindParam ( ':active',			$active			);
			$s1->bindParam ( ':closing_type',	$closing_type	);
		}

		if ( $s1->execute () == true )
		{
			$id = $s1->fetchColumn ();
			
			$result['id']		= $id;

			// Add entries to staff_master_link
			$s2 = $pdo->prepare ( 'delete from task_master_link where task_master_id=:task_master_id' );
			$s2->bindParam ( ':task_master_id', 	$id );
			if ( $s2->execute () == true )
			{
				if ( $sm_array != null )
				{
					for ( $i=0; $i<count($sm_array); $i++ )
					{
						$s2 = $pdo->prepare ( 'insert into task_master_link (task_master_id,staff_member_id) values (:task_master_id,:staff_member_id)' );
						$s2->bindParam ( ':task_master_id', 	$id 				);
						$s2->bindParam ( ':staff_member_id', 	$sm_array [$i] );
						if ( $s2->execute () != true )
						{
							$result['status'] 	= 'KO';
							break;			
						}
					}
				}
			}
		}
		else
			$result['status'] 	= 'KO';
	}

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