<?php
class JobsController extends AppController {

	var $name = 'Jobs';
	var $helpers = array('Html', 'Form', 'Text', 'Javascript', 'Number');

	var $components = array('RequestHandler');

	var $paginate = array(

		'contain' => false,
		'limit' => 200,
		'order'=>array('Job.id' => 'desc')

	);

	function index($showUnpaid = null, $showUnsent = null) {
		$this->Job->recursive = 1;



		if(!empty($showUnpaid) && !empty($showUnsent)) {

			$conditions = array(
				'Job.all_paid' => 0,
				'Job.all_sent' => 0,
			);
		}

		else if(!empty($showUnpaid)) {
			$conditions = array(
				'Job.all_paid' => 0,

			);
		}

		else if(!empty($showUnsent)) {
			$conditions = array(
				'Job.all_sent' => 0,
			);
		}
		else {
			$conditions = array();
		}

		$this->set('jobs', $this->paginate($conditions));

		$this->set('customers', $this->Job->Enquiry->Customer->find('list'));
		$this->set('currencies', $this->Job->Currency->find('list'));
		$this->set('principleList',$this->Job->Enquiry->Principle->find('list'));


		$this->set('sale_category_options', $this->sale_category_options());
		$this->set('sale_category_array', $this->sale_category_array());
		$this->set('job_type_options', $this->job_type_options());
		$this->set('shipment_category_options', $this->shipment_category_options());
		$this->set('freight_paid_by_options',$this->freight_paid_options());
		$this->set('gst_options', $this->gst_options());

	}

	/** Called via AJAX to get an editable row */
	function getEditableRow($id) {
		$this->layout = 'ajax';

		$job = $this->Job->find('first', array('conditions'=>array('Job.id'=>$id)));

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

		$this->data = $job;

		$this->set('shipment_category_options', $this->shipment_category_options());
		$this->set('yesNo', array(0=>'No', 1=>'Yes'));
		$this->set('currencies', $this->Job->Currency->find('list'));
		$this->set('sale_category_options', $this->sale_category_options());
		$this->set('sale_category_array', $this->sale_category_array());
		$this->set('job_type_options', $this->job_type_options());
		$this->set('freight_paid_by_options',$this->freight_paid_options());
		$this->set('gst_options', $this->gst_options());
		$this->set('job_status_options', $this->job_status_options());
		$this->set('principleList',$this->Job->Enquiry->Principle->find('list'));

	}

	/** Called via AJAX to get an viewable row */
	function getViewableRow($id) {
		$this->layout = 'ajax';
		$this->set('job', $this->Job->find('first', array('conditions'=>array('Job.id'=>$id))));


		$this->set('sale_category_options', $this->sale_category_options());
		$this->set('sale_category_array', $this->sale_category_array());
		$this->set('job_type_options', $this->job_type_options());
		$this->set('shipment_category_options', $this->shipment_category_options());
		$this->set('freight_paid_by_options',$this->freight_paid_options());
		$this->set('gst_options', $this->gst_options());
		$this->set('principleList',$this->Job->Enquiry->Principle->find('list'));


	}


	function reports() {
		$this->Job->recursive = 0;

		$jobs = $this->Job->find('all', array('fields'=>array('Job.date_order_received'), 'order'=>array('Job.date_order_received'=>'asc')));

		//$monthList = $this->getYearMonths($jobs);

		//$this->set('monthList', $monthList);


		$Fyears = $this->getFinancialYears($jobs);
		$this->set('Fyears',$Fyears);

	/*	$this->set('jobs', $jobs);
	$this->set('customers', $this->Job->Enquiry->Customer->find('list'));
	$this->set('currencies', $this->Job->Currency->find('list'));*/

	}



	function viewReport($year, $month = null) {
		$this->layout = 'ajax';


		if(isset($month) && isset($year)) { //After a Specific Month for a Year



			$startDate = $year.'-'.$month.'-01';

			$startDateTime = strtotime($startDate);

			$numberOfDaysInMonth = date('t', $startDateTime);

			$endDate = $year.'-'.$month.'-'.$numberOfDaysInMonth;

			$monthStrings = array(
				'01'=>'January',
				'02'=> 'February',
				'03'=>'March',
				'04'=> 'April',
				'05'=> 'May',
				'06'=> 'June',
				'07'=> 'July',
				'08'=> 'August',
				'09'=> 'September',
				'10'=> 'October',
				'11'=> 'November',
				'12' => 'December');



			$jobRangeTitle = $monthStrings[$month]." $year";
			$jobs = $this->Job->find('all', array('conditions'=>
				array('Job.date_order_received BETWEEN ? AND ?'=>array($startDate, $endDate)),
					'order'=>'Job.date_order_received ASC'));


		/*   $dateStringFormat = 'j F Y';
		$dateString['first'] = date($dateStringFormat, $firstDayUnix);
		$dateString['last'] = date($dateStringFormat, $lastDayUnix);
		 */
			$this->set('jobRangeTitle', $jobRangeTitle);

			$this->set('year', $year);
			$this->set('month', $month);


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

			$this->set('totals', $this->getTotals($jobs));

			$this->set('principleList',$this->Job->Enquiry->Principle->find('list'));

			$this->set('startDate',$startDate);
			$this->set('endDate',$endDate);


		}

		elseif(isset($year) && !isset($month)) { //Requested a whole Financial Year Jobs



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

			$lastDayUnix = $this->getLastDayFY($year);
			$firstDayUnix = $this->getFirstDayFY($year,true);


			$lastDayDate = date('Y-m-d', $lastDayUnix);
			$firstDayDate = date('Y-m-d', $firstDayUnix);

			$dateStringFormat = 'j F Y';

			$dateString['first'] = date($dateStringFormat, $firstDayUnix);
			$dateString['last'] = date($dateStringFormat, $lastDayUnix);


			if($year == 0) { //Jobs with an empty 'date_order_received
				$jobs = $this->Job->find('all', array('conditions'=>array('Job.date_order_received'=>'0000-00-000')));
				$jobRangeTitle = "Jobs without Order Received date";
			}
			else { //We're looking for Jobs that have an 'date_order_received'

				$jobs = $this->Job->find('all', array('conditions'=>
					array('Job.date_order_received BETWEEN ? AND ?'=>array($firstDayDate, $lastDayDate))
				)
			);

				$lastYear = $year - 1;
				$jobRangeTitle = $lastYear.' - '.$year.' ('.$dateString['first']." to ".$dateString['last'].')';

			}

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

			$this->set('jobs',$jobs);
			$this->set('principleList',$this->Job->Enquiry->Principle->find('list'));
			$this->set('sale_category_options', $this->sale_category_options());
			$this->set('sale_category_array', $this->sale_category_array());
			$this->set('job_type_options', $this->job_type_options());
			$this->set('shipment_category_options', $this->shipment_category_options());
			$this->set('freight_paid_by_options',$this->freight_paid_options());
			$this->set('gst_options', $this->gst_options());

			$this->set('totals', $this->getTotals($jobs));
			// print_r($totals);
			//print_r($jobs);
		}

		else {
			echo "Failure";
		}


		//$this->set('jobs', )



	}


	/**
	 * Generate aggregates for the financial data in $jobs.
	 *
	 * Procedure:
	 * 1. Loop over the $jobs.
	 * 2. Check if this job is cancelled or on hold.
	 * 3. If not, add each $job[$field] to the total.
	 *
	 * @param <type> $jobs
	 */
	function getTotals($jobs) {

		$fields = array(
			'company_gross_sales_aud' => 'total',
			'net_sales_aud' =>'total',
			'gross_profit_aud' => 'total',
			'net_export_sales_aud' => 'total',
			'gross_profit_exports_aud' => 'total',
			'gp_percent' => 'average',
			'gross_australian_sales_foreign_currency' => 'total',
			'net_australian_sales_foreign_currency' => 'total',
			'gross_profit_value_australian_sales_foreign_currency' => 'total',
			'gross_export_sales_foreign_currency' => 'total',
			'net_export_sales_foreign_currency' => 'total',
			'gross_profit_value_after_discount_exports_foreign_currency' => 'total',
			'gross_commissions' => 'total',
			'net_commissions' => 'total'
		);

		$totals = array();

		foreach($fields as $field => $action) {
			$totals[$field] = 0;
		}


		$jobCount = 0;
		foreach($jobs as $job) {
			if($job['Job']['job_status'] == 'JOB CANCELLED' ||
				$job['Job']['job_status'] == 'JOB ON HOLD' ) {
					continue; //Don't total cancelled or on hold jobs.
				}
			else { //Total all other jobs.

				foreach(array_keys($job['Job']) as $key) {
					if(isset($fields[$key])) {
						$totals[$key] += $job['Job'][$key];
					}
				}

				$jobCount++;
			}
		}

		foreach($totals as $key => $value) {
			if($fields[$key] == 'average') {
				$avg = $value / $jobCount;
				$totals[$key] = $avg;
			}
		}

		return $totals;
	}


	function getFinancialYears($jobs) {

		$Fyears = array();

		foreach($jobs as $job) {

			$time = strtotime($job['Job']['date_order_received']);
			$year = date('Y', $time); //ISO-8601 year number


			$startFYunix = $this->getFirstDayFY($year); //1 July of $year.

			if($time < $startFYunix) { //Date is before 1 July $year.
				$lastYear = $year - 1;

				if(!isset($Fyears[$year])) {
					$Fyears[$year] = 1;
				}
				else {
					$Fyears[$year]++;
				}
			}
			else { //Date is After 1 July $year.

				$nextYear = $year + 1;
				if(!isset($Fyears[$nextYear])) {
					$Fyears[$nextYear] = 1;
				}
				else {
					$Fyears[$nextYear]++;
				}
			}

		}
		krsort($Fyears); //Sort the array in reverse order, most recent to oldest.
		return $Fyears;
	}

	/**
	 *
	 * @param <type> $year
	 * @param <type> $prevYear
	 * @return <type>

	 function getFirstDayFY($year,$prevYear = false) {
		 if($prevYear == false) {
			 return mktime(0,0,0,7,1,$year);

}
else {
	return mktime(0,0,0,7,1,$year-1);
}
}

*
	*
	* /**

	*
	* @param <type> $year
	* @return <int>

	function getLastDayFY($year) {
		return mktime(23,59,59,6,30,$year);

}

function getMonthsFY($year) {

} */


	function job_status_options() {
		$options = array('ORDER RECEIVED FROM CUSTOMER',
			'ORDER PLACED ON PRINCIPLE - WAITING ON DELIVERY',
			'GOODS SHIPPED TO CUSTOMER',
			'WAITING ON DELIVERY',
			'MULTIPLE SHIPMENTS CMC WAITING ON ANOTHER DELIVERY',
			'GOODS DELIVERED TO CUSTOMER',
			'JOB CANCELLED',
			'JOB ON HOLD',
			'CUSTOMER TO PAY 100% WITH ORDER'
		);
		$options = $this->buildEnumOpts($options);
		return $options;
	}


	/**
	 * For the 'sale_category' column.
	 */
	function sale_category_options() {

		$options['Australian Sale'] = array(
			0 => "AS: Australian Customer & Australian Destination (GST Applies)",
			1 => "AS: Overseas Customer & Australian Destination (GST Applies)",
			2 => "AS: Commission from Australian Company or Supplier (GST Applies)",

		);

		$options['Exports'] = array(
			3 => "EX: Overseas Customer & Overseas Destination (no GST)",
			4 => "EX: Australian Customer & Overseas Destination (no GST)",
			5 => "EX: Commission from Overseas Company (no GST)"
		);


		return $options;
	}

	/** For viewing the sale Cat */
	function sale_category_array() {
		$options = array(
			0 => "AS: Australian Customer & Australian Destination (GST Applies)",
			1 => "AS: Overseas Customer & Australian Destination (GST Applies)",
			2 => "AS: Commission from Australian Company or Supplier (GST Applies)",
			3 => "EX: Overseas Customer & Overseas Destination (no GST)",
			4 => "EX: Australian Customer & Overseas Destination (no GST)",
			5 => "EX: Commission from Overseas Company (no GST)"
		);

		return $options;

	}





	/**
	 * Build the Array for 'job_type'
	 */
	function job_type_options() {

		//$options = array('INDENT','STOCK','COMMISSION','SERVICE');
		$options = array('GOODS','SERVICES');
		$enumOpts = $this->buildEnumOpts($options);
		return $enumOpts;
	}

	function shipment_category_options() {
		$options = array(
			0 => '',
			1 => 'Indent - via CMC',
			2 => 'Direct - Principle to final',
			3 => 'Stock',
			4 => 'No Shipment'
		);

		return $options;
	}

	function freight_paid_options() {
		$options = array('CMC', 'CUSTOMER');
		return $this->buildEnumOpts($options);
	}

	function gst_options() {
		$options = array(1=>'YES', 0=>'NO');
		return $options;
	}



	function buildEnumOpts($options) {

		$enumOpts = array();
		foreach($options as $opt) {
			$enumOpts[$opt] = $opt;
		}
		return $enumOpts;
	}


	function ajax_edit() {
		if(!empty($this->data)) {
			if ($this->Job->save($this->data)) {
				echo "SUCCESS";
			}
			else {
				echo "FAILURE";
			}


		}
		else {
			return;
		}

	}



	function view($id = null) {
		if (!$id) {
			$this->flash(__('Invalid Job', true), array('action'=>'index'));
		}

		$job = $this->Job->read(null, $id);

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




		$this->set('job', $job);
		$this->set('customer', $this->Job->Enquiry->Customer->findById($job['Enquiry']['customer_id']));
		$this->set('principles', $this->Job->PurchaseOrder->Principle->find('list'));
		$this->pageTitle = $job['Job']['title'];

	}

	function save_jobs() {
		if(isset($this->data)) {
			//$data = json_decode($this->data);

			// print_r($this->data);
		}

	}


	function ajax_add($enquiryID) {
		$this->layout  = 'ajax';

		if(!isset($enquiryID)) {
			return;
		}
		else {

			$enquiry = $this->Job->Enquiry->find('first', array('conditions'=>array('Enquiry.id'=>$enquiryID)));
			$result = $this->Job->newJob($enquiry);

			if (is_array($result)) {
				echo "SUCCESS";
			}
			else {
				echo "FAILURE";
			}
		}
	}


	function __isNotEmptyDate($date) {
		if($date == "0000-00-00") {
			return true;
		}
		else {
			return false;
		}
	}


	function autocomplete() {
		$this->layout = 'ajax';

		$query = strtolower($_GET["term"]);

		//$this->set('customers_json', print_r($this->data));

		if($query == null) {
			return;
		}

		App::import('Core', 'Sanitize');

		$query = Sanitize::clean($query);

		$jobs = $this->Job->find('list', array(
			'conditions' => array(
				'Job.title LIKE' => '%'.$query.'%'
			),'fields' => array('Job.title'),
				'order' => array('Job.title ASC')

			));

		//print_r($POs);

		foreach ($jobs as $id => $job) {
			$job_list[] = array('id'=> $id, 'label' => $job);
		}

		$jobs_json = json_encode($job_list);

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

	}


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

		if(!$id) {
			echo "FAILURE";
		}
		else {
			$this->Job->read(null, $id);
			$this->Job->set('deleted', true);
			if($this->Job->save()) {
				echo "SUCCESS";
			}
			else {
				echo "FAILURE";
			}
		}
	}


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

		if(!$id) {
			echo "FAILURE";
		}
		else {
			$this->Job->read(null, $id);
			$this->Job->set('deleted', false);
			if($this->Job->save()) {
				echo "SUCCESS";
			}
			else {
				echo "FAILURE";
			}
		}
	}



	function getdata($id) {
		$job = $this->Job->read(null, $id);
		$this->set('job_json', json_encode($job));
	}


	/**
	 * Need to fix the customer_id which hasn't been set for these 500odd records.
	 *
	 * Will fetch the right ID the same way the Index does, then update each record.
	 */
	/*function fixJobs() {

	$jobs = $this->Job->find('all');

	foreach($jobs as $job) {
		$this->Job->id = $job['Job']['id'];
		$this->data = $job;

		$this->data['Job']['customer_id'] = $job['Enquiry']['customer_id'];
		$this->data['Job']['state_id'] = $job['Enquiry']['state_id'];
		$this->data['Job']['contact_id'] = $job['Enquiry']['contact_id'];
		$this->Job->save($this->data);

	}

	$this->set('jobs', $this->Job->find('all'));




	}*/




}
?>
