<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

require_once('include/Dashlets/Dashlet.php');
require_once('include/Sugar_Smarty.php');
require_once('Helper.php');


class MySaldoDashlet extends Dashlet { 

	var $savedText; // users's saved text
    var $height = '300'; // height of the pad 
    var $firstLoad = 'yes';
    function MySaldoDashlet($id, $def = null) {
  
		global $current_user, $mod_strings, $app_strings;
		require('modules/EcmPaymentStates/Dashlets/MySaldoDashlet/MySaldoDashlet.meta.php');
		require('modules/EcmCharts/language/pl_pl.lang.php');
        parent::Dashlet($id); // call parent constructor   
        
        $this->isConfigurable = true; // dashlet is configurable
        $this->hasScript = false;  // dashlet has java ipt attached to it
        $options = $this->loadOptions();

        // if no custom title, use default
        if(!$options["title"]) 
        	$options["title"] = "Salda";
        
        $this->title = $options["title"];        

    }
	
	function display() {
		global $current_user, $mod_strings, $app_strings;
		
	// prepare data
$db = $GLOBALS ['db'];

if ($_REQUEST['account_type'])
	$account_type = $_REQUEST['account_type'];
else
	$account_type = '';

if ($_REQUEST['saldo_type'])
    $saldo_type = $_REQUEST['saldo_type'];
else
    $saldo_type = '';


if ($_REQUEST['type2'])
    $and = " and account_type2='".$_REQUEST['type2']."'";
else
    $saldo_type = '';
// get list of accounts
$saldo_type='minus';
if ($account_type == '')
	$clients = $db->query ( "SELECT distinct t.parent_id FROM ecmtransactions as t
	        INNER JOIN accounts AS a
ON t.parent_id = a.id
	         WHERE t.settled!='1' AND t.deleted='0' ".$and." ORDER BY t.parent_name" );
else 
	$clients = $db->query ( "
			SELECT distinct t.parent_id FROM ecmtransactions AS t
INNER JOIN accounts AS a
ON t.parent_id = a.id
WHERE 
t.settled!='1' AND 
t.deleted='0' AND
a.account_type = '$account_type' ".$and."
ORDER BY t.parent_name;
			" );
// arrays to handle data for SMARTY
$data = array ();
$sum = array ();
$sum['saldo'] = 0;
$sum['today_saldo'] = 0;
$sum ['unsettled'] = 0;
$sum ['not_overdue'] = 0;
$sum ['overdue'] = 0;
$sum ['2'] = 0; // 1..30
$sum ['3'] = 0; // 31..60
$sum ['4'] = 0; // 61..90
$sum ['5'] = 0; // 91..180
$sum ['6'] = 0; // 180..
$sum ['8'] = 0; 
$sum ['9'] = 0; 
$sum ['10'] = 0; 

while ( $c = $db->fetchByAssoc ( $clients ) ) {
	
	$row = array ();
	$row['id'] = $c['parent_id'];
	
	$tt= $db->fetchByAssoc ( $db->query ( "SELECT name FROM accounts WHERE id='" . $c ['parent_id'] . "'" ) );
	$row ['name'] =$tt['name'];
	$row ['unsettled'] = getData ( $c ['parent_id'], 0 );
	$row ['not_overdue'] = getData ( $c ['parent_id'], 7 );
	$row ['overdue'] = getData ( $c ['parent_id'], 1 );
	$row ['2'] = getData ( $c ['parent_id'], 2 ); // 1..30
	$row ['3'] = getData ( $c ['parent_id'], 3 ); // 31..60
	$row ['4'] = getData ( $c ['parent_id'], 4 ); // 61..90
	$row ['5'] = getData ( $c ['parent_id'], 5 ); // 91..180
	$row ['6'] = getData ( $c ['parent_id'], 6 ); // 180..
	$row ['saldo'] = getData ( $c ['parent_id'], 8 ); 
	$row ['today_saldo'] = getData ( $c ['parent_id'], 9 ); 
	if($saldo_type=='plus' && !($row ['saldo']>0))continue;
	if($saldo_type=='minus' && $row ['saldo']>0)continue;
	$sum ['unsettled'] += $row ['unsettled'];
	$sum ['not_overdue'] += $row ['not_overdue'];
	$sum ['overdue'] += $row ['overdue'];
	$sum ['2'] += $row ['2']; // 1..30
	$sum ['3'] += $row ['3']; // 31..60
	$sum ['4'] += $row ['4']; // 61..90
	$sum ['5'] += $row ['5']; // 91..180
	$sum ['6'] += $row ['6']; // 180..
	$sum ['saldo'] += $row ['saldo']; 
	$sum ['today_saldo'] += $row ['today_saldo']; 
	
	$data [] = $row;
} 
// format sum
$sum ['unsettled'] = format_number ( $sum ['unsettled'] );
$sum ['not_overdue'] = format_number ( $sum ['not_overdue'] );
$sum ['overdue'] = format_number ( $sum ['overdue'] );
$sum ['2'] = format_number ( $sum ['2'] ); // 1..30
$sum ['3'] = format_number ( $sum ['3'] ); // 31..60
$sum ['4'] = format_number ( $sum ['4'] ); // 61..90
$sum ['5'] = format_number ( $sum ['5'] ); // 91..180
$sum ['6'] = format_number ( $sum ['6'] ); // 180..
$sum ['saldo'] = format_number ( $sum ['saldo'] ); 
$sum ['today_saldo'] = format_number ( $sum ['today_saldo'] ); 
                                           
// sort
$sort = array ();

if ($_REQUEST ['sort'] && $_REQUEST ['sort'] != '')
	switch ($_REQUEST ['sort']) {
		case 'unsettled' :
			if ($_REQUEST ['sortType'] == 'asc') {
				usort ( $data, "cmpUnsettled" );
				$sort ['unsettled'] = 'desc'; // now is asc, so next is desc
			}
			if ($_REQUEST ['sortType'] == 'desc') {
				usort ( $data, "cmpUnsettledDesc" );
				$sort ['unsettled'] = 'asc'; // same story
			}
			break;
		case 'account' :
			if ($_REQUEST ['sortType'] == 'asc') {
				usort ( $data, "cmpAccount" );
				$sort ['account'] = 'desc'; // now is asc, so next is desc
			}
			if ($_REQUEST ['sortType'] == 'desc') {
				usort ( $data, "cmpAccountDesc" );
				$sort ['account'] = 'asc'; // same story
			}
			break;
		case 'not_overdue' :
			if ($_REQUEST ['sortType'] == 'asc') {
				usort ( $data, "cmpNotOverdue" );
				$sort ['not_overdue'] = 'desc'; // now is asc, so next is desc
			}
			if ($_REQUEST ['sortType'] == 'desc') {
				usort ( $data, "cmpNotOverdueDesc" );
				$sort ['not_overdue'] = 'asc'; // same story
			}
			break;
		case 'overdue' :
			if ($_REQUEST ['sortType'] == 'asc') {
				usort ( $data, "cmpOverdue" );
				$sort ['overdue'] = 'desc'; // now is asc, so next is desc
			}
			if ($_REQUEST ['sortType'] == 'desc') {
				usort ( $data, "cmpOverdueDesc" );
				$sort ['overdue'] = 'asc'; // same story
			}
			break;
			case 'saldo' :
				if ($_REQUEST ['sortType'] == 'asc') {
					usort ( $data, "cmpSaldo" );
					$sort ['saldo'] = 'desc'; // now is asc, so next is desc
				}
				if ($_REQUEST ['sortType'] == 'desc') {
					usort ( $data, "cmpSaldoDesc" );
					$sort ['saldo'] = 'asc'; // same story
				}
			break;
			case 'today_saldo' :
				if ($_REQUEST ['sortType'] == 'asc') {
					usort ( $data, "cmpTodaySaldo" );
					$sort ['today_saldo'] = 'desc'; // now is asc, so next is desc
				}
				if ($_REQUEST ['sortType'] == 'desc') {
					usort ( $data, "cmpTodaySaldoDesc" );
					$sort ['today_saldo'] = 'asc'; // same story
				}
				break;
	}
	
	// format data
foreach ( $data as $key => $row ) {
	// format numbers
	$row ['unsettled'] = format_number ( $row ['unsettled'] );
	$row ['not_overdue'] = format_number ( $row ['not_overdue'] );
	$row ['overdue'] = format_number ( $row ['overdue'] );
	$row ['2'] = format_number ( $row ['2'] ); // 1..30
	$row ['3'] = format_number ( $row ['3'] ); // 31..60
	$row ['4'] = format_number ( $row ['4'] ); // 61..90
	$row ['5'] = format_number ( $row ['5'] ); // 91..180
	$row ['6'] = format_number ( $row ['6'] ); // 180..
	$row ['saldo'] = format_number ( $row ['saldo'] ); 
	$row ['today_saldo'] = format_number ( $row ['today_saldo'] ); 
	
	$data [$key] = $row;
}

// create & execute smarty
$ss = new Sugar_Smarty ();
global $mod_strings;
$ss->assign ( "MOD", $mod_strings );
$ss->assign ( "DATA", $data );
$ss->assign ( "SUM", $sum );
$ss->assign ( "SORT", $sort );
$ss->assign("account_type", $account_type);
$ss->assign("saldo_type",$saldo_type);
$ss->assign("type",$_REQUEST['type2']);
$ss->assign("type2",$app_list_strings['account_type2_dom']);
$output = $ss->fetch('modules/EcmPaymentStates/Dashlets/MySaldoDashlet/MySaldoDashlet.tpl');




     
        // return parent::display for title and smarty template
        return parent::display($this->dashletStrings['LBL_DBLCLICK_HELP']) . $output; 
    }
	
	function displayOptions() {
	    global $mod_strings,$current_user;
	    // format daty	     
		$smarty = new Sugar_Smarty();
		// Pobieram ustawienia
		$options = $this->loadOptions();
		// Data od
		$Calendar_daFormat = str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));
	   if(!$options['date_from'])
			$options['date_from'] = '01.01.2010';

		//The id must be assigned in all dashlet options pages
		$smarty->assign('id', $this->id); 
		// Typ dokumentu: all, normal, correct

	
		$smarty->assign('date_from', $options["date_from"]);
		$smarty->assign("dateFormat", $Calendar_daFormat);
		$smarty->assign('LANG', $mod_strings);
		$smarty->assign('title', $options["title"]);
		// Pokazywać dane porównawcze? Tak: enabled, nie: disabled

		
		// Przekazuję widok opcji do metody displayOptions()
		return parent::displayOptions() . $smarty->fetch('modules/EcmPaymentStates/Dashlets/MySaldoDashlet/MySaldoDashletOptions.tpl');	
	}
	
	// Zapisywanie opcji dashletu
	function saveOptions($req) {
		$options = array();
		$options["year"] = $req["year"];
		$options["comparativeData"] = $req["comparativeData"];
		$options["type"] = $req["type"];
		$options["chartType"] = $req["chartType"];
		$options["title"] = $req["title"];

		if( $req["account_name"] == '' )
		{
			$options["contractor_name"] = '';
			$options["contractor_id"] = '';
		} else {
			$options["contractor_name"] = $req['account_name'];
			$options["contractor_id"] = $req['account_id'];
		}
		return $options;
    }
}
?>