<?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.
 *************************************************************************************/
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);

//Opensource fix for tracking email access count
// chdir(dirname(__FILE__). '/../');

require_once 'includes/Loader.php';
require_once 'include/utils/utils.php';

vimport('includes.http.Request');
vimport('includes.runtime.Globals');
vimport('includes.runtime.BaseModel');
vimport('includes.runtime.Controller');
vimport('includes.runtime.LanguageHandler');

vimport ('includes.runtime.Globals');
require_once 'include/utils/utils.php';
require_once 'modules/Google/views/List.php';
require_once 'modules/Users/Users.php';
// Google_List_View::renderSyncUI(new Vtiger_Request($arr));
global $current_user, $adb;
error_reporting("");
ini_set('error_log','CreantisCalendarSyncLog.txt');

//no sincronizar a un usuario hasta que alla terminado
$sql = "SELECT userid FROM vtiger_google_oauth2 WHERE service = 'GoogleCalendar' order by userid asc;";
$result = $adb->pquery($sql, array());

//actualiza vtiger_cron_task
$time = strtotime(date('Y-m-d H:i:s'));
$upd1 = "update vtiger_cron_task set laststart = $time where name='CreantisCalendarSync'";
//////////////////////////////////////////////////////////////////////////////////////////
$adb->pquery($upd1, array());
while($data = $adb->fetch_row($result)){
	$tmp = rand()."".time();
	$userid = ($data['userid'] == 1)? 1 : false;
	error_log(print_r( "Iniciando[$tmp] ".date('Y-m-d H:i:s')." sincronizacion para el usuario {$data['userid']}" , true));
	// error_log(print_r( "Hora inicio[$tmp]: ".date('Y-m-d H:i:s') , true));
	$user = new Users();
	$current_user = $user->retrieveCurrentUserInfoFromFile($data['userid']);
	$obj = new Google_List_View();
	$records = $obj->Calendar($userid);
	error_log(print_r("Registros importados:"), true);
	error_log(print_r($records,true));
	error_log(print_r( "Finalizando[$tmp] ".date('Y-m-d H:i:s')."sincronizacion para el usuario {$data['userid']}" , true));
	// error_log(print_r( "Hora fin[$tmp]: ".date('Y-m-d H:i:s') , true));
}
//////////////////////////////////////////////////////////////////////////////////////////
$time = strtotime(date('Y-m-d H:i:s'));
$upd2 = "update vtiger_cron_task set lastend = $time where name='CreantisCalendarSync'";
$adb->pquery($upd2, array());
