<?php
/*+***********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 *************************************************************************************/

class RoundRobinHandler extends VTEventHandler {

	function handleEvent($eventName, $entityData) {
		global $log, $adb;
		if($eventName == 'vtiger.entity.aftersave.final') {
			$record = $entityData->getId();
			$moduleName = $entityData->getModuleName();
			if ($moduleName != 'Campaigns') return false;

			$field_asignar_a = "cf_1001";

			$aux_asignados = array();
			$roundrobin_logic = array();
			
			$model = Vtiger_Record_Model::getInstanceById($record, "Campaigns");
			$asignados = explode(" |##| ", decode_html($model->get($field_asignar_a)));

			// $adb->setDebug(true);
			$change = false;
			$rs = $adb->pquery("SELECT roundrobin_userid FROM vtiger_campaignscf WHERE campaignid = ?", array($record));
			$aux_roundrobin = $users_roundrobin = decode_html($adb->query_result($rs, 0, 'roundrobin_userid'));
			
			if ( !empty($users_roundrobin) ) {
				$users_roundrobin = json_decode($users_roundrobin, true);
			} else {
				$users_roundrobin = array();
			}

			sort($asignados);
			foreach ($asignados as $id) {
				$rs = $adb->pquery("SELECT unidad FROM vtiger_users where id = ?", array($id));
				$unidades = explode(" |##| ", decode_html($adb->query_result($rs, 0, 'unidad')));
				foreach ($unidades as $unidad) {
					if (empty($unidad)) {
						$unidad = "SIN UNIDAD";
					}
					$aux_asignados[$unidad][] = $id;
					$roundrobin_logic[$unidad] = 0;
				}
			}
			
			if ( $aux_asignados != $users_roundrobin ) {
				$save_roundrobin = (object) $aux_asignados;
				$save_roundrobin = json_encode($save_roundrobin);

				$save_roundrobin_logic = (object) $roundrobin_logic;
				$save_roundrobin_logic = json_encode($save_roundrobin_logic);

				$adb->pquery("UPDATE vtiger_campaignscf set roundrobin_userid = ?, roundrobin_logic = ? WHERE campaignid = ?", array($save_roundrobin, $save_roundrobin_logic, $record));
			}
		}
	}
}