<?php
class QuotesController extends AppController {

    var $name = 'Quotes';
    var $helpers = array('Html', 'Form', 'Time', 'Number');

    var $components = array('RequestHandler');

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

    function ajax_edit() {
	$this->layout = 'ajax';
	if(!empty($this->data)) {

	    if ($this->Quote->save($this->data)) {
		echo "SUCCESS";
	    }
	    else {
		echo "FAILURE";
	    }
	}
	else {
	    echo "NO-DATA";
	}

    }

    function edit($id = null) {
	$this->layout = 'ajax';

	if (!$id && empty($this->data)) {
	    $this->Session->setFlash(__('Invalid Quote', true));
	    $this->redirect(array('action'=>'index'));
	}
	if (!empty($this->data)) {
	    /*$issuedate = $this->data['Quote']['date_issued'];
	    $issuedate = $issuedate['year'].'-'.$issuedate['month'].'-'.$issuedate['day'];

	    $validUntilDate = strtotime($issuedate."+ ".$this->data['Quote']['days_valid']." days");

	    $this->data['Quote']['valid_until'] = date('Y-m-d', $validUntilDate);
	    */

	    if ($this->Quote->save($this->data)) {

		$this->Session->setFlash(__('The Quote has been saved', true));
		$thisquote = $this->Quote->id;
		$this->redirect(array('action' =>'view/'.$id), null, false);
	    } else {
		$this->Session->setFlash(__('The Quote could not be saved. Please, try again.', true));
	    }
	}
	if (empty($this->data)) {
	    $quote = $this->Quote->read(null, $id);
	    $this->data = $quote;
	}
	$enquiry = $this->Quote->Enquiry->findById($quote['Quote']['enquiry_id']);
	$currencies = $this->Quote->Currency->find('list');
	$this->set('yesNo', array(0=>'No', 1=>'Yes'));
	$this->set(compact('enquiry', 'quote', 'currencies'));
        
        $this->set('cityCountryList', $this->Quote->Enquiry->Principle->getCityCountryList());
    }


    function pdf($id = null) {
	//Configure::write('debug',0);
	if(!$id) {
	    $this->Session->setFlash(__('Invalid Quote', true));
	    $this->redirect(array('controller'=>'enquiries', 'action'=>'index'));
	}
	$quote = $this->Quote->findById($id);
	//$customer = $this->Quote->Enquiry->Customer->read(null, $quote['Enquiry']['customer_id']);
	$enquiry = $this->Quote->Enquiry->find('first', array('conditions' => array('Enquiry.id' => $quote['Quote']['enquiry_id'])));


	$quoteProducts = $this->Quote->Document->LineItem->find('all', array('recursive' => 0, 'conditions' => array('LineItem.quote_id' => $id),
		'order' => array('LineItem.item_number ASC'))
	);

	$user = $this->Quote->Enquiry->User->find('first', array('conditions' => array('User.id' => $enquiry['Enquiry']['user_id'])));




	/**
	 * Call the commercial Comments. Need to have already figured out what page to do this on..
	 *
	 * * Passing a data structure in the following format.
	 *
	 * $details = array(
	 *              'deliveryTime' => (String) eg. 2-3
	 *              'paymentTerms => (String) eg. 100% PAYMENT WITH ORDER || NET 30 DAYS FOR APPROVED ACCOUNTS
	 *              'dateIssued' => (String) eg. 2009-05-20
	 *              'daysValid' => (Int) eg. 30
	 *              'deliveryPoint' => (String) eg. EX-CMC Technologies, NSW. || EX-SUPPLIER NAME
	 *              'exchangeRate' => (String) eg. FIXED
	 *              'customsDuty' => (String) eg. NIL || 5%
	 *              'gst' => (String) eg. 10% EXTRA || Not Applicable for Export
	 *              'salesEngineer' => (String) eg. Karl Cordes || Con Carpis || Kenan Fernandes etc
	 *          );
	 *
	 *
	 */

	if($enquiry['Enquiry']['gst'] == 1) {
	    $gstPhrase = "10% EXTRA";
	}
	else {
	    $gstPhrase = "Not Applicable for Export";
	}

	$commercialDetails = array (
		'deliveryTime' => strtoupper($quote['Quote']['delivery_time']),
		'paymentTerms' => strtoupper($quote['Quote']['payment_terms']),
		'dateIssued' => $quote['Quote']['date_issued'],
		'validFor' => $quote['Quote']['days_valid'],
		'deliveryPoint' => strtoupper($quote['Quote']['delivery_point']),
		'exchangeRate' => strtoupper($quote['Quote']['exchange_rate']),
		'customsDuty' => strtoupper($quote['Quote']['customs_duty']),
		'gst' => strtoupper($gstPhrase),
		'salesEngineer' => strtoupper($user['User']['first_name'].' '.$user['User']['last_name'])





	);

	$this->set('commercialDetails', $commercialDetails);

	//debug($quote);
	//debug($commercialDetails);



	$this->set('quote', $quote);
	$this->set('enquiry', $enquiry);

	$this->set('principlesList', $this->Quote->Enquiry->Principle->find('list'));

	$this->set('products', $quoteProducts);



    }


    function ajaxpdf($id = null) {
	//Configure::write('debug',0);
	if(empty($this->data)) {
	    $this->Session->setFlash(__('Invalid Quote', true));
	    $this->redirect(array('controller'=>'enquiries', 'action'=>'index'));
	}
	else {
	    $id = $this->data['Quote']['id'];

	    $quote = $this->Quote->findById($id);
	    //$customer = $this->Quote->Enquiry->Customer->read(null, $quote['Enquiry']['customer_id']);
	    $enquiry = $this->Quote->Enquiry->find('first', array('conditions' => array('Enquiry.id' => $quote['Quote']['enquiry_id'])));


	    $quoteProducts = $this->Quote->LineItem->find('all', array('recursive' => 1, 'conditions' => array('LineItem.quote_id' => $id),
		    'order' => array('LineItem.item_number ASC'))
	    );

	    $user = $this->Quote->Enquiry->User->find('first', array('conditions' => array('User.id' => $enquiry['Enquiry']['user_id'])));




	    /**
	     * Call the commercial Comments. Need to have already figured out what page to do this on..
	     *
	     * * Passing a data structure in the following format.
	     *
	     * $details = array(
	     *              'deliveryTime' => (String) eg. 2-3
	     *              'paymentTerms => (String) eg. 100% PAYMENT WITH ORDER || NET 30 DAYS FOR APPROVED ACCOUNTS
	     *              'dateIssued' => (String) eg. 2009-05-20
	     *              'daysValid' => (Int) eg. 30
	     *              'deliveryPoint' => (String) eg. EX-CMC Technologies, NSW. || EX-SUPPLIER NAME
	     *              'exchangeRate' => (String) eg. FIXED
	     *              'customsDuty' => (String) eg. NIL || 5%
	     *              'gst' => (String) eg. 10% EXTRA || Not Applicable for Export
	     *              'salesEngineer' => (String) eg. Karl Cordes || Con Carpis || Kenan Fernandes etc
	     *          );
	     *
	     *
	     */

	    if($enquiry['Enquiry']['gst'] == 1) {
		$gstPhrase = "10% EXTRA";
	    }
	    else {
		$gstPhrase = "Not Applicable for Export";
	    }

	    $commercialDetails = array (
		    'deliveryTime' => strtoupper($quote['Quote']['delivery_time']),
		    'paymentTerms' => strtoupper($quote['Quote']['payment_terms']),
		    'dateIssued' => $quote['Quote']['date_issued'],
		    'validFor' => $quote['Quote']['days_valid'],
		    'deliveryPoint' => strtoupper($quote['Quote']['delivery_point']),
		    'exchangeRate' => strtoupper($quote['Quote']['exchange_rate']),
		    'customsDuty' => strtoupper($quote['Quote']['customs_duty']),
		    'gst' => strtoupper($gstPhrase),
		    'salesEngineer' => strtoupper($user['User']['first_name'].' '.$user['User']['last_name'])





	    );

	    $this->set('commercialDetails', $commercialDetails);

	    //debug($quote);
	    //debug($commercialDetails);



	    $this->set('quote', $quote);
	    $this->set('enquiry', $enquiry);



	    $this->set('products', $quoteProducts);
	}


    }




    /**
     * Revise an existing quote.
     *
     * Might make this AJAXy in the future. For now, I just want to make it work
     * Process is:
     *   1.Check what Quote ID we're revising
     *   2. Find that quote
     *   3. find the Line Items in this quote
     *   4. Make a new Quote.
     *   5. Make new copies of the line items referring to that quote
     *   6. Make copies of the QuotePages
     *
     */
    function revise($id) {

	if(!$id) {
	    $this->Session->setFlash(__('Invalid Quote', true));
	    $this->redirect(array('controller'=>'enquiries', 'action'=>'index'));
	}
	else {
	    $quoteid = $id;
	    $quote = $this->Quote->read(null,$id);
	    $enquiryid = $quote['Quote']['enquiry_id'];


	    $number_of_revisions = $this->Quote->findCount('Quote.enquiry_id ='. $enquiryid);
	    $number_of_revisions;

	    //debug($quote);

	    //	$this->Quote->create();
	    $this->data['Quote'] = $quote['Quote'];
	    $this->data['Quote']['id'] = null;
	    $this->data['Quote']['created'] = null;
	    $this->data['Quote']['modified'] = null;
	    $this->data['Quote']['revision'] = $number_of_revisions;
	    $this->data['Quote']['enquiry_id'] = $enquiryid;

	    foreach($quote['LineItem'] as $item) {
		$item['id'] = null;
		$item['quote_id'] = null;
		$this->data['LineItem'][] = $item;
	    }

	    
	    //debug($this->data);

	    if ($this->Quote->saveAll($this->data)) {
		$quoteid = $this->Quote->id;
		$this->Session->setFlash(__('Created Quote Revision '.$number_of_revisions, true));
		$this->redirect(array('action'=>'view/'.$quoteid));
	    }




	}

    }


}
?>