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

	$result = array (
			"status"	=> 'KO',
			"results"	=> array ()
	);

	$doc_id		= $_POST["doc_id"];
	$action_id	= $_POST["action_id"];
	$toAdd 		= json_decode ( $_POST["toadd"], true );
	$toRemove 	= json_decode ( $_POST["toremove"], true );

	error_log ( " doc_id : " .$doc_id );
	error_log ( " action_id : " .$action_id );
	error_log ( " nb values to add : " .count($toAdd) );
	error_log ( " nb values to remove : " .count($toRemove) );

	$pdo = getPDO ();
	
	if ( $pdo )
	{
		$result['status'] = 'OK';

		for ($i=0; $i<count($toRemove); $i++ )
		{
			error_log ( "remove : " .$toRemove [$i]);
			$s0 = $pdo->prepare ( "delete from action_status_link where document_id = :doc_id and staff_member_id=:staff_id and action_id=:action_id" );
			$s0->bindParam ( ':doc_id', 	$doc_id 	);
			$s0->bindParam ( ':staff_id', 	$toRemove[$i] 	);
			$s0->bindParam ( ':action_id', 	$action_id 	);

			if ( $s0->execute () != true )
				$result['status'] = 'KO';
		}

		for ($i=0; $i<count($toAdd); $i++ )
		{
			error_log ( "insert : " .$toAdd [$i]);
			$s1 = $pdo->prepare ( "insert into action_status_link ( document_id, staff_member_id, action_id, date ) select :doc_id, :staff_id, :action_id_2, NOW() where not exists ( select 1 from action_status_link where document_id=:doc_id and staff_member_id=:staff_id and action_id=:action_id_1)" );
			$s1->bindParam ( ':doc_id', 	$doc_id );
			$s1->bindParam ( ':staff_id', 	$toAdd [$i] );
			$s1->bindParam ( ':action_id_1',$action_id );
			$s1->bindParam ( ':action_id_2',$action_id );

			if ( $s1->execute () != true )
				$result['status'] = 'KO';
		}
	}

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