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

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

	if ( isset ( $_POST['acc_ids']) && is_array($_POST['acc_ids'])) 
    	$acc_ids = $_POST['acc_ids'];

    $emails_str = "";

    if ( isset ( $_POST['emails']) && is_array($_POST['emails'])) 
	{
    	$emails = $_POST['emails'];

    	$emails_str = implode(',', $emails );
    }

    $mail_id	= (isset($_POST['mail_id']))? $_POST['mail_id'] : false;
    $enabled 	= (isset($_POST['enabled']))? $_POST['enabled'] : false;

	$pdo = getPDO ();
		
	if ( $pdo )
	{
		$sql = "update alertmail set enabled=".$enabled.", mail_to=:emails where mail_id=:mail_id";
		$s0 = $pdo->prepare ( $sql );
		$s0->bindParam ( ':emails',		$emails_str );
		$s0->bindParam ( ':mail_id',	$mail_id );

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

			$sql = "delete from alertmail_account_link where alert_mail_id=:mail_id";
			$s1 = $pdo->prepare ( $sql );
			$s1->bindParam ( ':mail_id',	$mail_id );

			if ( $s1->execute () )
			{
				foreach ( $acc_ids as $account_id )
				{
					$sql = "insert into alertmail_account_link (alert_mail_id, account_id) values (:mail_id, :account_id)";
					$s2 = $pdo->prepare ( $sql );
					$s2->bindParam ( ':mail_id',	$mail_id );
					$s2->bindParam ( ':account_id',	$account_id );

					if ( $s2->execute () )
					{

					}
				}
			}

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