<?php
class InvoicesController extends AppController {

	var $name = 'Invoices';
	var $helpers = array('Html', 'Form', 'Time', 'Js' => array('Jquery'));
	var $components = array('RequestHandler');
	//$helpers = array('Report'); 
	
	function beforeFilter() {	  
		parent::beforeFilter();
	}		

	function index() {
		$this->layout = 'main_index';
		$this->redirectToNamed();		
		$conditions = array();
		
		$params = $this->params['named'];
		
		if (!empty($params['status_id'])) {
		  $conditions['Invoice.status_id ='] = $params['status_id'];
		}
		
		if (!empty($params['invoice_code'])) {
		  $conditions['Invoice.invoice_code ='] = $params['invoice_code'];
		}
		
		if (!empty($params['customer_id'])) {
		  $conditions['Invoice.customer_id ='] = $params['customer_id'];
		}	
		
		if (!empty($params['month_f'])) {
		  $conditions['Invoice.invoiced_month ='] = $params['month_f'];
		}
		
		if (!empty($params['year_f'])) {
		  $conditions['Invoice.invoiced_year ='] = $params['year_f'];
		}
		
		$urlArgs = array('url' => $params);

		if (empty($conditions)) {
			$conditions['Invoice.status_id ='] = 0;		  
		}		
		
		$this->paginate = array(
						'fields' => array('id','invoice_code','created','status_id'),
						'conditions' => $conditions,
						'link' => array(
							'Customer' => array(
								'fields' => array('Customer.id', 'Customer.name')),
							'Status' => array(
								'fields' => array('Status.id', 'Status.name_eng', 'Status.name_fre'))
								),
						'order' => 'Invoice.id DESC'
					);

		# Get the current language for status
		$currentLang = Configure::read('Config.language');
		$statuses = $this->Invoice->Status->forsearchListStatus(3,'name_'.$currentLang,'Status');
		$customers = $this->Invoice->Customer->find('list');
		$invoices = $this->paginate('Invoice');
		
		$this->set(compact('invoices', 'customers', 'statuses', 'urlArgs'));
	}


	function view($id = null) {
		$this->idEmptyRedirect($id, 'index');

		# Get the Invoice view information - and all the Evaluation-Tests
		# Invoice info - header
		$infoInvoice = $this->Invoice->infoCustomerInvoice($id);
		
		$this->data['Invoice']['customer_id'] = $infoInvoice['Customer']['id'];
		$this->data['Invoice']['invoice_id'] = $id;
				
		$this->set(compact('infoInvoice'));		
	}		

	function create_invoice() {
		# First time the page is loaded - right after the Invoices parameters have been selected			
		if (!empty($this->data)) {
			$month_invoice = $this->data['Invoice']['invoiced_date']['month'];
			$year_invoice = $this->data['Invoice']['invoiced_date']['year'];
			$customer_id = $this->data['Invoice']['customer_id'];
			$team_id = $this->data['Invoice']['team_id'];
			$requester_id = $this->data['Invoice']['requester_id'];
			$type_inv = $this->data['Invoice']['invoice_type'];			
			
			# By Customer
			if ($type_inv == 1) {
				$countInvoice = $this->Invoice->countInvoice($month_invoice, $year_invoice, $customer_id, NULL, NULL);
			} elseif ($type_inv == 2) {
			# By Company / Team
				$countInvoice = $this->Invoice->countInvoice($month_invoice, $year_invoice, $customer_id, $team_id, NULL);
			} elseif ($type_inv == 3) {
			# By Company / Team / Requester
				//$countInvoice = $this->Invoice->countInvoice($month_invoice, $year_invoice, $customer_id, $team_id, $requester_id);
				$countInvoice = 0;
			}
			//echo ' countInvoice '.$countInvoice;
			
			//infoEvalByCustTeam
			# It is an Insert in the Invoice table
			if( $countInvoice == 0) {
				$getInvoiceDataToSave = $this->Invoice->getInvoiceDataToSave($customer_id, $team_id, $requester_id, $type_inv, $month_invoice, $year_invoice);
				//echo pr($getInvoiceDataToSave);
				
				if(count($getInvoiceDataToSave) == 0) {
					$this->flashWarning(__('There are no records to produce the Invoice', true));
				} else {
				# Prepare $this->data['Invoice'] / $this->data['InvoiceItems']tally up invoice
					if ($this->__prepInvoiceItems($customer_id, $month_invoice, $year_invoice, $getInvoiceDataToSave)){
						$this->Invoice->create();						
						if ($this->Invoice->save($this->data)) {
							# attach Invoice ID
							$this->__attachInvoiceIdToItems($this->Invoice->id);
							
							# save items
							$this->Invoice->InvoiceItem->saveAll($this->data['InvoiceItem']);
							
							$this->flashSuccess(__('The Invoice has been created', true), 'index/invoice_code:'.$this->data['Invoice']['invoice_code']);
						} else {
							$this->flashWarning(__('The Invoice could not be created. Please correct the error(s) and try again', true));
						}				 
					}				
				}				
			}else{
				$this->flashWarning(__('The Invoice Customer/Team already exists in the System. Please, check the report', true));
			}			
		}		
		$customers = $this->Invoice->Customer->find('list');

		$this->set(compact('customers'));			
	}

	function invoice_report()  {
		# Get the choice report/ and the customer - from the View Invoice		
		if (isset($this->params['named']['invoice_id'])){
			$invoice_id = $this->params['named']['invoice_id'];
			$type_rep = $this->params['named']['type_rep'];		
		}		
		# Get the customer address / patient name / order code => to the letter	
		$infoCustomerInvoice = $this->Invoice->infoCustomerInvoice($invoice_id);
	//	echo $infoCustomerInvoice;
		
		# Evaluate the Report Choice
		# Invoice Customer Report
		$infoInvoiceItems = $this->Invoice->InvoiceItem->infoInvoiceItems($invoice_id);
		
		$this->layout = 'pdf'; //this will use the pdf.ctp layout

		$this->set(compact('infoCustomerInvoice','infoInvoiceItems'));
		$this->render();
		
	}	
	
	
	function edit($id = null) {
		$this->idEmptyRedirect($id, 'index');
		
		if (!empty($this->data)) {
			if ($this->Invoice->save($this->data)) {
				$this->flashSuccess(__('The Invoice has been updated', true), 'index');
			} else {
				$this->flashWarning(__('The Invoice could not be updated. Please correct the error(s) and try again', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Invoice->read(null, $id);
		}
	}	


	function delete($id = null) {
		$this->idEmptyRedirect($id, 'index');
		
		if ($this->Invoice->del($id)) {
			$this->flashSuccess('Invoice deleted', 'index');
		}
	}
	
	function cancel() {
	# Called from Ques.Treat. view/add
		if (isset($this->params['named']['invoice_code'])) {
			$invoice_code = $this->params['named']['invoice_code'];
		}	
		$this->redirect(array ('controller' => 'invoices', 'action' => 'index/invoice_code:'.$invoice_code));		
	}	
	
	### Private methods ###	
	function __prepInvoiceItems($cust_id, $month_inv, $year_inv, $itemsValues) {
		//echo pr($itemsValues);
		##### get and set the last Invoice-Code from Orders table - 20000
		$lastInvoice = $this->Invoice->lastInvoice();
		if($lastInvoice == 0) { 
			# 1st Invoice 3800
			$this->data['Invoice']['invoice_code'] = 4000;
		} else {
			$this->data['Invoice']['invoice_code'] = $lastInvoice['Invoice']['invoice_code'] + 1;
		}	
		
		$this->data['Invoice']['invoiced_month'] = $month_inv;
		$this->data['Invoice']['invoiced_year'] = $year_inv;
		//$this->data['Invoice']['customer_id'] = $cust_id;
		$this->data['Invoice']['status_id'] = 19;
		$this->data['Invoice']['paid_date'] = date('Y-m-d', strtotime("+32 days"));
		
		# Current Tax Rates #
		$this->data['Invoice']['tax_fed_rate'] = 0.05;
		//$this->data['Invoice']['tax_prov_rate'] = 0.095;
		$this->data['Invoice']['tax_prov_rate'] = 0.09975;
		
		$itemsCount = count($itemsValues);
		for ($i=0; $i < $itemsCount; $i++) {
			$this->data['InvoiceItem'][$i]['amount'] = $itemsValues[$i]['fee_value'];
			$this->data['InvoiceItem'][$i]['evaluation_id'] = $itemsValues[$i]['test_id'];
			$this->data['InvoiceItem'][$i]['status_id'] = $itemsValues[$i]['status_id'];
			$this->data['Eval'][$i] = $itemsValues[$i]['test_id'];
			//$subTotal = $subTotal + $itemsValues[$i]['fee_value'];					
		
		}
		return true;
	}
	
	function export_invoicesxls($id = null)  {
		# Invoice Customer Report
			
        $this->layout = 'ajax';
		
		$infoInvoiceItemsXlss = $this->Invoice->InvoiceItem->infoInvoiceItemsXls($id);
		
        //$this->set('event', $this->Events->findById($id)); 		
		$this->set('infoInvoiceItemsXls',$infoInvoiceItemsXlss);
		$this->render('export_invoicesxls', 'export_invoicesxls');
		
	}	
	
	# attaches Invoice.id to $this->data['Item']
	function __attachInvoiceIdToItems($id){
		$itemsCount = 0;
		$itemsCount = count($this->data['InvoiceItem']);
	  for ($i=0; $i < $itemsCount; $i++) {
	    $this->data['InvoiceItem'][$i]['invoice_id'] = $id;
	  }
	}	
	
	function __lists() {
		$statuses = $this->Invoice->Status->find('list');
		$customers = $this->Invoice->Customer->find('list');		
		$this->set(compact('statuses', 'customers'));
	}
	
	public function get_teams_ajax() {
	  Configure::write('debug', 0);
	  if($this->RequestHandler->isAjax()) {
		$this->set('teams', $this->Invoice->Customer->Team->find('list',
							   array('conditions' =>
										   array('Team.customer_id' => $this->params['url']['idcust']),
									 'recursive' => -1)));
	  }
	}	
	
	public function get_requesters_ajax() {
	  Configure::write('debug', 0);
	  if($this->RequestHandler->isAjax()) {
		$this->set('requesters', $this->Invoice->Customer->Team->Requester->find('list',
							   array('conditions' =>
										   array('Requester.team_id' => $this->params['url']['idteam']),
									'fields' => array('Requester.id', 'Requester.name'),
									'recursive' => -1)));
	  }
	}	
}
?>