<?php
/**
 * AgileBill - Open Billing Software
 *
 * This body of work is free software; you can redistribute it and/or
 * modify it under the terms of the Open AgileBill License
 * License as published at http://www.agileco.com/agilebill/license1-4.txt
 *
 * Originally authored by Tony Landis, AgileBill LLC
 *
 * Recent modifications by Deon George
 *
 * @author Deon George <deonATleenooksDOTnet>
 * @copyright 2009 Deon George
 * @link http://osb.leenooks.net
 *
 * @link http://www.agileco.com/
 * @copyright 2004-2008 Agileco, LLC.
 * @license http://www.agileco.com/agilebill/license1-4.txt
 * @author Tony Landis <tony@agileco.com>
 * @package AgileBill
 * @subpackage Core
 */

/**
 * The main AgileBill CORE Database MASS DELETE Method
 *
 * @uses CORE_trigger
 */

function CORE_database_mass_delete($VAR,$construct,$type) {
	global $C_auth,$C_debug;

	$db = &DB();

	if (isset($VAR['delete_id']))
		$ids = explode(',',preg_replace('/,$/','',$VAR['delete_id']));
	elseif (isset($VAR['id']))
		$ids = explode(',',preg_replace('/,$/','',$VAR['id']));

	# Check and see if the user is authorised to delete this records
	foreach ($ids as $i => $id) {
		$groups = $db->Execute(sqlSelect($db,'account_group','group_id',array('account_id'=>$id),'group_id'));

		$group = array();
		while (! $groups->EOF) {
			array_push($group,$groups->fields['group_id']);
			$groups->MoveNext();
		}
		# Verify the user has access to view this account
		foreach ($group as $gid) {
			if (! $C_auth->auth_group_by_id($gid)) {
				unset($ids[$i]);
				break;
			}
		}
	}

	# Nothing to delete
	if (! count($ids))
		return false;

	# Execute the query
	$result = $db->Execute(sqlDelete($db,$construct->table,array('id'=>$ids)));

	# Error reporting
	if ($result === false) {
		$C_debug->error(__FILE__,__METHOD__, $db->ErrorMsg());

		if (isset($construct->trigger[$type])) {
			include_once(PATH_CORE.'trigger.inc.php');
			$trigger = new CORE_trigger;

			$trigger->trigger($construct->trigger[$type],0,$VAR);
		}

	} else {
		# Delete any associated records
		if (isset($construct->associated_DELETE) && is_array($construct->associated_DELETE) && count($construct->associated_DELETE)) {
			foreach ($construct->associated_DELETE as $assoc) {
				$db->Execute(sqlDelete($db,$assoc['table'],array($assoc['field']=>$ids)));

				# Alert delete message
				if (! defined('AJAX')) {
					global $C_translate;

					$C_translate->value['CORE']['module_name'] = $C_translate->translate('name',$construct->module,'');
					$message = $C_translate->translate('alert_delete_ids','CORE','');
					$message = str_replace('%%module_name%%','', $message);
					$C_debug->alert($message);
				}

				if (isset($construct->trigger[$type])) {
					include_once(PATH_CORE.'trigger.inc.php');
					$trigger = new CORE_trigger;

					$trigger->trigger($construct->trigger[$type],1,$VAR);
				}
			}
		}
	}

	return $result;
}
?>