<?php
class Attachment extends AppModel {

	var $name = 'Attachment';
	var $validate = array(
		'principle_id' => array('numeric'),
		'name' => array('notempty'),
		'type' => array('notempty'),
		'size' => array('numeric'),
		'archived' => array('numeric'),
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $belongsTo = array(
		'Principle' => array(
			'className' => 'Principle',
			'foreignKey' => 'principle_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

	var $hasMany = array(
		'DocumentAttachment' => array(
			'className' => 'DocumentAttachment',
			'foreignKey' => 'attachment_id'
		)
	);


	// Based on comment 8 from: http://bakery.cakephp.org/articles/view/improved-advance-validation-with-parameters

	function isUploadedFile($params){
		$val = array_shift($params);
		if ((isset($val['error']) && $val['error'] == 0) ||
			(!empty( $val['tmp_name']) && $val['tmp_name'] != 'none')) {
				return is_uploaded_file($val['tmp_name']);
			}
		return false;
	}


	/**
	 * Passed a PHP upload 
	 * array('name', 'type', 'tmp_name', 'error' 'size').
	 *
	 * Move the uploaded file to the storage directory
	 * and return a cake array for insertion.
	 *
	 */

	function process_attachment($attachment) {

		$upload = $attachment['Attachment']['file'];

		$new_filename = Configure::read('attachments_directory').$upload['name'];
		if(!file_exists($new_filename)) {
			move_uploaded_file($upload['tmp_name'], $new_filename);

			$attachment['Attachment']['filename'] = $upload['name'];
			$attachment['Attachment']['file'] = $new_filename;
			$attachment['Attachment']['size'] = $upload['size'];
			$attachment['Attachment']['type'] = $upload['type'];
			return $attachment;

		}
		return false;

	}

}
?>
