<?php
 
class billing_plugin {

	var $plugin_name        = 'billing_plugin';
	var $class_name         = 'billing_plugin';

    /*
            This function is called when the plugin is loaded
    */
    function onLoad() {
        global $app;
        
		//* Events
        $app->plugin->registerEvent('client:client:on_after_update','billing_plugin','client_update');
		$app->plugin->registerEvent('client:client:on_after_insert','billing_plugin','client_insert');
		$app->plugin->registerEvent('client:client:on_after_delete','billing_plugin','client_delete');
		
		$app->plugin->registerEvent('client:reseller:on_after_update','billing_plugin','client_update');
		$app->plugin->registerEvent('client:reseller:on_after_insert','billing_plugin','client_insert');
		$app->plugin->registerEvent('client:reseller:on_after_delete','billing_plugin','client_delete');
		
		$app->plugin->registerEvent('billing:client:on_after_update','billing_plugin','client_update');
		$app->plugin->registerEvent('billing:client:on_after_insert','billing_plugin','client_insert');
		$app->plugin->registerEvent('billing:client:on_after_delete','billing_plugin','client_delete');
				
		$app->plugin->registerEvent('client:client_template:on_after_insert','billing_plugin','template_update');
		$app->plugin->registerEvent('client:client_template:on_after_update','billing_plugin','template_update');
		
    }

	function template_update($event_name, $page_form) {
		global $app, $conf;
		
		//* Add a recurring invoice_item_template record if it does not exist
		$invoice_item_template = $app->db->queryOneRecord("SELECT invoice_item_template_id, name FROM invoice_item_template WHERE type = 'Recurring' AND client_template_id = ".intval($page_form->id));
		if($invoice_item_template == false && isset($page_form->dataRecord['template_name'])) {
			$client_template_id = intval($page_form->id);
			$template_name = $app->db->quote($page_form->dataRecord['template_name']);
			$sql = "INSERT INTO `invoice_item_template` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `type`, `name`, `description`, `price`, `vat`, `unit`, `recur_months`, `client_template_id`) 
			VALUES(1, 1, 'riud', 'riud', '', 'Recurring', '$template_name', '', 0, 0, 'Item', 1, $client_template_id)";
			$app->db->query($sql);
		} else {
			if(isset($page_form->dataRecord['template_name']) && $invoice_item_template['name'] != $page_form->dataRecord['template_name']) {
				$template_name = $app->db->quote($page_form->dataRecord['template_name']);
				$sql = "UPDATE invoice_item_template SET name = '$template_name' WHERE invoice_item_template_id = ".$invoice_item_template['invoice_item_template_id'];
				$app->db->query($sql);
			}
		}
	}
	
	function client_insert($event_name, $page_form) {
		global $app, $conf;
		
		//* Add client_invoice_settings if not exist
		$rec = $app->db->queryOneRecord('SELECT client_id FROM invoice_client_settings WHERE client_id = '.$page_form->id);
		if(!isset($rec['client_id'])) {
			$sql = "INSERT INTO invoice_client_settings (client_id,sys_userid, sys_groupid,sys_perm_user,sys_perm_group,sys_perm_other,invoice_company_id,payment_email,payment_terms,payment_gateway,no_invoice_sending) 
			VALUES (".$page_form->id.",1, 1,'riud','riud','',1,'',0,'none','n')";
			$app->db->query($sql);
		}
	}
	
    function client_update($event_name, $page_form) {
		global $app, $conf;
		
		if(isset($page_form->dataRecord['template_master'])) {
			//* Get the existing
			$new_template_ids = $page_form->dataRecord['template_master'];
			if($page_form->dataRecord['template_additional'] != '') $new_template_ids .= '/'.trim($page_form->dataRecord['template_additional']);
			//echo $new_template_ids;
			$new_template_id_array = explode('/',$new_template_ids);
			
			$old_template_ids = $page_form->oldDataRecord['template_master'];
			//echo $old_template_ids;
			if($page_form->oldDataRecord['template_additional'] != '') $old_template_ids .= '/'.trim($page_form->oldDataRecord['template_additional']);
			$old_template_id_array = explode('/',$old_template_ids);
			
			if(is_array($new_template_id_array)) {
				foreach($new_template_id_array as $new_key => $new_template_id) {
					$old_key = array_search($new_template_id,$old_template_id_array);
					if($old_key !== false) {
						unset($new_template_id_array[$new_key]);
						unset($old_template_id_array[$old_key]);
					}
				}
			}
			
			foreach($new_template_id_array as $client_template_id) {
				$client_template_id = intval($client_template_id);
				if($client_template_id > 0) {
					// Get the invoice_item_template for this client_template
					$invoice_item_template = $app->db->queryOneRecord("SELECT * FROM invoice_item_template WHERE client_template_id = ".intval($client_template_id));
					
					// Insert the invoice_recurring_item based on that template
					$sql = "INSERT INTO `invoice_recurring_item` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `invoice_item_template_id`, `invoice_company_id`, `client_id`, `name`, `description`, `quantity`, `price`, `setup_fee`, `vat`, `recur_months`, `next_payment_date`, `start_date`, `end_date`, `type`, `advance_payment`, `active`) VALUES 
					(1, 1, 'riud', 'riud', '', ".$invoice_item_template['invoice_item_template_id'].", 1, ".$page_form->id.", '".$app->db->quote($invoice_item_template['name'])."', '".$app->db->quote($invoice_item_template['description'])."', 1, ".$invoice_item_template['price'].", ".$invoice_item_template['setup_fee'].", ".$invoice_item_template['vat'].", ".$invoice_item_template['recur_months'].", '".date('Y-m-d')."', '".date('Y-m-d')."', '0000-00-00', 'clienttemplate', 'y', 'y')";
					//die($sql);
					$app->db->query($sql);
				}
			}
			
			foreach($old_template_id_array as $client_template_id) {
				$client_template_id = intval($client_template_id);
				if($client_template_id > 0) {
					$sql = "SELECT invoice_recurring_item.invoice_recurring_item_id, invoice_item_template.invoice_item_template_id FROM invoice_recurring_item,invoice_item_template WHERE invoice_recurring_item.invoice_item_template_id = invoice_item_template.invoice_item_template_id AND invoice_item_template.client_template_id = $client_template_id AND invoice_recurring_item.client_id = ".$page_form->id;
					$rec = $app->db->queryOneRecord($sql);
					if($rec['invoice_recurring_item_id'] > 0) $app->db->query("DELETE FROM invoice_recurring_item WHERE invoice_recurring_item_id = ".$rec['invoice_recurring_item_id']);
				}
			}
			
			
		}
		
		//* Add client_invoice_settings if not exist
		$rec = $app->db->queryOneRecord('SELECT client_id FROM invoice_client_settings WHERE client_id = '.$page_form->id);
		if(!isset($rec['client_id'])) {
			$sql = "INSERT INTO invoice_client_settings (client_id,sys_userid, sys_groupid,sys_perm_user,sys_perm_group,sys_perm_other,invoice_company_id,payment_email,payment_terms,payment_gateway,no_invoice_sending) 
			VALUES (".$page_form->id.",1, 1,'riud','riud','',1,'',0,'none','n')";
			$app->db->query($sql);
		}
		
	}
	
	function client_delete($event_name, $page_form) {
		global $app, $conf;
		
		$app->db->query("DELETE FROM invoice_client_settings WHERE client_id = ".$page_form->id);
		
	}
	
}              	