<?php
	require_once( $GLOBALS["site_root"]."/includes/widgets/Widget.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Job.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/JobQuote.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/MyMember.inc.php" );

	class JobQuoteAttachmentPane extends Widget {
		protected $jm = null;
		protected $jqm = null;
		protected $mmm = null;
		protected $job_quote_attachment_id = 0;
		protected $job_quote_attachment = array();

		public function __construct( $id = "JobPane" , $parent = null ) {
			parent::__construct( $id , $parent );
		}

		public function modifyGetPost( &$g , &$p ) {
			parent::modifyGetPost( $g , $p );
			if (isset( $this->aG["job_quote_attachment_id"] )) $this->job_quote_attachment_id = $this->aG["job_quote_attachment_id"];
		}

		protected function isJobQuoteAttachmentAvailable() {
			if (!$this->job_quote_attachment_id) return false;
			if (!isset( $this->job_quote_attachment["job_quote_id"] )) return false;
			if (!$this->mmm->isUserLoggedin()) return false;

			$user_id = $this->mmm->getLoggedinUserId();
			if (!$user_id) return false;
			return $this->jqm->isJobQuoteAvailableForUser( $this->job_quote["job_quote_id"] , $user_id );
		}

		protected function sendJobQuoteAttachment() {
			header( "Content-Type: " . $this->job_quote_attachment["attachment_mimetype"] );
			header( sprintf( "Content-Disposition: attachment; filename=\"%s\"",$this->job_quote_attachment["attachment_original_filename"] ) );
			$filename = $GLOBALS["site_root"].$this->job_quote_attachment["attachment_path"]."/".$this->job_quote_attachment["attachment_filename"];
			header( "Content-length: ".$this->job_quote_attachment["attachment_filesize"] );
			// TODO bufferelt kikuldes illene a nagy fileok miatt
			echo file_get_contents( $filename );
			exit();
		}

		public function handleEvents() {
			if (!$this->job_quote_attachment_id) return parent::handleEvents();
			$this->jm = new JobModel();
			$this->jqm = new JobQuoteModel();
			$this->mmm = new MyMemberModel();

			$this->job_quote_attachment = $this->jqm->getJobQuoteAttachment( $this->job_quote_attachment_id );
			if (!$this->job_quote_attachment) return parent::handleEvents();
			$this->job_quote = $this->jqm->getJobQuoteFromJobQuoteId( $this->job_quote_attachment["job_quote_id"] );
			if (!$this->job_quote) return parent::handleEvents();
			$this->job = $this->jm->getJobFromId( $this->job_quote["job_id"] );
			if (!$this->job) return parent::handleEvents();

			if ($this->isJobQuoteAttachmentAvailable()) $this->sendJobQuoteAttachment();
			return parent::handleEvents();
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$this->setParam( "bLoggedIn" , $this->mmm->isUserLoggedin() );
			$this->setParam( "bActiveSubscriber" , $this->mmm->isLoggedinMemberActiveSubscriber() );
			return parent::render();
		}
	}

?>
