<?php
/*********************************************************************************
 * The contents of this file are subject to the TimeTrex Public License Version
 * 1.1.0 ("License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.TimeTrex.com/TPL
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by TimeTrex" logo and
 *    (ii) the TimeTrex copyright notice
 * in the same form as they appear in the distribution.  See full license for
 * requirements.
 *
 * The Original Code is: TimeTrex Open Source
 * The Initial Developer of the Original Code is TimeTrex Payroll Services
 * Portions created by TimeTrex are Copyright (C) 2004-2007 TimeTrex Payroll Services;
 * All Rights Reserved.
 *
 ********************************************************************************/
/*
 * $Revision: 2237 $
 * $Id: T4Summary.php 2237 2008-11-11 18:18:20Z ipso $
 * $Date: 2008-11-11 10:18:20 -0800 (Tue, 11 Nov 2008) $
 */
require_once('../../includes/global.inc.php');
require_once(Environment::getBasePath() .'includes/Interface.inc.php');
require(Environment::getBasePath() .'/classes/fpdi/fpdi.php');

if ( !$permission->Check('report','enabled')
		OR !$permission->Check('report','view_t4_summary') ) {
	$permission->Redirect( FALSE ); //Redirect
}

$smarty->assign('title', TTi18n::gettext($title = 'T4 Summary Report')); // See index.php

/*
 * Get FORM variables
 */
extract	(FormVariables::GetVariables(
										array	(
												'action',
												'setup_data',
												'generic_data',
												'filter_data'
												) ) );

URLBuilder::setURL($_SERVER['SCRIPT_NAME'],
											array(
													'filter_data' => $filter_data
//													'sort_column' => $sort_column,
//													'sort_order' => $sort_order,
												) );

$static_columns = array(			'-1000-full_name' => TTi18n::gettext('Full Name'),
											'-1010-title' => TTi18n::gettext('Title'),
											'-1020-province' => TTi18n::gettext('Province'),
											'-1030-country' => TTi18n::gettext('Country'),
											'-1039-group' => TTi18n::gettext('Group'),
											'-1040-default_branch' => TTi18n::gettext('Default Branch'),
											'-1050-default_department' => TTi18n::gettext('Default Department'),
											'-1060-sin' => TTi18n::gettext('SIN')
											);

$non_static_columns = array(		'-1100-income' => TTi18n::gettext('Income (14)'),
											'-1110-income_tax' => TTi18n::gettext('Income Tax (22)'),
											'-1120-employee_cpp' => TTi18n::gettext('Employee CPP (16)'),
											'-1125-ei_earnings' => TTi18n::gettext('EI Insurable Earnings (24)'),
											'-1130-employee_ei' => TTi18n::gettext('Employee EI (18)'),
											'-1140-union_dues' => TTi18n::gettext('Union Dues (44)'),
											'-1150-employer_cpp' => TTi18n::gettext('Employer CPP'),
											'-1160-employer_ei' => TTi18n::gettext('Employer EI'),
											'-1200-other_box_0' => TTi18n::gettext('Other Box 1'),
											'-1210-other_box_1' => TTi18n::gettext('Other Box 2'),
											'-1220-other_box_2' => TTi18n::gettext('Other Box 3'),
											);

$pseallf = new PayStubEntryAccountLinkListFactory();
$pseallf->getByCompanyId( $current_company->getId() );
if ( $pseallf->getRecordCount() > 0 ) {
	$pseal_obj = $pseallf->getCurrent();
}

$column_ps_entry_name_map = array(
								'income' => @$setup_data['income_psea_ids'], //Gross Pay
								'income_tax' => @$setup_data['tax_psea_ids'],
								'employee_cpp' => array($setup_data['employee_cpp_psea_id']),
								'employee_ei' => array($setup_data['employee_ei_psea_id']),
								'ei_earnings' => @$setup_data['ei_earnings_psea_ids'],
								'union_dues' => array($setup_data['union_dues_psea_id']),
								'employer_cpp' => array($setup_data['employer_cpp_psea_id']),
								'employer_ei' => array($setup_data['employer_ei_psea_id']),
								'other_box_0' => @$setup_data['other_box'][0]['psea_ids'],
								'other_box_1' => @$setup_data['other_box'][1]['psea_ids'],
								'other_box_2' => @$setup_data['other_box'][2]['psea_ids'],
								);

$columns = Misc::prependArray( $static_columns, $non_static_columns);

$pplf = new PayPeriodListFactory();
$year_options = $pplf->getYearsArrayByCompanyId( $current_company->getId() );

$ugdlf = new UserGenericDataListFactory();
$ugdf = new UserGenericDataFactory();

$filter_data = Misc::preSetArrayValues( $filter_data, array('include_user_ids', 'exclude_user_ids', 'user_status_ids', 'group_ids', 'branch_ids', 'department_ids', 'user_title_ids', 'pay_period_ids', 'column_ids' ), array() );

$action = Misc::findSubmitButton();
Debug::Text('Action: '. $action, __FILE__, __LINE__, __METHOD__,10);
switch ($action) {
	case 'display_t4s':
	case 'display_report':
		//Debug::setVerbosity(11);

		Debug::Text('Submit!: '. $action, __FILE__, __LINE__, __METHOD__,10);
		Debug::Arr($filter_data, 'aFilter Data', __FILE__, __LINE__, __METHOD__,10);

		//Save report setup data
		$ugdlf->getByCompanyIdAndScriptAndDefault( $current_company->getId(), $_SERVER['SCRIPT_NAME'] );
		if ( $ugdlf->getRecordCount() > 0 ) {
			$ugdf->setID( $ugdlf->getCurrent()->getID() );
		}
		$ugdf->setCompany( $current_company->getId() );
		$ugdf->setName( $title );
		$ugdf->setScript( $_SERVER['SCRIPT_NAME'] );
		$ugdf->setData( $setup_data );
		$ugdf->setDefault( TRUE );
		if ( $ugdf->isValid() ) {
			$ugdf->Save();
		}

		$ulf = new UserListFactory();
		$ulf->getSearchByCompanyIdAndArrayCriteria( $current_company->getId(), $filter_data );
		if ( $ulf->getRecordCount() > 0 ) {
			foreach( $ulf as $u_obj ) {
				$filter_data['user_ids'][] = $u_obj->getId();
			}

			if ( isset($filter_data['year']) AND isset($filter_data['user_ids']) ) {
				//Get all pay period IDs in year.
				if ( isset($filter_data['year']) ) {
					$year_epoch = mktime(0,0,0,1,1,$filter_data['year']);
					Debug::Text(' Year: '. TTDate::getDate('DATE+TIME', $year_epoch) , __FILE__, __LINE__, __METHOD__,10);
				}

				//This must go by PAYSTUB transaction date, not PAY PERIOD transaction date.
				//To handle cases where a pay stub is paid earlier then the pay period transaction date
				//due to dismissal, and the transaction date happens to fall before the new year.
/*
				$pplf->getByCompanyIdAndTransactionStartDateAndTransactionEndDate( $current_company->getId(), TTDate::getBeginYearEpoch($year_epoch), TTDate::getEndYearEpoch($year_epoch) );
				if ( $pplf->getRecordCount() > 0 ) {
					foreach($pplf as $pp_obj) {
						$pay_period_ids[] = $pp_obj->getID();
					}
				}
*/
				$pself = new PayStubEntryListFactory();
				$pself->getReportByCompanyIdAndUserIdAndTransactionStartDateAndTransactionEndDate($current_company->getId(), $filter_data['user_ids'], TTDate::getBeginYearEpoch($year_epoch), TTDate::getEndYearEpoch($year_epoch) );
				//$pself->getReportByCompanyIdAndUserIdAndPayPeriodId( $current_company->getId(), $filter_data['user_ids'], $pay_period_ids );


				$report_columns = $static_columns;

				foreach( $pself as $pse_obj ) {
					$user_id = $pse_obj->getColumn('user_id');
					$pay_stub_entry_name_id = $pse_obj->getColumn('pay_stub_entry_name_id');

					$raw_rows[$user_id][$pay_stub_entry_name_id] = $pse_obj->getColumn('amount');
				}
				//var_dump($raw_rows);

				if ( isset($raw_rows) ) {
					$ulf = new UserListFactory();

					$utlf = new UserTitleListFactory();
					$title_options = $utlf->getByCompanyIdArray( $current_company->getId() );

					$uglf = new UserGroupListFactory();
					$group_options = $uglf->getArrayByNodes( FastTree::FormatArray( $uglf->getByCompanyIdArray( $current_company->getId() ), 'no_tree_text', TRUE) );

					$blf = new BranchListFactory();
					$branch_options = $blf->getByCompanyIdArray( $current_company->getId() );

					$dlf = new DepartmentListFactory();
					$department_options = $dlf->getByCompanyIdArray( $current_company->getId() );

					$x=0;
					foreach($raw_rows as $user_id => $raw_row) {
						$user_obj = $ulf->getById( $user_id )->getCurrent();

						$tmp_rows[$x]['user_id'] = $user_id;
						$tmp_rows[$x]['full_name'] = $user_obj->getFullName(TRUE);
						//$tmp_rows[$x]['province'] = Option::getByKey($user_obj->getProvince(), $user_obj->getOptions('province') );
						//$tmp_rows[$x]['province'] = $user_obj->getProvince();

						$tmp_rows[$x]['province'] = $user_obj->getProvince();
						$tmp_rows[$x]['country'] = $user_obj->getCountry();

						$tmp_rows[$x]['title'] = Option::getByKey($user_obj->getTitle(), $title_options, NULL );
						$tmp_rows[$x]['group'] = Option::getByKey($user_obj->getGroup(), $group_options );
						$tmp_rows[$x]['default_branch'] =  Option::getByKey($user_obj->getDefaultBranch(), $branch_options, NULL );
						$tmp_rows[$x]['default_department'] = Option::getByKey($user_obj->getDefaultDepartment(), $department_options, NULL );

						$tmp_rows[$x]['sin'] = $user_obj->getSIN();

						foreach($column_ps_entry_name_map as $column_key => $ps_entry_map) {
							$tmp_rows[$x][$column_key] = Misc::MoneyFormat( Misc::sumMultipleColumns( $raw_rows[$user_id], $ps_entry_map), FALSE );
						}

						$x++;
					}
				}
				//var_dump($rows);

				//Skip grouping if they are displaying T4's
				if ( $action != 'display_t4s' AND isset($filter_data['primary_group_by']) AND $filter_data['primary_group_by'] != '0' ) {
					Debug::Text('Primary Grouping Data By: '. $filter_data['primary_group_by'], __FILE__, __LINE__, __METHOD__,10);

					$ignore_elements = array_keys($static_columns);

					$filter_data['column_ids'] = array_diff( $filter_data['column_ids'], $ignore_elements );

					//Add the group by element back in
					if ( isset($filter_data['secondary_group_by']) AND $filter_data['secondary_group_by'] != 0 ) {
						array_unshift( $filter_data['column_ids'], $filter_data['primary_group_by'], $filter_data['secondary_group_by'] );
					} else {
						array_unshift( $filter_data['column_ids'], $filter_data['primary_group_by'] );
					}

					$tmp_rows = Misc::ArrayGroupBy( $tmp_rows, array(Misc::trimSortPrefix($filter_data['primary_group_by']),Misc::trimSortPrefix($filter_data['secondary_group_by'])), Misc::trimSortPrefix($ignore_elements) );
				}


				if ( isset($tmp_rows) ) {
					foreach($tmp_rows as $row) {
						$rows[] = $row;
					}

					//$rows = Sort::Multisort($rows, $filter_data['primary_sort'], NULL, 'ASC');
					$rows = Sort::Multisort($rows, Misc::trimSortPrefix($filter_data['primary_sort']), Misc::trimSortPrefix($filter_data['secondary_sort']), $filter_data['primary_sort_dir'], $filter_data['secondary_sort_dir']);

					$total_row = Misc::ArrayAssocSum($rows, NULL, 2);

					$last_row = count($rows);
					$rows[$last_row] = $total_row;
					foreach ($static_columns as $static_column_key => $static_column_val) {
						Debug::Text('Clearing Column: '. $static_column_key, __FILE__, __LINE__, __METHOD__,10);
						$rows[$last_row][Misc::trimSortPrefix($static_column_key)] = NULL;
					}
					unset($static_column_key, $static_column_val);
				}

			}
		}

		foreach( $filter_data['column_ids'] as $column_key ) {
			$filter_columns[Misc::trimSortPrefix($column_key)] = $columns[$column_key];
		}

		if ( $action == 'display_t4s' ) {
			Debug::Text('Generating PDF: ', __FILE__, __LINE__, __METHOD__,10);

			//Get company information
			$clf = new CompanyListFactory();
			$company_obj = $clf->getById( $current_company->getId() )->getCurrent();

			$border = 0;

			$pdf= new fpdi();

			//Import original Gov't supplied PDF.
			$pagecount = $pdf->setSourceFile(Environment::getBasePath().'interface'. DIRECTORY_SEPARATOR .'forms'. DIRECTORY_SEPARATOR .'ca'. DIRECTORY_SEPARATOR .'tax'. DIRECTORY_SEPARATOR .'t4flat-05b.pdf');
			$tplidx = $pdf->ImportPage(1);
			$tplidx_back = $pdf->ImportPage(2);

			$pdf->setMargins(5,5,5,5);
			$pdf->SetAutoPageBreak(FALSE);
			$pdf->SetFont('freeserif','',10);

			$i=0;
			$last_row = count($rows)-1;

			$total_row = $last_row+1;
			/*

				Fill out summary form.

			*/

			//Import original Gov't supplied PDF.
			$pagecount = $pdf->setSourceFile(Environment::getBasePath().'interface/forms/ca/tax/t4-sum-05b.pdf');
			$tplidx_summary = $pdf->ImportPage(1);

			$pdf->AddPage();
			$pdf->useTemplate($tplidx_summary,0,0);

			//Total T4's
			$pdf->setXY(79,16);
			$pdf->Cell(10,5, substr($filter_data['year'],2,2) , $border, 0, 'C');

			//Business Number
			$pdf->setXY(102,29);
			$pdf->Cell(65,5,$company_obj->getBusinessNumber(), $border, 0, 'L');

			//Employer Info
			$pdf->setXY(102,40);
			$pdf->Cell(65,5,$company_obj->getName(), $border, 0, 'L');

			$pdf->setXY(102,45);
			$pdf->Cell(65,5,$company_obj->getAddress1().' '.$company_obj->getAddress2(), $border, 0, 'L');

			$pdf->setXY(102,50);
			$pdf->Cell(65,5,$company_obj->getCity().', '.$company_obj->getProvince(), $border, 0, 'L');

			$postal_code_a = substr($company_obj->getPostalCode(), 0, 3);
			$postal_code_b = substr($company_obj->getPostalCode(), 3, 6);

			$pdf->setXY(102,55);
			$pdf->Cell(20,5,$postal_code_a.' '. $postal_code_b, $border, 0, 'L');

			//Total T4 slips
			$pdf->setXY(25,74.5);
			$pdf->Cell(20,5,$last_row, $border, 0, 'L');

			//Income
			if ( $rows[$last_row]['income'] > 0 ) {
				$pdf->setXY(55,87.5);
				$pdf->Cell(20,5,Misc::getBeforeDecimal( $rows[$last_row]['income'] ), $border, 0, 'R');
				$pdf->setXY(75,87.5);
				$pdf->Cell(10,5,Misc::getAfterDecimal( $rows[$last_row]['income'] ), $border, 0, 'C');
			}

			//Employee CPP
			if ( $rows[$last_row]['employee_cpp'] > 0 ) {
				$pdf->setXY(121,74.5);
				$pdf->Cell(20,5,Misc::getBeforeDecimal( $rows[$last_row]['employee_cpp'] ), $border, 0, 'R');
				$pdf->setXY(141,74.5);
				$pdf->Cell(10,5,Misc::getAfterDecimal( $rows[$last_row]['employee_cpp'] ), $border, 0, 'C');
			}

			//Employers CPP
			if ( $rows[$last_row]['employer_cpp'] > 0 ) {
				$pdf->setXY(121,87.5);
				$pdf->Cell(20,5,Misc::getBeforeDecimal( $rows[$last_row]['employer_cpp'] ), $border, 0, 'R');
				$pdf->setXY(141,87.5);
				$pdf->Cell(10,5,Misc::getAfterDecimal( $rows[$last_row]['employer_cpp'] ), $border, 0, 'C');
			}

			//Employees EI
			if ( $rows[$last_row]['employee_ei'] > 0 ) {
				$pdf->setXY(121,100);
				$pdf->Cell(20,5,Misc::getBeforeDecimal( $rows[$last_row]['employee_ei'] ), $border, 0, 'R');
				$pdf->setXY(141,100);
				$pdf->Cell(10,5,Misc::getAfterDecimal( $rows[$last_row]['employee_ei'] ), $border, 0, 'C');
			}

			//Employers EI
			if ( $rows[$last_row]['employer_ei'] > 0 ) {
				$pdf->setXY(121,113);
				$pdf->Cell(20,5,Misc::getBeforeDecimal( $rows[$last_row]['employer_ei'] ), $border, 0, 'R');
				$pdf->setXY(141,113);
				$pdf->Cell(10,5,Misc::getAfterDecimal( $rows[$last_row]['employer_ei'] ), $border, 0, 'C');
			}

			//Income Tax
			if ( $rows[$last_row]['income_tax'] > 0 ) {
				$pdf->setXY(121,126);
				$pdf->Cell(20,5,Misc::getBeforeDecimal( $rows[$last_row]['income_tax'] ), $border, 0, 'R');
				$pdf->setXY(141,126);
				$pdf->Cell(10,5,Misc::getAfterDecimal( $rows[$last_row]['income_tax'] ), $border, 0, 'C');
			}

			//Total Deductons
			$total_deductions = Misc::MoneyFormat( $rows[$last_row]['employee_cpp'] + $rows[$last_row]['employer_cpp'] + $rows[$last_row]['employee_ei'] + $rows[$last_row]['employer_ei'] + $rows[$last_row]['income_tax'], FALSE );
			if ( $total_deductions > 0 ) {
				$pdf->setXY(121,138);
				$pdf->Cell(20,5,Misc::getBeforeDecimal( $total_deductions ), $border, 0, 'R');
				$pdf->setXY(141,138);
				$pdf->Cell(10,5,Misc::getAfterDecimal( $total_deductions ), $border, 0, 'C');
			}
/*
			//Remittance
			if ( $total_deductions > 0 ) {
				$pdf->setXY(121,151);
				$pdf->Cell(20,5,Misc::getBeforeDecimal( $total_deductions ), $border, 0, 'R');
				$pdf->setXY(141,151);
				$pdf->Cell(10,5,Misc::getAfterDecimal( $total_deductions ), $border, 0, 'C');
			}
*/

			foreach($rows as $row) {
				if ( $i == $last_row ) {
					continue;
				}

				$ulf = new UserListFactory();
				$user_obj = $ulf->getById( $row['user_id'] )->getCurrent();

				$pdf->AddPage();
				$pdf->useTemplate($tplidx,0,0);

				//Use the original PDF instead
				//$pdf->Image(Environment::getBasePath().'interface/images/t4flat.jpg',0,0,210,300);
				//$pdf->Image(Environment::getBasePath().'interface/images/t4flat.png',0,0);

				$bottom_offset = 139;

				//Year
				$pdf->setXY(127,13.5);
				$pdf->Cell(19,5,$filter_data['year'], $border, 0, 'C');

				$pdf->setXY(127,13.5+$bottom_offset);
				$pdf->Cell(19,5,$filter_data['year'], $border, 0, 'C');

				//Employer Info
				$pdf->setXY(18,10);
				$pdf->Cell(65,5,$company_obj->getName(), $border, 0, 'L');
				$pdf->setXY(18,10+$bottom_offset);
				$pdf->Cell(65,5,$company_obj->getName(), $border, 0, 'L');

				$pdf->setXY(18,15);
				$pdf->Cell(65,5,$company_obj->getAddress1().' '.$company_obj->getAddress2(), $border, 0, 'L');
				$pdf->setXY(18,15+$bottom_offset);
				$pdf->Cell(65,5,$company_obj->getAddress1().' '.$company_obj->getAddress2(), $border, 0, 'L');

				$pdf->setXY(18,20);
				$pdf->Cell(65,5,$company_obj->getCity().', '.$company_obj->getProvince(), $border, 0, 'L');
				$pdf->setXY(18,20+$bottom_offset);
				$pdf->Cell(65,5,$company_obj->getCity().', '.$company_obj->getProvince(), $border, 0, 'L');


				$postal_code_a = substr($company_obj->getPostalCode(), 0, 3);
				$postal_code_b = substr($company_obj->getPostalCode(), 3, 6);

				$pdf->setXY(18,25);
				$pdf->Cell(20,5,$postal_code_a.' '. $postal_code_b, $border, 0, 'L');
				$pdf->setXY(18,25+$bottom_offset);
				$pdf->Cell(20,5,$postal_code_a.' '. $postal_code_b, $border, 0, 'L');

				//Business Number
				$pdf->setXY(21,39);
				$pdf->Cell(35,5,$company_obj->getBusinessNumber(), $border, 0, 'L');
				$pdf->setXY(21,39+$bottom_offset);
				$pdf->Cell(35,5,$company_obj->getBusinessNumber(), $border, 0, 'L');

				//SIN
				$pdf->setXY(21,51.5);
				$pdf->Cell(35,5,$row['sin'], $border, 0, 'L');
				$pdf->setXY(21,51.5+$bottom_offset);
				$pdf->Cell(35,5,$row['sin'], $border, 0, 'L');

				//Excemptions

				//Get User Tax / Deductions by Pay Stub Account.
				$udlf = new UserDeductionListFactory();
				$udlf->getByUserIdAndPayStubEntryAccountID( $user_obj->getId(), $setup_data['employee_cpp_psea_id'] );
				if ( $setup_data['employee_cpp_psea_id'] != 0
						AND $udlf->getRecordCount() == 0 ) {
					Debug::Text('CPP Exempt!', __FILE__, __LINE__, __METHOD__,10);
					$pdf->setXY(74,51.5);
					$pdf->Cell(5,5,'X', $border, 0, 'C');
					$pdf->setXY(74,51.5+$bottom_offset);
					$pdf->Cell(5,5,'X', $border, 0, 'C');
				}

				$udlf->getByUserIdAndPayStubEntryAccountID( $user_obj->getId(), $setup_data['employee_ei_psea_id'] );
				if ( $setup_data['employee_ei_psea_id'] != 0
						AND $udlf->getRecordCount() == 0 ) {
					Debug::Text('EI Exempt!', __FILE__, __LINE__, __METHOD__,10);
					$pdf->setXY(83,51.5);
					$pdf->Cell(5,5,'X', $border, 0, 'C');
					$pdf->setXY(83,51.5+$bottom_offset);
					$pdf->Cell(5,5,'X', $border, 0, 'C');
				}

				//Employee Info
				$pdf->setXY(20,70);
				$pdf->Cell(55,5,strtoupper( $user_obj->getLastName() ), $border, 0, 'L');
				$pdf->setXY(20,70+$bottom_offset);
				$pdf->Cell(55,5,strtoupper( $user_obj->getLastName() ), $border, 0, 'L');

				$pdf->setXY(78,70);
				$pdf->Cell(25,5,$user_obj->getFirstName(), $border, 0, 'L');
				$pdf->setXY(78,70+$bottom_offset);
				$pdf->Cell(25,5,$user_obj->getFirstName(), $border, 0, 'L');

				$pdf->setXY(108,70);
				$pdf->Cell(8,5,substr( $user_obj->getMiddleName(),0,1), $border, 0, 'R');
				$pdf->setXY(108,70+$bottom_offset);
				$pdf->Cell(8,5,substr( $user_obj->getMiddleName(),0,1), $border, 0, 'R');

				$pdf->setXY(20,77);
				$pdf->Cell(75,5,$user_obj->getAddress1().' '.$user_obj->getAddress2(), $border, 0, 'L');
				$pdf->setXY(20,77+$bottom_offset);
				$pdf->Cell(75,5,$user_obj->getAddress1().' '.$user_obj->getAddress2(), $border, 0, 'L');

				$pdf->setXY(20,82);
				$pdf->Cell(75,5,$user_obj->getCity().', '.$user_obj->getProvince(), $border, 0, 'L');
				$pdf->setXY(20,82+$bottom_offset);
				$pdf->Cell(75,5,$user_obj->getCity().', '.$user_obj->getProvince(), $border, 0, 'L');

				$pdf->setXY(20,87);
				$pdf->Cell(75,5,$user_obj->getPostalCode(), $border, 0, 'L');
				$pdf->setXY(20,87+$bottom_offset);
				$pdf->Cell(75,5,$user_obj->getPostalCode(), $border, 0, 'L');

				$pdf->setXY(107,39);
				$pdf->Cell(10,5, $user_obj->getProvince(), $border, 0, 'C');
				$pdf->setXY(107,39+$bottom_offset);
				$pdf->Cell(10,5, $user_obj->getProvince(), $border, 0, 'C');

				//Earnings
				$pdf->setXY(132,26.5);
				$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['income'] ), $border, 0, 'R');
				$pdf->setXY(132,26.5+$bottom_offset);
				$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['income'] ), $border, 0, 'R');

				$pdf->setXY(153,26.5);
				$pdf->Cell(10,5,Misc::getAfterDecimal( $row['income'] ), $border, 0, 'C');
				$pdf->setXY(153,26.5+$bottom_offset);
				$pdf->Cell(10,5,Misc::getAfterDecimal( $row['income'] ), $border, 0, 'C');

				//Income Tax
				if ( $row['income_tax'] > 0 ) {
					$pdf->setXY(178,26.5);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['income_tax'] ), $border, 0, 'R');
					$pdf->setXY(178,26.5+$bottom_offset);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['income_tax'] ), $border, 0, 'R');

					$pdf->setXY(199,26.5);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['income_tax'] ), $border, 0, 'C');
					$pdf->setXY(199,26.5+$bottom_offset);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['income_tax'] ), $border, 0, 'C');

				}

				//CPP
				if ( $row['employee_cpp'] > 0 ) {
					$pdf->setXY(132,39);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['employee_cpp'] ), $border, 0, 'R');
					$pdf->setXY(132,39+$bottom_offset);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['employee_cpp'] ), $border, 0, 'R');

					$pdf->setXY(153,39);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['employee_cpp'] ), $border, 0, 'C');
					$pdf->setXY(153,39+$bottom_offset);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['employee_cpp'] ), $border, 0, 'C');

				}

				//EI Earnings
				if ( $row['ei_earnings'] > 0 ) {
					$pdf->setXY(178,39);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['ei_earnings'] ), $border, 0, 'R');
					$pdf->setXY(178,39+$bottom_offset);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['ei_earnings'] ), $border, 0, 'R');

					$pdf->setXY(199,39);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['ei_earnings'] ), $border, 0, 'C');
					$pdf->setXY(199,39+$bottom_offset);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['ei_earnings'] ), $border, 0, 'C');
				}

				//EI
				if ( $row['employee_ei'] > 0 ) {
					$pdf->setXY(132,64.5);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['employee_ei'] ), $border, 0, 'R');
					$pdf->setXY(132,64.5+$bottom_offset);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['employee_ei'] ), $border, 0, 'R');

					$pdf->setXY(153,64.5);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['employee_ei'] ), $border, 0, 'C');
					$pdf->setXY(153,64.5+$bottom_offset);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['employee_ei'] ), $border, 0, 'C');

				}

				//Union Dues
				if ( $row['union_dues'] > 0 ) {
					$pdf->setXY(178,64.5);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['union_dues'] ), $border, 0, 'R');
					$pdf->setXY(178,64.5+$bottom_offset);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['union_dues'] ), $border, 0, 'R');

					$pdf->setXY(199,64.5);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['union_dues'] ), $border, 0, 'C');
					$pdf->setXY(199,64.5+$bottom_offset);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['union_dues'] ), $border, 0, 'C');
				}

				//Other Box(s)
				if ( $row['other_box_0'] > 0 AND isset($setup_data['other_box'][0]['box']) AND $setup_data['other_box'][0]['box'] !='') {
					$pdf->setXY(40,115);
					$pdf->Cell(10,5,Misc::getBeforeDecimal( $setup_data['other_box'][0]['box'] ), $border, 0, 'C');
					$pdf->setXY(40,114+$bottom_offset);
					$pdf->Cell(10,5,Misc::getBeforeDecimal( $setup_data['other_box'][0]['box'] ), $border, 0, 'C');

					$pdf->setXY(63,115);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['other_box_0'] ), $border, 0, 'R');
					$pdf->setXY(63,114+$bottom_offset);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['other_box_0'] ), $border, 0, 'R');

					$pdf->setXY(83,115);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['other_box_0'] ), $border, 0, 'C');
					$pdf->setXY(83,114+$bottom_offset);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['other_box_0'] ), $border, 0, 'C');
				}

				if ( $row['other_box_1'] > 0 AND isset($setup_data['other_box'][1]['box']) AND $setup_data['other_box'][1]['box'] !='') {
					$pdf->setXY(98,115);
					$pdf->Cell(10,5,Misc::getBeforeDecimal( $setup_data['other_box'][1]['box'] ), $border, 0, 'C');
					$pdf->setXY(98,114+$bottom_offset);
					$pdf->Cell(10,5,Misc::getBeforeDecimal( $setup_data['other_box'][1]['box'] ), $border, 0, 'C');

					$pdf->setXY(120,115);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['other_box_1'] ), $border, 0, 'R');
					$pdf->setXY(120,114+$bottom_offset);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['other_box_1'] ), $border, 0, 'R');

					$pdf->setXY(141,115);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['other_box_1'] ), $border, 0, 'C');
					$pdf->setXY(141,114+$bottom_offset);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['other_box_1'] ), $border, 0, 'C');
				}

				if ( $row['other_box_2'] > 0 AND isset($setup_data['other_box'][2]['box']) AND $setup_data['other_box'][2]['box'] !='') {
					$pdf->setXY(155,115);
					$pdf->Cell(10,5,Misc::getBeforeDecimal( $setup_data['other_box'][2]['box'] ), $border, 0, 'C');
					$pdf->setXY(155,114+$bottom_offset);
					$pdf->Cell(10,5,Misc::getBeforeDecimal( $setup_data['other_box'][2]['box'] ), $border, 0, 'C');

					$pdf->setXY(177,115);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['other_box_2'] ), $border, 0, 'R');
					$pdf->setXY(177,114+$bottom_offset);
					$pdf->Cell(20,5,Misc::getBeforeDecimal( $row['other_box_2'] ), $border, 0, 'R');

					$pdf->setXY(198,115);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['other_box_2'] ), $border, 0, 'C');
					$pdf->setXY(198,114+$bottom_offset);
					$pdf->Cell(10,5,Misc::getAfterDecimal( $row['other_box_2'] ), $border, 0, 'C');
				}

				if ( isset($filter_data['include_t4_back']) AND $filter_data['include_t4_back'] == 1 ) {
					$pdf->AddPage();
					$pdf->useTemplate($tplidx_back,0,0);
				}

				$i++;
			}


			//Finish off PDF
			$output = $pdf->Output('','S');

			Misc::FileDownloadHeader('t4summary.pdf', 'application/pdf', strlen($output));
			echo $output;

			exit;

		} else {
			Debug::Text('NOT Generating PDF: ', __FILE__, __LINE__, __METHOD__,10);
		}

		$smarty->assign_by_ref('generated_time', TTDate::getTime() );
		//$smarty->assign_by_ref('pay_period_options', $pay_period_options );
		$smarty->assign_by_ref('filter_data', $filter_data );
		$smarty->assign_by_ref('columns', $filter_columns );
		$smarty->assign_by_ref('rows', $rows);

		$smarty->display('report/T4SummaryReport.tpl');

		break;
	case 'delete':
	case 'save':
		Debug::Text('Action: '. $action, __FILE__, __LINE__, __METHOD__,10);

		$generic_data['id'] = UserGenericDataFactory::reportFormDataHandler( $action, $filter_data, $generic_data, URLBuilder::getURL(NULL, $_SERVER['SCRIPT_NAME']) );
		unset($generic_data['name']);
	default:
		BreadCrumb::setCrumb($title);

		$ugdlf->getByCompanyIdAndScriptAndDefault( $current_company->getId(), $_SERVER['SCRIPT_NAME'] );
		if ( $ugdlf->getRecordCount() > 0 ) {
			Debug::Text('Found Company Report Setup!', __FILE__, __LINE__, __METHOD__,10);
			$ugd_obj = $ugdlf->getCurrent();
			$setup_data = $ugd_obj->getData();
		}
		unset($ugd_obj);

		if ( $action == 'load' ) {
			Debug::Text('Loading Report!', __FILE__, __LINE__, __METHOD__,10);
			extract( UserGenericDataFactory::getReportFormData( $generic_data['id'] ) );
		} elseif ( $action == '' ) {
			//Check for default saved report first.
			$ugdlf->getByUserIdAndScriptAndDefault( $current_user->getId(), $_SERVER['SCRIPT_NAME'] );
			if ( $ugdlf->getRecordCount() > 0 ) {
				Debug::Text('Found Default Report!', __FILE__, __LINE__, __METHOD__,10);

				$ugd_obj = $ugdlf->getCurrent();
				$filter_data = $ugd_obj->getData();
				$generic_data['id'] = $ugd_obj->getId();
			} else {
				Debug::Text('Default Settings!', __FILE__, __LINE__, __METHOD__,10);
				//Default selections
				//$filter_data['user_ids'] = array_keys( UserListFactory::getByCompanyIdArray( $current_company->getId(), FALSE, FALSE ) );
				$filter_data['user_status_ids'] = array( -1 );
				$filter_data['branch_ids'] = array( -1 );
				$filter_data['department_ids'] = array( -1 );
				$filter_data['user_title_ids'] = array( -1 );
				$filter_data['group_ids'] = array( -1 );

				//$filter_data['year'] = $year_options[$year_keys[1]];

				$filter_data['column_ids'] = array_keys($columns);

				//$filter_data['sort_column'] = 'last_name';
				$filter_data['primary_sort'] = '-1000-full_name';
				$filter_data['secondary_sort'] = '-1020-province';


			}
		}
		$filter_data = Misc::preSetArrayValues( $filter_data, array('include_user_ids', 'exclude_user_ids', 'user_status_ids', 'group_ids', 'branch_ids', 'department_ids', 'user_title_ids', 'pay_period_ids', 'column_ids' ), NULL );

		//Deduction PSEA accounts
		$psealf = new PayStubEntryAccountListFactory();
		$filter_data['pay_stub_entry_account_options'] = $psealf->getByCompanyIdAndStatusIdAndTypeIdArray( $current_company->getId(), 10, array(10,20,30,40,50), TRUE );

		$psealf = new PayStubEntryAccountListFactory();
		$filter_data['deduction_pay_stub_entry_account_options'] = $psealf->getByCompanyIdAndStatusIdAndTypeIdArray( $current_company->getId(), 10, array(20,30), TRUE );

		$ulf = new UserListFactory();
		$all_array_option = array('-1' => TTi18n::gettext('-- All --'));

		//Get include employee list.
		$ulf->getByCompanyId( $current_company->getId() );
		$user_options = $ulf->getArrayByListFactory( $ulf, FALSE, TRUE );

		$filter_data['src_include_user_options'] = Misc::arrayDiffByKey( (array)$filter_data['include_user_ids'], $user_options );
		$filter_data['selected_include_user_options'] = Misc::arrayIntersectByKey( (array)$filter_data['include_user_ids'], $user_options );

		//Get exclude employee list
		$exclude_user_options = Misc::prependArray( $all_array_option, $ulf->getArrayByListFactory( $ulf, FALSE, TRUE ) );
		$filter_data['src_exclude_user_options'] = Misc::arrayDiffByKey( (array)$filter_data['exclude_user_ids'], $user_options );
		$filter_data['selected_exclude_user_options'] = Misc::arrayIntersectByKey( (array)$filter_data['exclude_user_ids'], $user_options );

		//Get employee status list.
		$user_status_options = Misc::prependArray( $all_array_option, $ulf->getOptions('status') );
		$filter_data['src_user_status_options'] = Misc::arrayDiffByKey( (array)$filter_data['user_status_ids'], $user_status_options );
		$filter_data['selected_user_status_options'] = Misc::arrayIntersectByKey( (array)$filter_data['user_status_ids'], $user_status_options );

		//Get Employee Groups
		$uglf = new UserGroupListFactory();
		$group_options = Misc::prependArray( $all_array_option, $uglf->getArrayByNodes( FastTree::FormatArray( $uglf->getByCompanyIdArray( $current_company->getId() ), 'TEXT', TRUE) ) );
		$filter_data['src_group_options'] = Misc::arrayDiffByKey( (array)$filter_data['group_ids'], $group_options );
		$filter_data['selected_group_options'] = Misc::arrayIntersectByKey( (array)$filter_data['group_ids'], $group_options );

		//Get branches
		$blf = new BranchListFactory();
		$blf->getByCompanyId( $current_company->getId() );
		$branch_options = Misc::prependArray( $all_array_option, $blf->getArrayByListFactory( $blf, FALSE, TRUE ) );
		$filter_data['src_branch_options'] = Misc::arrayDiffByKey( (array)$filter_data['branch_ids'], $branch_options );
		$filter_data['selected_branch_options'] = Misc::arrayIntersectByKey( (array)$filter_data['branch_ids'], $branch_options );

		//Get departments
		$dlf = new DepartmentListFactory();
		$dlf->getByCompanyId( $current_company->getId() );
		$department_options = Misc::prependArray( $all_array_option, $dlf->getArrayByListFactory( $dlf, FALSE, TRUE ) );
		$filter_data['src_department_options'] = Misc::arrayDiffByKey( (array)$filter_data['department_ids'], $department_options );
		$filter_data['selected_department_options'] = Misc::arrayIntersectByKey( (array)$filter_data['department_ids'], $department_options );

		//Get employee titles
		$utlf = new UserTitleListFactory();
		$utlf->getByCompanyId( $current_company->getId() );
		$user_title_options = Misc::prependArray( $all_array_option, $utlf->getArrayByListFactory( $utlf, FALSE, TRUE ) );
		$filter_data['src_user_title_options'] = Misc::arrayDiffByKey( (array)$filter_data['user_title_ids'], $user_title_options );
		$filter_data['selected_user_title_options'] = Misc::arrayIntersectByKey( (array)$filter_data['user_title_ids'], $user_title_options );

		//Get column list
		$filter_data['src_column_options'] = Misc::arrayDiffByKey( (array)$filter_data['column_ids'], $columns );
		$filter_data['selected_column_options'] = Misc::arrayIntersectByKey( (array)$filter_data['column_ids'], $columns );

		$filter_data['year_options'] = $year_options;

		//Get primary/secondary order list
		$filter_data['sort_options'] = $columns;
		$filter_data['sort_direction_options'] = Misc::getSortDirectionArray();

		$filter_data['group_by_options'] = Misc::prependArray( array('0' => TTi18n::gettext('No Grouping')), $static_columns );

		$saved_report_options = $ugdlf->getByUserIdAndScriptArray( $current_user->getId(), $_SERVER['SCRIPT_NAME']);
		$generic_data['saved_report_options'] = $saved_report_options;
		$smarty->assign_by_ref('generic_data', $generic_data);

		$smarty->assign_by_ref('filter_data', $filter_data);
		$smarty->assign_by_ref('setup_data', $setup_data);

		$smarty->assign_by_ref('ugdf', $ugdf);

		$smarty->display('report/T4Summary.tpl');

		break;
}
?>