<?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-2010 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero 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 Affero General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Affero 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 Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero 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/ListView/ListViewDisplay.php');
include_once("modules/EcmStockOperations/EcmStockOperation.php");

require_once('include/contextMenus/contextMenu.php');

class ListViewSmarty extends ListViewDisplay{

	var $data;
	var $ss; // the smarty object
	var $displayColumns;
	var $searchColumns; // set by view.list.php
	var $tpl;
	var $moduleString;
	var $export = true;
    var $delete = true;
    var $select = true;
    var $mailMerge = true;
	var $multiSelect = true;
	var $overlib = true;
	var $quickViewLinks = true;
	var $lvd;
	var $mergeduplicates = true;
    var $contextMenus = true;
    var $showMassupdateFields = true;
    /**
     * Constructor, Smarty object immediately available after
     *
     */
	function ListViewSmarty() {
		parent::ListViewDisplay();
		$this->ss = new Sugar_Smarty();
	}

    /**
     * Processes the request. Calls ListViewData process. Also assigns all lang strings, export links,
     * This is called from ListViewDisplay
     *
     * @param file file Template file to use
     * @param data array from ListViewData
     * @param html_var string the corresponding html var in xtpl per row
     *
     */
	function process($file, $data, $htmlVar) {
		if(!$this->should_process)return;
		global $odd_bg, $even_bg, $hilite_bg, $click_bg, $app_strings;
		parent::process($file, $data, $htmlVar);

		$this->tpl = $file;
		$this->data = $data;

        $totalWidth = 0;
        foreach($this->displayColumns as $name => $params) {
            $totalWidth += $params['width'];
        }
        $adjustment = $totalWidth / 100;

        $contextMenuObjectsTypes = array();
        foreach($this->displayColumns as $name => $params) {
            $this->displayColumns[$name]['width'] = floor($this->displayColumns[$name]['width'] / $adjustment);
            // figure out which contextMenu objectsTypes are required
            if(!empty($params['contextMenu']['objectType']))
                $contextMenuObjectsTypes[$params['contextMenu']['objectType']] = true;
        }
		$this->ss->assign('displayColumns', $this->displayColumns);
		$this->ss->assign('APP',$app_strings);

		$this->ss->assign('bgHilite', $hilite_bg);
		$this->ss->assign('colCount', count($this->displayColumns) + 2);
		$this->ss->assign('htmlVar', strtoupper($htmlVar));
		$this->ss->assign('moduleString', $this->moduleString);
        $this->ss->assign('editLinkString', $app_strings['LBL_EDIT_BUTTON']);
        $this->ss->assign('viewLinkString', $app_strings['LBL_VIEW_BUTTON']);
        $this->ss->assign('allLinkString',$app_strings['LBL_LINK_ALL']);
        $this->ss->assign('noneLinkString',$app_strings['LBL_LINK_NONE']);
        $this->ss->assign('recordsLinkString',$app_strings['LBL_LINK_RECORDS']);
        $this->ss->assign('selectLinkString',$app_strings['LBL_LINK_SELECT']);
        if($this->overlib) $this->ss->assign('overlib', true);
		if($this->select)$this->ss->assign('selectLink', $this->buildSelectLink('select_link', $this->data['pageData']['offsets']['total'], $this->data['pageData']['offsets']['next']-$this->data['pageData']['offsets']['current']));
		
		if($this->show_action_dropdown)
		{
			$this->ss->assign('actionsLink', $this->buildActionsLink());
		}
		
		$this->ss->assign('quickViewLinks', $this->quickViewLinks);
		
		// handle save checks and stuff
		if($this->multiSelect) {
		
		//if($this->data['pageData']['bean']['moduleDir']== 'KBDocuments')
		//{ 
		//	$this->ss->assign('selectedObjectsSpan', $this->buildSelectedObjectsSpan(true, $this->data['pageData']['offsets']['current']));
		//} else {
			$this->ss->assign('selectedObjectsSpan', $this->buildSelectedObjectsSpan(true, $this->data['pageData']['offsets']['total']));
		//}
		
		$this->ss->assign('multiSelectData', $this->getMultiSelectData());
		}
		// include button for Adding to Target List if in one of four applicable modules
		if ( isset ( $_REQUEST['module']) && in_array ( $_REQUEST['module'] , array ( 'Contacts','Prospects','Leads','Accounts' )))
			$this->ss->assign( 'targetLink', $this->buildTargetList() ) ;
		$this->processArrows($data['pageData']['ordering']);
		$this->ss->assign('prerow', $this->multiSelect);
		$this->ss->assign('clearAll', $app_strings['LBL_CLEARALL']);
		$this->ss->assign('rowColor', array('oddListRow', 'evenListRow'));
		$this->ss->assign('bgColor', array($odd_bg, $even_bg));
        $this->ss->assign('contextMenus', $this->contextMenus);
        $this->ss->assign('is_admin_for_user', is_admin_for_module($GLOBALS['current_user'],'Users'));
        $this->ss->assign('is_admin', is_admin($GLOBALS['current_user']));


        if($this->contextMenus && !empty($contextMenuObjectsTypes)) {
            $script = '';
            $cm = new contextMenu();
            foreach($contextMenuObjectsTypes as $type => $value) {
                $cm->loadFromFile($type);
                $script .= $cm->getScript();
                $cm->menuItems = array(); // clear menuItems out
            }
            $this->ss->assign('contextMenuScript', $script);
        }
	}

    /**
     * Assigns the sort arrows in the tpl
     *
     * @param ordering array data that contains the ordering info
     *
     */
	function processArrows($ordering)
    {
		$pathParts = pathinfo(SugarThemeRegistry::current()->getImageURL('arrow.gif',false));

        list($width,$height) = getimagesize($pathParts['dirname'].'/'.$pathParts['basename']);

		$this->ss->assign('arrowExt', $pathParts['extension']);
		$this->ss->assign('arrowWidth', $width);
		$this->ss->assign('arrowHeight', $height);
		$this->ss->assign('arrowAlt', translate('LBL_SORT'));
	}



    /**
     * Displays the xtpl, either echo or returning the contents
     *
     * @param end bool display the ending of the listview data (ie MassUpdate)
     *
     */
	function display($end = true) {

		if(!$this->should_process) return $GLOBALS['app_strings']['LBL_SEARCH_POPULATE_ONLY'];
        global $app_strings,$current_user;
        $this->ss->assign('data', $this->data['data']);
		$this->data['pageData']['offsets']['lastOffsetOnPage'] = $this->data['pageData']['offsets']['current'] + count($this->data['data']);
		$this->ss->assign('pageData', $this->data['pageData']);
	
        $navStrings = array('next' => $app_strings['LNK_LIST_NEXT'],
                            'previous' => $app_strings['LNK_LIST_PREVIOUS'],
                            'end' => $app_strings['LNK_LIST_END'],
                            'start' => $app_strings['LNK_LIST_START'],
                            'of' => $app_strings['LBL_LIST_OF']);
        $this->ss->assign('navStrings', $navStrings);

		$str = parent::display();
		$strend = $this->displayEnd();
		$sum_mag=0;
	
		
		if($_REQUEST['query'] && $_REQUEST['module']=="EcmProducts"){
			$wh=array();
			if($_REQUEST['searchFormTab']=="basic_search"){
				if($_REQUEST['name_basic'])$wh[]="name like '".$_REQUEST['name_basic']."%'";
				if($_REQUEST['code_basic'])$wh[]="code like '%".$_REQUEST['code_basic']."%'";
				if($_REQUEST['manufacturer_id_basic'])$wh[]="manufacturer_id like '%".$_REQUEST['manufacturer_id_basic']."%'";
				if($_REQUEST['manufacturer_name_basic'])$wh[]="manufacturer_name like '%".$_REQUEST['manufacturer_name_basic']."%'";
				if($_REQUEST['product_category_id_basic'])$wh[]="product_category_id like '%".$_REQUEST['product_category_id_basic']."%'";
				if($_REQUEST['product_category_name_basic']){$wh[]="product_category_name like '%".$_REQUEST['product_category_name_basic']."%'";
				$bd=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT id FROM crm.ecmproductcategories WHERE name like '".$_REQUEST['product_category_name_advanced']."'"));
				}
				if($_REQUEST['purchase_price_basic'])$wh[]="purchase_price='".$_REQUEST['purchase_price_basic']."'";
				if($_REQUEST['production_basic']==1)$wh[]="production='1'";
				if($_REQUEST['end_of_line_basic']==1)$wh[]="end_of_line='1'";
				if($_REQUEST['production_basic']==0 && $_REQUEST['production_basic']!="")$wh[]="production='0'";
				if($_REQUEST['end_of_line_basic']==0 && $_REQUEST['end_of_line_basic']!="")$wh[]="end_of_line='0'";
			}
			else{
				if($_REQUEST['name_advanced'])$wh[]="name like '".$_REQUEST['name_advanced']."%'";
				if($_REQUEST['code_advanced'])$wh[]="code like '%".$_REQUEST['code_advanced']."%'";
				if($_REQUEST['manufacturer_id_advanced'])$wh[]="manufacturer_id like '%".$_REQUEST['manufacturer_id_advanced']."%'";
				if($_REQUEST['manufacturer_name_advanced'])$wh[]="manufacturer_name like '%".$_REQUEST['manufacturer_name_advanced']."%'";
				if($_REQUEST['product_category_id_advanced'])$wh[]="product_category_id like '%".$_REQUEST['product_category_id_advanced']."%'";
				if($_REQUEST['product_category_name_advanced']){$wh[]="product_category_name like '%".$_REQUEST['product_category_name_advanced']."%'";
				$bd=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT id FROM crm.ecmproductcategories WHERE name like '".$_REQUEST['product_category_name_advanced']."'"));
				
				}
				if(($_REQUEST['product_active_advanced']==0 || $_REQUEST['product_active_advanced']==1) && $_REQUEST['product_active_advanced']!="")$wh[]="product_active like '%".$_REQUEST['product_active_advanced']."%'";
				if($_REQUEST['commission_rate_advanced'])$wh[]="commission_rate like '%".$_REQUEST['commission_rate_advanced']."%'";
				if($_REQUEST['qty_per_unit_advanced'])$wh[]="qty_per_unit like '%".$_REQUEST['qty_per_unit_advanced']."%'";
				if($_REQUEST['sales_start_date_advanced'])$wh[]="sales_start_date>='".$_REQUEST['sales_start_date_advanced']."'";
				if($_REQUEST['sales_start_date_2_advanced'])$wh[]="sales_start_date<='".$_REQUEST['sales_start_date_2_advanced']."'";
				if($_REQUEST['sales_end_date_advanced'])$wh[]="sales_end_date>='".$_REQUEST['sales_end_date_advanced']."'";
				if($_REQUEST['sales_end_date_2_advanced'])$wh[]="sales_end_date<='".$_REQUEST['sales_end_date_2_advanced']."'";
				if($_REQUEST['production_advanced']==1)$wh[]="production='1'";
				if($_REQUEST['end_of_line_advanced']==1)$wh[]="end_of_line='1'";
				if($_REQUEST['production_advanced']==0 && $_REQUEST['production_advanced']!="")$wh[]="production='0'";
				if($_REQUEST['end_of_line_advanced']==0 && $_REQUEST['end_of_line_advanced']!="")$wh[]="end_of_line='0'";
			}
			$where=implode(" and ",$wh);
			$_SESSION['EcmProductsForXLSwhere']=$where;			
			$_SESSION['EcmProductsForXLSorder_by']=$_REQUEST['orderBy'];			
			$_SESSION['EcmProductsForXLSsorder']=$_REQUEST['sorder'];
		}
		
		if($_REQUEST['module']=="EcmProducts"){
			$op=new EcmStockOperation();
			$createxls='<input class="button" value="Stwórz XLS" onclick="document.forms[\'MassUpdate\'].action.value=\'CreateXLS\';document.forms[\'MassUpdate\'].to_pdf.value=\'1\';" type="submit">';		
			$createxml='<input class="button" value="Stwórz XML Merlin" onclick="document.forms[\'MassUpdate\'].action.value=\'CreateXMLMerlin\';document.forms[\'MassUpdate\'].to_pdf.value=\'1\';" type="submit">';
			if($where)$where1="and ".$where;	
			else $where1="";
		
			global $current_user;
			$z1="select id from ecmproducts where 1=1 ".$where1." and deleted='0'";
			$lol=$GLOBALS['db']->query($z1);
			
			$ids = array();
			$ac=0;
			while($rs2=$GLOBALS['db']->fetchByAssoc($lol)){
				$ids[] = $rs2['id'];
				
				$ac++;
			}
	
			$acc="select avg(pieces_per_carton) as ppc from ecmproducts where 1=1 ".$where1;
			$rs=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query($acc));
			if($_REQUEST['name_advanced'] || $_REQUEST['name_basic']){
		$row_mz = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT sum(quantity) as sum FROM ecmstockstates as ss INNER JOIN ecmproducts as p ON ss.product_id = p.id WHERE p.id IN ('".implode("','", $ids)."')"));
			
			}else{
			$row_mz = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT sum(quantity) as sum FROM ecmstockstates as ss INNER JOIN ecmproducts as p ON ss.product_id = p.id ".$where1));
			//echo $row_mz ['sum'];
			}
			if($_REQUEST['product_category_name_advanced'] || $_REQUEST['product_category_name_basis']){
				$x="select sum(pp.product_quantity) as l from ecmproducts_ecmpurchaseorders as pp inner join ecmpurchaseorders as p on p.id=pp.ecmpurchaseorder_id where p.status='accepted' and pp.ecmproduct_id IN ('".implode("','", $ids)."')";
		
			} else {
			$x="select sum(pp.product_quantity) as l from ecmproducts_ecmpurchaseorders as pp inner join ecmpurchaseorders as p on p.id=pp.ecmpurchaseorder_id where p.status='accepted'".$where1;
			}
		//echo $ac;
			
			//echo $rs['id'];
			
			//ilosc
			
			//end mz
			$wss=$GLOBALS['db']->query("select p0,p3 from ecmproducts where 1=1 ".$where1);
			
		 
			while($rss=$GLOBALS['db']->fetchByAssoc($wss)){
				
			//$arrr=$op->getStockArray($this->id);
			
				if($rss['p0']>0){
					$p0+=$rss['p0'];
					$i0++;
				}
				if($rss['p3']>0){
					$p3+=$rss['p3'];
					$i3++;
				}
			}  
				//print_r($ids);

			if($_REQUEST['searchFormTab']=="basic_search" || $_REQUEST['searchFormTab']=="advanced_search" ){
			 $x="select sum(pp.product_quantity) as l from ecmproducts_ecmpurchaseorders as pp inner join ecmpurchaseorders as p on p.id=pp.ecmpurchaseorder_id where p.status='accepted' and pp.ecmproduct_id IN ('".implode("','", $ids)."')";
			 
			 $ros=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query($x));
		
			} else {
				$x="select sum(pp.product_quantity) as l from ecmproducts_ecmpurchaseorders as pp inner join ecmpurchaseorders as p on p.id=pp.ecmpurchaseorder_id where p.status='accepted'".$where1;
				$ros=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query($x));
			}
		
			//print_r($ros);
			$summary='<td style="padding:4px;font-weight:bold;">Razem</td><td style="padding:4px;font-weight:bold;"></td><td style="padding:4px;font-weight:bold;"></td><td style="padding:4px;font-weight:bold;"></td><td style="padding:4px;font-weight:bold;">'.number_format($row_mz['sum'],2,',','').'</td><td style="padding:4px;font-weight:bold;">'.number_format($ros['l'],0,'','').'</td><td style="padding:4px;font-weight:bold;">'.number_format($rs['ppc'],0,'','').'</td><td style="padding:4px;font-weight:bold;"></td>';
        	$this->ss->assign('summary', $summary);

		}
		
	
		//return $str . $this->ss->fetch($this->tpl) . (($end) ? $strend : '');
		return $str . $this->ss->fetch($this->tpl). (($end) ? '<br>'.$createxls.'<br>'.'<br>'.$createxml.'<br>' . $strend : '');
	}
    function displayEnd() {
        $str = '';
        if($this->show_mass_update_form) {
            if($this->showMassupdateFields){
                $str .= $this->mass->getMassUpdateForm(true);
            }
            $str .= $this->mass->endMassUpdateForm();
        }

        return $str;
    }
}

?>