<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/**
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 */




require_once('include/Dashlets/Dashlet.php');
require_once('include/Sugar_Smarty.php');
require_once('include/charts/Charts.php');
require_once('modules/Dashboard/Forms.php');

class OutcomeByMonthDashlet extends Dashlet {
    var $refresh = false;
    
    var $obm_date_start;
    var $obm_date_end;
    var $obm_ids;
    
    function OutcomeByMonthDashlet($id, $options) {
        global $timedate;
        parent::Dashlet($id);
        $this->isConfigurable = true;
        $this->isRefreshable = true;
        
		$this->loadLanguage('OutcomeByMonthDashlet', 'modules/Charts/Dashlets/');

        if(empty($options['title'])) 
        	$this->title = $this->dashletStrings['LBL_TITLE'];
        else
        	$this->title = $options['title'];
        
        if(empty($options['obm_date_start'])) 
            $this->obm_date_start = date($timedate->get_db_date_time_format(), time());
        else
            $this->obm_date_start = $options['obm_date_start']; 
            
        if(empty($options['obm_date_end']))
            $this->obm_date_end = date($timedate->get_db_date_time_format(), strtotime('2010-01-01'));
        else
            $this->obm_date_end = $options['obm_date_end'];
            
        $this->obm_ids = (empty($options['obm_ids'])) ? array() : $options['obm_ids'];
    }

    function saveOptions($req) {
        global $sugar_config, $timedate, $current_user, $theme;
        $options = array();
                
        $date_start = $this->obm_date_start;
        $date_end = $this->obm_date_end;
        $dateStartDisplay = strftime($timedate->get_user_date_format(), strtotime($date_start));
        $dateEndDisplay     = strftime($timedate->get_user_date_format(), strtotime($date_end));
        $seps               = array("-", "/");
        $dates              = array($dateStartDisplay, $dateEndDisplay);
        $dateFileNameSafe   = str_replace($seps, "_", $dates);
        if(is_file($sugar_config['tmp_dir'] . $current_user->getUserPrivGuid()."_".$theme."_my_pipeline_".$dateFileNameSafe[0]."_".$dateFileNameSafe[1].".xml"))
            unlink($sugar_config['tmp_dir'] . $current_user->getUserPrivGuid()."_".$theme."_my_pipeline_".$dateFileNameSafe[0]."_".$dateFileNameSafe[1].".xml");
        
        $options['title'] = $_REQUEST['pbss_dashlet_title'];
        $options['obm_ids'] = $_REQUEST['obm_ids'];
        $timeFormat = $current_user->getUserDateTimePreferences();
       
        $options['obm_date_start'] =  $timedate->swap_formats($_REQUEST['obm_date_start'], $timeFormat['date'], $timedate->dbDayFormat);
        $options['obm_date_end'] =  $timedate->swap_formats($_REQUEST['obm_date_end'], $timeFormat['date'], $timedate->dbDayFormat);
        
        return $options;
    }

    function displayOptions() {
        global $timedate, $image_path, $app_strings, $current_user, $app_list_strings;
        
        $ss = new Sugar_Smarty();
        $ss->assign('id', $this->id);
        $ss->assign('module', $_REQUEST['module']);
        $ss->assign('dashletType', 'predefined_chart');       
        $ss->assign('LBL_TITLE', translate('LBL_TITLE', 'Charts'));
        $ss->assign('LBL_CHART_TYPE', translate('LBL_CHART_TYPE', 'Charts'));        
        $ss->assign('LBL_DATE_START', translate('LBL_DATE_START', 'Charts'));
        $ss->assign('LBL_DATE_END', translate('LBL_DATE_END', 'Charts'));
        $ss->assign('LBL_USERS', translate('LBL_USERS', 'Charts'));
        $ss->assign('LBL_ENTER_DATE', translate('LBL_ENTER_DATE', 'Charts'));
        $ss->assign('LBL_SELECT_BUTTON_TITLE', $app_strings['LBL_SELECT_BUTTON_TITLE']);
        $ss->assign('LBL_SUBMIT_BUTTON_LABEL', $app_strings['LBL_SUBMIT_BUTTON_LABEL']);
        $ss->assign('image_path', $image_path);
        
        //get the dates to display
        $date_start = $this->obm_date_start;
        $date_end = $this->obm_date_end;
        
        $timeFormat = $current_user->getUserDateTimePreferences();
        $ss->assign('date_start', $timedate->swap_formats($date_start, $timedate->dbDayFormat, $timeFormat['date']));
        $ss->assign('date_end', $timedate->swap_formats($date_end, $timedate->dbDayFormat, $timeFormat['date']));
        
        //get list of user ids for which to display data
		if (isset($this->obm_ids) && count($this->obm_ids) > 0) {
			$ids = $this->obm_ids;
		}
		else {
			$ids = get_user_array(false);
			$ids = array_keys($ids);
		}
        
        $id_hash = '1';
		if (isset($ids)) {
			sort($ids);
			$id_hash = crc32(implode('',$ids));
			if($id_hash < 0)
			{
		        $id_hash = $id_hash * -1;
			}
		
		}
		$GLOBALS['log']->debug("ids is:");
		$GLOBALS['log']->debug($ids);
		$id_md5 = substr(md5($current_user->id),0,9);
		        
        $ss->assign('obm_ids', get_select_options_with_id(get_user_array(false),$ids));
        
        $ss->assign('dashlet_title', $this->title);
        
        $ss->assign('user_date_format', $timedate->get_user_date_format());
        $ss->assign('cal_dateformat', $timedate->get_cal_date_format());
        
        $ss->assign('module', $_REQUEST['module']);
        
        return parent::displayOptions() . $ss->fetch('modules/Charts/Dashlets/OutcomeByMonthDashlet/OutcomeByMonthConfigure.tpl');
    }

    
    /**
     * Displays the javascript for the dashlet
     * 
     * @return string javascript to use with this dashlet
     */
    function displayScript() {
    	global $sugar_config, $current_user, $current_language;
		
		$xmlFile = $sugar_config['tmp_dir']. $current_user->id . '_' . $this->id . '.xml';
		$chartStringsXML = $sugar_config['tmp_dir'].'chart_strings.' . $current_language .'.lang.xml';    
    	
    	$ss = new Sugar_Smarty();
        $ss->assign('chartName', $this->id);
        $ss->assign('chartXMLFile', $xmlFile);    

        $ss->assign('chartStyleCSS', chartStyle());
        $ss->assign('chartColorsXML', chartColors());
        $ss->assign('chartStringsXML', $chartStringsXML);
                
        $str = $ss->fetch('modules/Charts/Dashlets/PredefinedChartDashletScript.tpl');     
        return $str;
    }

    function getTitle($text) {
        global $image_path, $app_strings, $sugar_config;
        
        if($this->isConfigurable) 
            $additionalTitle = '<table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td width="99%">' . $text 
                               . '</td><td nowrap width="1%"><div style="width: 100%;text-align:right"><a href="#" onclick="SUGAR.mySugar.configureDashlet(\'' 
                               . $this->id . '\'); return false;" class="chartToolsLink">'    
                               . get_image($image_path.'edit','title="' . translate('LBL_DASHLET_EDIT', 'Home') . '" alt="' . translate('LBL_DASHLET_EDIT', 'Home') . '"  border="0"  align="absmiddle"').'</a> ' 
                               . '';
        else 
            $additionalTitle = '<table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td width="99%">' . $text 
                   . '</td><td nowrap width="1%"><div style="width: 100%;text-align:right">';
        
        if($this->isRefreshable)
            $additionalTitle .= '<a href="#" onclick="SUGAR.mySugar.retrieveDashlet(\'' 
                                . $this->id . '\',\'predefined_chart\'); return false;"><img width="13" height="13" border="0" align="absmiddle" title="' . translate('LBL_DASHLET_REFRESH', 'Home') . '" alt="' . translate('LBL_DASHLET_REFRESH', 'Home') . '" src="' 
                                . $image_path . 'refresh.gif"/></a> ';
        $additionalTitle .= '<a href="#" onclick="SUGAR.mySugar.deleteDashlet(\'' 
                            . $this->id . '\'); return false;"><img width="13" height="13" border="0" align="absmiddle" title="' . translate('LBL_DASHLET_DELETE', 'Home') . '" alt="' . translate('LBL_DASHLET_DELETE', 'Home') . '" src="' 
                            . $image_path . 'close_dashboard.gif"/></a></div></td></tr></table>';
            
        if(!function_exists('get_form_header')) {
            global $theme;
            require_once('themes/'.$theme.'/layout_utils.php');
        }
        
        $str = '<div ';
        if(empty($sugar_config['lock_homepage']) || $sugar_config['lock_homepage'] == false) $str .= ' onmouseover="this.style.cursor = \'move\';"';
        $str .= 'id="dashlet_header_' . $this->id . '">' . get_form_header($this->title, $additionalTitle, false) . '</div>';
        
        return $str;
    }        
    
    function display() {
        global $app_list_strings, $current_language, $sugar_config, $currentModule, $action, $current_user, $theme, $timedate, $image_path;
        
        $this->loadLanguage('OutcomeByMonthDashlet', 'modules/Charts/Dashlets/');
        $returnStr = '';
        
        $user_dateFormat = $timedate->get_date_format();
        $current_module_strings = return_module_language($current_language, 'Charts');      

		$currency_symbol = $sugar_config['default_currency_symbol'];
		
		if ($current_user->getPreference('currency')){
		    require_once('modules/Currencies/Currency.php');
            $currency = new Currency();
            $currency->retrieve($current_user->getPreference('currency'));
            $currency_symbol = $currency->symbol;
        }

		require_once('include/Sugar_Smarty.php');
		require_once('include/SugarCharts/SugarChart.php');
		require_once('modules/Charts/PredefinedChart.php');
		
		require("modules/Charts/chartdefs.php");
		
		$sugar_smarty = new Sugar_Smarty();

		$charts = array();
	
		$sugarChart = new SugarChart();
		$predefined_chart = new PredefinedChart;
		
		$chartDef = $chartDefs['outcome_by_month'];
		
		$chartUnits = translate('LBL_OPP_SIZE', 'Charts') . ' ' . $currency_symbol . '1' .translate('LBL_OPP_THOUSANDS', 'Charts');
		
		$sugarChart->setProperties('', $chartUnits, $chartDef['chartType']);
		$sugarChart->base_url = $chartDef['base_url'];
	
		$sugarChart->group_by = $chartDef['groupBy'];
		$sugarChart->url_params = $predefined_chart->params;		
		
		$sugarChart->getData($this->constructQuery());
	
		$xmlFile = $sugarChart->getXMLFileName($this->id);
		$sugarChart->saveXMLFile($xmlFile, $sugarChart->generateXML());
	
		$returnStr = $sugarChart->display($this->id, $xmlFile, '100%', '480', false);
        
        return $this->getTitle('<div align="center"></div>') . '<div align="center">' . $returnStr . '</div><br />';
	}
    
    function constructQuery()
    {
        require_once('modules/Opportunities/Opportunity.php');
		
		global $current_user;
		global $timedate;

        $date_start = $this->obm_date_start;
        $date_end = $this->obm_date_end;
			
        $user_ids = $this->obm_ids;
        if (empty($user_ids)) {
            $user_ids = array_keys(get_user_array(false));
        }
        
        $where = "opportunities.assigned_user_id IN ('" . implode("','",$user_ids) . "') ";
        
		// cn: adding user-pref date handling
		$dateStartDisplay = date($timedate->get_date_format(), strtotime($date_start));
		$dateEndDisplay = date($timedate->get_date_format(), strtotime($date_end));

		$opp = new Opportunity();
		//build the where clause for the query that matches $date_start and $date_end
		$where .= "AND opportunities.date_closed >= ".db_convert("'".$date_start."'",'datetime')." AND opportunities.date_closed <= ".db_convert("'".$date_end."'",'datetime')." AND opportunities.deleted=0";
		$query = "SELECT sales_stage,".db_convert('opportunities.date_closed','date_format',array("'%Y-%m'"),array("'YYYY-MM'"))." as m, sum(amount_usdollar/1000) as total, count(*) as opp_count FROM opportunities ";



		$query .= "WHERE ".$where;
		$query .= " GROUP BY sales_stage,".db_convert('opportunities.date_closed','date_format',array("'%Y-%m'"),array("'YYYY-MM'"))."ORDER BY m";		
		return $query;
    }
}

?>
