<?php

class EnquiriesController extends AppController {

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

  var $paginate = array(

    'contain' => false,
    'limit' => 150,
	'order'=>array('Enquiry.id' => 'desc'),
  );

  var $components = array('RequestHandler', 'Email');

  //var $cacheAction = "1 hour";



  function index() {
    $this->Enquiry->recursive = 0;
    $this->set('enquiries', $this->paginate());
    $status_list = $this->Enquiry->Status->getJSON();
    $this->set('status_list', $status_list);
    $classNames = $this->Enquiry->Status->getClassNamesJSON();
    $this->set('class_names', $classNames);

    //debug($this->paginate());
    //	$this->set('status_list', $this->Enquiry->Status->find('list'));
  }

  function view($id = null) {
    if (!$id) {
      $this->Session->setFlash(__('Invalid Enquiry.', true));
      $this->redirect(array('action'=>'index'));
    }
    //$enquiry = $this->Enquiry->read(null, $id);
    //$enquiry = $this->Enquiry->find('first', array('recursive' => 1, 'conditions' => array('Enquiry.id'=>$id)));
    $enquiry = $this->Enquiry->read(null, $id);
    $this->set('enquiry', $enquiry);


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

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

    //$this->set('quotes', $enquiry['Quote']);
    $this->set('quotes', $this->Enquiry->Quote->find('all', array('conditions'=>array('Quote.enquiry_id'=>$id), 'order'=>'Document.revision DESC')));

    $this->set('invoices', $this->Enquiry->Invoice->find('all', array('conditions' => array('Invoice.enquiry_id' => $id), 'order'=>'Document.revision DESC')));

    $this->pageTitle = "Enquiry: ".$enquiry['Enquiry']['title'];


    //$this->set('number_of_files', $this->Enquiry->EnquiryFile->find('count', array('conditions' => array('EnquiryFile.enquiry_id'=>$id))));
    $this->set('principle_emails', $this->Enquiry->Principle->PrincipleContact->findAllByPrincipleId($enquiry['Enquiry']['principle_id']));

    $this->set('jobs', $this->Enquiry->Job->find('all', array('conditions'=>array('Job.enquiry_id'=>$id, ),'order'=>'Job.id DESC')));
    $this->set('order_acknowledgements', $this->Enquiry->OrderAcknowledgement->find('all', array('conditions'=>array('OrderAcknowledgement.enquiry_id'=>$id), 'order'=>'OrderAcknowledgement.id DESC')));

    if($enquiry['Enquiry']['billing_address_id'] != 0) {
      $this->set('billingaddress', $this->Enquiry->BillingAddress->findById($enquiry['Enquiry']['billing_address_id']));
    }

    if($enquiry['Enquiry']['shipping_address_id'] != 0) {
      $this->set('shippingaddress', $this->Enquiry->ShippingAddress->findById($enquiry['Enquiry']['shipping_address_id']));
    }

  }


    /*    function add() {
     $this->set('users',$this->Enquiry->User->find('list', array('conditions'=>array('User.type'=>'user', 'User.enabled'=>true))));
    }*/



  function add() {

    if(empty($this->data)) {
      if(isset($this->params['named']['customerid'])) {
        $customer = $this->Enquiry->Customer->findById($this->params['named']['customerid']);
      }
      else {
        $this->Session->setFlash(__('The customer must already exist in the database. Please add Enquiries to an existing Customer', true));
        $this->redirect(array('action'=>'index'));
      }
    }

    if(isset($customer)) {
      /* Check if the customer exists in the database - otherwise send the user back to step 1*/
      if(!$customer) {
        $this->Session->setFlash(__('The customer must already exist in the database. Please try again', true));
        $this->redirect(array('action'=>'add'));
      }

      $this->__showPage2($customer);
      $this->render();

    }

    if (!empty($this->data)) {
      $customer = $this->Enquiry->Customer->findById($this->data['Enquiry']['customer_id']);
      $principle = $this->Enquiry->Principle->findById($this->data['Enquiry']['principle_id']);
      $this->data['Enquiry']['principle_code'] = $principle['Principle']['code']; //Store which principle code this enquiry belongs to.
      //Sanitize::clean($this->data);
      if(isset($this->data['Contact']['new'])) {
        if($this->data['Contact']['new']) {
          $this->Enquiry->Contact->save($this->data);
          $this->data['Enquiry']['contact_id'] = $this->Enquiry->Contact->id;
        }
      }
      $this->Enquiry->set($this->data);
      if($this->Enquiry->validates()) {

        $enquiryno = $this->__generateEnquiryNumber($this->data);
        $this->data['Enquiry']['title'] = $enquiryno;
        $this->Enquiry->create();
        if ($this->Enquiry->save($this->data)) {
          $id = $this->Enquiry->id;
          if($this->data['Enquiry']['send_enquiry_email'] == 1) {
            $this->__sendNewEnquiryEmail($id); //Will change this to be the queue at some point.
          }
          else {
            $this->Session->setFlash(__('The Enquiry has been saved but the Contact has NOT been emailed, as you requested.', true));
            $this->redirect(array('action'=>'view/'.$id), null, false);
          }
        }
        else {
          $this->Session->setFlash(__('The Enquiry could not be saved. Please, try again.', true));
          $this->__showPage2($this->Enquiry->Customer->findById($this->data['Enquiry']['customer_id']));
        }
      }
      else {

        $this->set('errors', $this->Enquiry->invalidFields());
        $this->__showPage2($customer);
        $this->render();


      }

    }
  }

  /* Internal function to display page 2 of the Add Enquiry Form Wizard
   * to help make the flow-control logic of the add function clearer.
   *  */
  function __showPage2($customer) {

    /* Combine the first_name and last_name for the Contact Drop Down Box */
    $contacts = $this->Enquiry->Contact->find('all', array('conditions' => array('Contact.customer_id' => $customer['Customer']['id'])));
    $contacts = Set::Combine($contacts, '{n}.Contact.id', array('{0} {1}', '{n}.Contact.first_name', '{n}.Contact.last_name'));
    $states = $this->Enquiry->State->find('list');
    $countries = $this->Enquiry->Country->find('list', array('order'=> 'Country.name asc'));
    $principles = $this->Enquiry->Principle->find('list', array('order' => 'Principle.name asc'));
    $statuses = $this->Enquiry->Status->find('list');
    $users = $this->Enquiry->User->find('list', array('fields' => array('User.id', 'User.username'), 'conditions'=>array('User.type'=>'user', 'User.archived' => 0)));
    $this->set(compact('users', 'customers', 'states', 'countries', 'principles', 'statuses', 'contacts', 'customer'));
    $customerAddresses = $this->Enquiry->BillingAddress->find('all', array('conditions'=>array('BillingAddress.customer_id' => $customer['Customer']['id'])));
    $this->set('billing_addresses', $customerAddresses);
    $this->set('shipping_addresses', $customerAddresses);
    $this->set('errors', $this->Enquiry->invalidFields());
    /* Feels like an ugly hack. But it gets the desired effect and it will do for now */

    if(isset($customerAddresses[0]['BillingAddress'])) {
      $billing_address_list[0] = "No Address Selected";
      foreach ($customerAddresses as $address) {
        $i = $address['BillingAddress']['id'];
        $billing_address_list[$i] = $address['BillingAddress']['address'].'<br>'.$address['BillingAddress']['city'].' '.$address['State']['name'].' '.$address['BillingAddress']['postcode'].'<br>'.up($address['Country']['name']).'<br><br>';
      }
      $this->set('billing_addresses_list', $billing_address_list);
      $this->set('shipping_addresses_list', $billing_address_list);
    }
    else {
      $this->set('billing_addresses_list', 'No Addresses exist for this Customer. Please add one');
      $this->set('shipping_addresses_list', 'No Addresses exist for this Customer. Please add one');
    }
  }


  /* Add enquiry_id to the Email Queue */

  function __addToQueue($id) {
    $enquiry = $this->Enquiry->read(null, $id);
    $this->Enquiry->EnquiryEmailQueue->create();
    $this->data['EnquiryEmailQueue']['enquiry_id'] = $enquiry['Enquiry']['id'];
    if ($this->Enquiry->EnquiryEmailQueue->save($this->data)) {
      $this->Session->setFlash(__('The Enquiry has been saved and the Enquiry notification email has been added to the Queue', true));
      $this->redirect(array('action'=>'view/'.$enquiry['Enquiry']['id']), null, false);

    }
    else {
      $this->Session->setFlash(__('The Enquiry has been saved but the notification email could not be added to the Queue.', true));
      $this->redirect(array('action'=>'view/'.$enquiry['Enquiry']['id']), null, false);
    }
  }

  /* Generate Enquiry number and return it as a string */

  function __generateEnquiryNumber($data) {
    $state =  $this->Enquiry->State->findById($data['Enquiry']['state_id']);
    $principle = $this->Enquiry->Principle->findById($data['Enquiry']['principle_id']);
    /* Generate the enquiry number for this enquiry */
    /* CMC Enquiry number format is:
     * CMC<INCREMENTAL_NUMBER><STATE_INITIAL>E<PRINCIPLE_CODE><NO_OF_ENQ_FOR_THIS_PRINCIPLE_CODE>-<NO_OF_ENQ_FOR_THIS_PRINCIPLE_CODE_IN_THIS_STATE>
     * eg. CMC1245NE351234-456 */

    $enquiryid = $this->Enquiry->findCount(); /* Find what number we are - CMCXXXX  */
    $enquiryoffset = 7882; //What Number Enquiry we were at before using this package.
    $enquiryid += $enquiryoffset;
    $enquiryid++;
    /* Find how many enquiries have been for this principle code */
    $principleenquiries = $this->Enquiry->findCount('principle_code ='. $principle['Principle']['code']);


    /* Principle Code Offsets - Existing Number of Enquiries for each Principle Code */
    $principlecode_offset = array(	15 => 207, 	//ELMAC, AMAL
      20 => 51,	//T and B Electronic
      25 => 2062,	//ATEX,Brilex,Marston
      35 => 2067, //Mid-West Instrument, DP
      36 => 47,	//Reading Technologies
      37 => 2040,	//Eldridge, Smart Measurement, Alia
      65 => 2212,	//Papenmeier, Herberts Industrieglas
      85 => 586,	//Analytical Systems, Misc
      95 => 181); //Comet, T and D.
    if(array_key_exists($principle['Principle']['code'], $principlecode_offset)) {
      	$principleenquiries += $principlecode_offset[$principle['Principle']['code']]; //Add the offset.
    } 
      
    $principleenquiries++;



    /* Find how many enquiries have been for this principle code in this state */
    /* This aspect of the enquiry number is not useful anymore. Made redundant thanks to mySQL queries.
     * But this has been done for backwards-compatablity with existing enquiry numbers */  
    $principleconditions = array
      (
        "Enquiry.principle_code"   => $principle['Principle']['code'],
        "Enquiry.state_id" => $data['Enquiry']['state_id']
      );

    $stateprincipleenquiries = $this->Enquiry->findCount($principleconditions);

    /*Add the offsets for the State Principle Enquiries for each Code */
    $stateprinciple_offset = array(
      //Elmac, Amal
      15 => array("NSW" => 39, "VIC" => 38, "TAS" => 58,
      "ACT" => 0, "QLD" => 30, "NT" => 0,
      "WA" => 19, "SA" => 8, "Overseas" => 1),
      //T and B Electronic
      20 => array("NSW" => 14, "VIC" => 6, "TAS" => 0,
      "ACT" => 0, "QLD" => 8, "NT" => 0,
      "WA" => 12, "SA" => 1, "Overseas" => 5),
      //ATEX,Brilex,Marston
      25 => array("NSW" => 580, "VIC" => 599, "TAS" => 186,
      "ACT" => 0, "QLD" => 254, "NT" => 3,
      "WA" => 541, "SA" => 72, "Overseas" => 625),
      //Mid-West Instrument, DP
      35 => array("NSW" => 549, "VIC" => 851, "TAS" => 9,
      "ACT" => 0, "QLD" => 245, "NT" => 15,
      "WA" => 470, "SA" => 508, "Overseas" => 154),
      //Reading Technologies
      36 => array("NSW" => 1, "VIC" => 3, "TAS" => 0,
      "ACT" => 0, "QLD" => 7, "NT" => 0,
      "WA" => 0, "SA" => 4, "Overseas" => 2),
      //Eldridge, Smart Measurement, Alia
      37 => array("NSW" => 204, "VIC" => 60, "TAS" => 1,
      "ACT" => 0, "QLD" => 130, "NT" => 1,
      "WA" => 44, "SA" => 25, "Overseas" => 18),
      //Papenmeier, Herberts Industrieglas
      65 => array("NSW" => 498, "VIC" => 537, "TAS" => 44,
      "ACT" => 0, "QLD" => 158, "NT" => 12,
      "WA" => 138, "SA" => 25, "Overseas" => 174),
      //Analytical Systems, Misc
      85 => array("NSW" => 3, "VIC" => 6, "TAS" => 0,
      "ACT" => 0, "QLD" => 1, "NT" => 0,
      "WA" => 2, "SA" => 2, "Overseas" => 0),
      //Comet, T and D.
      95 => array("NSW" => 34, "VIC" => 28, "TAS" => 6,
      "ACT" => 0, "QLD" => 29, "NT" => 0,
      "WA" => 9, "SA" => 8, "Overseas" => 31),
    );
    if(array_key_exists($principle['Principle']['code'], $stateprinciple_offset)) {
        $stateprincipleenquiries += $stateprinciple_offset[$principle['Principle']['code']][$state['State']['shortform']];
    }

    $stateprincipleenquiries++;
    /* Generate/set the enquiry number */
    $enquiryno = 'CMC'.$enquiryid.$state['State']['enqform'].'E'.$principle['Principle']['code'].$principleenquiries.
      '-'.$stateprincipleenquiries;
    return $enquiryno;
  }

  /* Autocomplete the customer name  - Used in: add.ctp */
  function completeCustomer() {

    $this->set('customers', $this->Enquiry->Customer->find('all', array(
      'conditions' => array(
        'Customer.name LIKE' => '%'.$this->data['Customer']['name'].'%'
      ),'fields' => array('Customer.name')
    )));
    $this->layout = 'ajax';

  }

  function email_format($a) {
    return "<".$a.">";
  }

  /* Moving this to the new Enquiry email sender. */
  function __sendNewEnquiryEmail($id) {

    //Setup the SMTP Options
    $this->Email->smtpOptions = Configure::read('smtp_settings');


    $this->Email->delivery = 'smtp';

    $enquiry = $this->Enquiry->read(null, $id);
    $this->Email->to = $this->email_format($enquiry['Contact']['email']);
    $this->Email->cc = array($this->email_format($enquiry['User']['email']));
    $this->Email->bcc = array($this->email_format('carpis@cmctechnologies.com.au'));

    $this->Email->subject = $enquiry['Enquiry']['title'].' - Your Enquiry has been Entered in our System - CMC Technologies';
    $this->Email->replyTo = $enquiry['User']['email'];
    $this->Email->from = 'CMC Technologies - Sales <sales@cmctechnologies.com.au>';
    $this->Email->template = 'enquiry_added';
    $this->Email->sendAs = 'both';
    $this->Email->charset = 'iso-8859-1';
    $this->set('enquiry', $enquiry);
    if($this->Email->send()) {
      $this->Session->setFlash(__('The Enquiry has been added and the Contact has been emailed', true));
      $this->redirect(array('action'=>'view/'.$id), null, false);
    }
    else {
      $this->set('smtp_errors', $this->Email->smtpError);
      die(print_r($this->Email->smtpError));
      $this->Session->setFlash(__('The Enquiry has been added but email to the contact has NOT been sent. Something went wrong.', true));
      $this->redirect(array('action'=>'view/'.$id), null, false);

    }

  }


  function edit($id = null) {
    if (!$id && empty($this->data)) {
      $this->Session->setFlash(__('Invalid Enquiry', true));
      $this->redirect(array('action'=>'index'));
    }
    if (!empty($this->data)) {

      if ($this->Enquiry->save($this->data)) {
        $this->Session->setFlash(__('The Enquiry has been saved', true));
        $this->redirect(array('action'=>'index'));
      } else {
        $this->Session->setFlash(__('The Enquiry could not be saved. Please try again.', true));
        $this->set('dump', $this->data);
      }
    }
    if (empty($this->data)) {
      $this->data = $this->Enquiry->read(null, $id);
    }
    $enquiry = $this->Enquiry->read(null, $id);
    $users = $this->Enquiry->User->find('list', array('fields' => array('User.id', 'User.username'), 'conditions'=>array('User.type'=>'user')));
    //$customer = $this->Enquiry->Customer->findById($enquiry['Enquiry']['customer_id']);

    $contacts = $this->Enquiry->Contact->find('all', array('conditions' => array('Contact.customer_id' => $enquiry['Enquiry']['customer_id'])));
    $contacts = Set::Combine($contacts, '{n}.Contact.id', array('{0} {1}', '{n}.Contact.first_name', '{n}.Contact.last_name'));
    //$state = $this->Enquiry->State->findById($enquiry['Enquiry']['state_id']);
    //$country = $this->Enquiry->Country->findById($enquiry['Enquiry']['country_id']);
    //$principle = $this->Enquiry->Principle->findById($enquiry['Enquiry']['principle_id']);
    $statuses = $this->Enquiry->Status->find('list');
    $principles = $this->Enquiry->Principle->find('list', array('conditions' => array('Principle.code' => $enquiry['Principle']['code'])));
    $customerAddresses = $this->Enquiry->BillingAddress->find('all', array('conditions'=>array('BillingAddress.customer_id' => $enquiry['Customer']['id'])));
    $this->set('billing_addresses', $customerAddresses);
    $this->set('shipping_addresses', $customerAddresses);

    /* Feels like an ugly hack. But it gets the desired effect and it will do for now */

    if(isset($customerAddresses[0]['BillingAddress'])) {
      $billing_address_list[0] = "No Address Selected";
      foreach ($customerAddresses as $address) {
        $i = $address['BillingAddress']['id'];
        $billing_address_list[$i] = $address['BillingAddress']['address'].'<br>'.$address['BillingAddress']['city'].' '.$address['State']['name'].' '.$address['BillingAddress']['postcode'].'<br>'.up($address['Country']['name']).'<br><br>';
      }
      $this->set('billing_addresses_list', $billing_address_list);
      $this->set('shipping_addresses_list', $billing_address_list);
    }
    else {
      $this->set('billing_addresses_list', 'No Addresses exist for this Customer. Please add one');
      $this->set('shipping_addresses_list', 'No Addresses exist for this Customer. Please add one');
    }


    $this->set(compact('enquiry', 'users','contacts','principles','statuses', 'addresses'));
  }

    /* function update_status($enquiryid) {
        $newid = $this->params['form']['value'];


        if($newid) {
            $this->Enquiry->id = $enquiryid;
            $this->Enquiry->saveField('status_id', $newid);
            $this->set('enquiry', $this->Enquiry->findById($enquiryid));
            $this->render('ajax');

        }

    }*/


  function update_status() {
    if($this->data) {

      $enquiry = $this->Enquiry->read(null, $this->data['Enquiry']['id']);
      $enquiry['Enquiry']['status_id'] = $this->data['Enquiry']['status_id'];

      $this->Enquiry->save($enquiry);

      $this->set('enquiry', $this->Enquiry->read(null,$enquiry['Enquiry']['id']));
    }

  }


  /**
   * For the search query form
   */
  function search() {

  }

  /**
   * Actually performs the searches
   */
  function doSearch() {
    if(!empty($this->data)) {
      $searchQuery = trim($this->data['Enquiry']['search_string']);



      $custConditions = array('Customer.name LIKE' => "%$searchQuery%");
      $enqConditions = array('Enquiry.title LIKE' => "%$searchQuery%");

      $words = explode(" ", $searchQuery);

      if(count($words) == 2) {
        $contactConditions = array('AND'=>array('Contact.first_name LIKE' => "%$words[0]%",
          'Contact.last_name LIKE' => "%$words[1]%"));
      }
      else {
        $contactConditions = array('OR'=>array('Contact.first_name LIKE' => "%$searchQuery%",
          'Contact.last_name LIKE' => "%$searchQuery%"));
      }

      $customerFields = array('Customer.id', 'Customer.name');
      $enquiryFields = array('Enquiry.id', 'Enquiry.title','Enquiry.created','Principle.short_name', 'Principle.name', 'Customer.name', 'Customer.id', 'Contact.first_name','Contact.last_name', 'Contact.id');
      $contactFields = array('Contact.id', 'Contact.type','Contact.customer_id', 'Contact.first_name','Contact.last_name', 'Customer.name');


      $customerResults = $this->Enquiry->Customer->find('all', array('conditions' => $custConditions, 'recursive'=>0, 'fields'=>$customerFields));
      $enquiryResults = $this->Enquiry->find('all', array('conditions'=>$enqConditions, 'recursive'=>0, 'fields'=>$enquiryFields));
      $contactResults = $this->Enquiry->Contact->find('all', array('conditions'=>$contactConditions, 'recursive'=>0, 'fields'=>$contactFields));

      $searchDone = true;

      $statuses = $this->Enquiry->Status->find('all', array('recursive'=>0));
      $status_list = array();
      foreach ($statuses as $status) {
        $statusid = $status['Status']['id'];
        $status_list[$statusid] = $status['Status']['name'];
      }
      $this->set('status_list', $status_list);


      $jobConditions = array('OR' =>array("Job.title LIKE" =>"%$searchQuery%",
        "Job.customer_order_number LIKE" =>"%$searchQuery%"));

      $jobResults = $this->Enquiry->Job->find('all', array('conditions'=>$jobConditions, 'recursive'=>1));


      $this->set(compact('customerResults', 'enquiryResults', 'contactResults', 'searchDone', 'status_list',
        'jobResults'));
      $this->layout = 'ajax';

    }



  }

  function mark_submitted($id = null) {
    if($id == null) {
      $this->Session->setFlash('Invalid Enquiry ID');
      $this->redirect(array('action'=>'index'));
    }
    else {
      $this->Enquiry->id = $id;
      $today = date("Y-m-d");
      $this->Enquiry->saveField('submitted', $today);
      $this->Session->setFlash('The Enquiry has been marked as submitted today ('.date('j M Y').')');
      $this->redirect(array('action'=>'index'));
    }



  }




  function view_user_enquiries($id = null) {
    if($id == null) {
      $this->Session->setFlash('Invalid Enquiry ID');
      $this->redirect(array('action'=>'index'));
    }
    else {
      $this->set('enquiries', $this->paginate('Enquiry', array('Enquiry.user_id' => $id)));


      $statuses = $this->Enquiry->Status->find('all', array('recursive'=>0));
      $status_list = array();
      foreach ($statuses as $status) {
        $statusid = $status['Status']['id'];
        $status_list[$statusid] = $status['Status']['name'];
      }
      $this->set('status_list', $status_list);
      $this->layout = 'ajax';
    }
  }


  function delete($id = null) {
	 if($id == null) {
      $this->Session->setFlash('Invalid Enquiry ID');
      $this->redirect(array('action'=>'index'));
	 }
	 else {
		$enquiry = $this->Enquiry->findById($id);
	 
		$enquiry['Enquiry']['archived'] = 1;

		$this->Enquiry->save($enquiry);

		$undo = '<a href="/enquiries/undelete/'.$id.'">Undo this</a>';

		$this->Session->setFlash('Enquiry '.$enquiry['Enquiry']['title'].' has been deleted. '.$undo);
		$this->redirect(array('action'=>'index'));
	 }
  }

  /** Could do it in a single method, but fuck it. */
  function undelete($id = null) {
	  
	  if($id == null) {
		$this->Session->setFlash('Invalid Enquiry ID');
		$this->redirect(array('action'=>'index'));
	 }
	 else {
		$enquiry = $this->Enquiry->findById($id);
	 
		$enquiry['Enquiry']['archived'] = 0;

		$this->Enquiry->save($enquiry);

		$undo = '<a href="/enquiries/delete/'.$id.'">Undo this</a>';

		$this->Session->setFlash('Enquiry '.$enquiry['Enquiry']['title'].' has been undeleted. '.$undo);
		$this->redirect(array('action'=>'index'));
	 }
  }

}
?>
