<?php
class Job extends AppModel {

    var $name = 'Job';


    var $validate = array(
	    'title' => array('notempty'),

	    'enquiry_id' => array('numeric'),

	    /*    'date_order_received' => array('date'),

	    'domestic_freight_paid_by' => array('notempty'),
	    'sale_category' => array('notempty'),
	    'shipment_category' => array('notempty') */
    );




    //The Associations below have been created with all possible keys, those that are not needed can be removed
    var $belongsTo = array(

	    'Enquiry' => array(
			    'className' => 'Enquiry',
			    'foreignKey' => 'enquiry_id',
			    'conditions' => '',
			    'fields' => '',
			    'order' => '',
			    'counterCache' => true
	    ),

	    'Currency' => array(
			    'className' => 'Currency',
			    'foreignKey' => 'currency_id'
	    ),

	    'Customer' => array(
			    'className' => 'Customer',
			    'foreignKey' => 'customer_id'
	    )
    );

    var $hasAndBelongsToMany = array(
	    'PurchaseOrder' => array(
			    'className' => 'PurchaseOrder',
			    'joinTable' => 'jobs_purchase_orders',
			    'unique'    => true
	    ),
	    'Email' => array(
			    'className' => 'Email',
			    'joinTable' => 'emails_jobs',
	    ),

	    'Shipment' => array(
			    'className' => 'Shipment',
			    'joinTable' => 'shipments_jobs',
	    )
    );

    var $hasMany = array(
	    'OrderAcknowledgement' => array(
			    'className' => 'OrderAcknowledgement',
			    'foreign_key' => 'job_id'
	    )
    );


    function newJob($enquiry, $customerOrderNumber = null) {

	$this->create();

	$job_offset = 6141;

	$number_of_jobs = $this->findCount();
	$new_job_number = $job_offset + $number_of_jobs;

	$monthYearShort = strtoupper(date("My"));

	$jobLetter = $enquiry['State']['enqform'];

	$newJob = array();

	$newJob['Job']['title'] = $monthYearShort.$jobLetter."J".$new_job_number;
	$newJob['Job']['state_id'] = $enquiry['Enquiry']['state_id'];
	$newJob['Job']['customer_id'] = $enquiry['Enquiry']['customer_id'];
	$newJob['Job']['contact_id'] = $enquiry['Enquiry']['contact_id'];
	$newJob['Job']['enquiry_id'] = $enquiry['Enquiry']['id'];
	$newJob['Job']['date_order_received'] = date('Y-m-d');

	if(!empty($customerOrderNumber)) {
	    $newJob['Job']['customer_order_number'] = $customerOrderNumber;
	}

	if ($this->save($newJob)) {
	    
	    return $this->find('first',array('conditions'=>array('Job.id'=>$this->id)));
	}
	else {
	    return false;
	}
    }


}
?>