<?php
class InvoicesController extends AppController {

    var $name = 'Invoices';
    var $helpers = array('Html', 'Form', 'Time', 'Text','Javascript');


    var $paginate = array(
	    'limit' => 300,
	    'contain' => array('Customer'),
	    'order'=>array('Invoice.id' => 'desc')
    );

    function index() {
	$this->Invoice->recursive = 0;
	$this->set('invoices', $this->paginate());
    }



    function printView() {
	$this->layout = 'minimal';
	$this->Invoice->recursive = 0;
	$this->set('invoices', $this->Invoice->find('all'));
    }

    function view($id = null) {
	if (!$id) {
	    $this->Session->setFlash(__('Invalid Invoice.', true));
	    $this->redirect(array('action'=>'index'));
	}
	$invoice =  $this->Invoice->read(null, $id);
	$this->set('invoice', $invoice);

	$emailIDs = array();
	foreach($invoice['Email'] as $email) {
	    $emailIDs[] = $email['id'];
	}
	$emails = $this->Invoice->Email->find('all', array('conditions'=>array('Email.id'=>$emailIDs)));
	$this->set('emails', $emails);
    }


    function payment_received($id = null) {
	if (!$id) {
	    $this->Session->setFlash(__('Invalid Invoice.', true));
	    $this->redirect(array('action'=>'index'));
	}
	$invoice =  $this->Invoice->read(null, $id);

	$invoice['Invoice']['paid'] = 1;
	$invoice['Invoice']['payment_received_date'] = date('Y-m-d');
	$this->Invoice->save($invoice);
    }



    function edit($id = null) {
	if (!$id && empty($this->data)) {
	    $this->Session->setFlash(__('Invalid Invoice', true));
	    $this->redirect(array('action'=>'index'));
	}
	if (!empty($this->data)) {
	    if ($this->Invoice->save($this->data)) {
		$this->Session->setFlash(__('The Invoice has been saved', true));
		$this->redirect(array('action'=>'index'));
	    } else {
		$this->Session->setFlash(__('The Invoice could not be saved. Please, try again.', true));
	    }
	}
	if (empty($this->data)) {
	    $invoice = $this->Invoice->read(null, $id);
	    $this->data = $invoice;

	}
	
	$jobs = $this->Invoice->Job->find('list', array('conditions'=>array('Job.enquiry_id'=>$invoice['Invoice']['enquiry_id'])));
	$this->set(compact('users', 'jobs'));
    }

    /*function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Invoice', true));
            $this->redirect(array('action'=>'index'));
        }
        if ($this->Invoice->del($id)) {
            $this->Session->setFlash(__('Invoice deleted', true));
            $this->redirect(array('action'=>'index'));
        }
    }*/

}

?>