<?php
include 'common.php';

function DeleteAccountMail($dbhandle, $group_mail_id)
{
	$split = ",";
	$arrMailIds = explode($split, $group_mail_id);
	for($i=0;$i< sizeof($arrMailIds);$i++)
	{
		//Delete Mail
		$query = "DELETE from mail_box_account where id=".$arrMailIds[$i];
		$result = @mysqli_query($dbhandle,$query);
		if($result != 1)
		{		
			return false;
		}
	}
	
	return true;
}

function RemoveAccountMail($group_mail_id, $account_id, $login_key)
{
	$dbhandle = DB_Connect();
	//Select DB
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");
	
	
	if(!CheckLoginKey($dbhandle, $account_id, $login_key))
	{
		PrintLoginKeyError();
		mysqli_close($dbhandle);
		return;
	}
	
	
	$response = "REMOVE_MAIL_FAILED";
	$error = "";

	$delete_mail = DeleteAccountMail($dbhandle, $group_mail_id);
	if ($delete_mail)
	{
		$response = "REMOVE_MAIL_OK";
	}
	else
	{
		//$error = mysqli_error($dbhandle);
		$error = "Delete Mail Failed";
	}
	
	 mysqli_close($dbhandle);
 
    $isXmlHttpRequest = (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) ?
    (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false: false;
    ($isXmlHttpRequest) ? header('Content-type: application/json') : header('Content-type: text/plain');
 
    echo json_encode(array('result'=>$response,'error'=>$error,'list_mail_id'=>$group_mail_id));
}

$json = json_decode(file_get_contents('php://input'));
$group_mail_id = $json->group_mail_id;
$account_id = $json->account_id;
$login_key = $json->login_key;
//

if(CheckValidatedServerIP())
{
	RemoveAccountMail($group_mail_id, $account_id, $login_key);
}
else
{
	$response = "INVALIDATED_SERVER";
	$error = "CheckValidatedServerIP ERROR";
	$isXmlHttpRequest = (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) ?
	(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false: false;
	($isXmlHttpRequest) ? header('Content-type: application/json') : header('Content-type: text/plain'); 
 
	echo json_encode(array(	'result'=>$response,'error'=>$error	));
}

?>