<?php
	require_once( $GLOBALS["site_root"]."/includes/widgets/Widget.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/FrontendTextbox.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/FrontendTextarea.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/FrontendSelect.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/FrontendSubmit.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/FrontendButton.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/JobAttachments.inc.php" ) ;
	require_once( $GLOBALS["site_root"]."/includes/widgets/CommunityToolbar.inc.php" ) ;
	require_once( $GLOBALS["site_root"]."/includes/widgets/JobDetails.inc.php" );

	require_once( $GLOBALS["site_root"]."/includes/models/MyMember.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Member.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/User.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/Constants.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Globals.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/UserLog.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/TemplateMail.inc.php" );

	require_once( $GLOBALS["site_root"]."/includes/urlgen/TranslatorJobs.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/urlgen/Article.inc.php" );

	class JobQuotePane extends Widget {
		protected $model_mymember;
		protected $oQuotePricing;
		protected $oQuote;
		protected $oAttachments;

		protected $oTemplates;
		protected $oTemplateName;
		protected $oLoadTemplate;
		protected $oSaveTemplate;
		protected $oDeleteTemplate;
		protected $oSubmit;
		protected $job_id;
		protected $job;

		protected $bPreview;

		protected $bLoggedin = false;
		protected $bActiveSubscriber = false;
		protected $bAvailable = false;

		public function setLoggedin( $v ) { $this->bLoggedin = $v; }
		public function setActiveSubscriber( $v ) { $this->bActiveSubscriber = $v; }
		public function setAvailable( $v ) { $this->bAvailable = $v; }
		public function setJobId( $v ) { $this->job_id = $v; }

		public function __construct( $id , $parent ) {
			parent::__construct( $id , $parent );
			$this->model_mymember = new MyMemberModel();
		}

		public function modifyGetPost( &$g , &$p ) {
			$retval = parent::modifyGetPost( $g , $p );
			$this->oCommunityToolbar = new CommunityToolbar( "CommunityToolbar" , $this );
			$this->oJobDetails = new JobDetails( "JobDetails" , $this );
			if ($this->bAvailable) {
				$this->oQuotePricing = new FrontendTextbox( "quote_pricing" , $this );
				$this->oQuote = new FrontendTextarea( "quote" , $this );
				$this->oAttachments = new JobAttachments( "attachments" , $this );
				$this->oTemplates = new FrontendSelect( "templates" , $this );
				$this->oTemplateName = new FrontendTextbox( "template_name" , $this );
				$this->oLoadTemplate = new FrontendButton( "btn_load_template" , $this );
				$this->oSaveTemplate = new FrontendButton( "btn_save_template" , $this );
				$this->oDeleteTemplate = new FrontendButton( "btn_delete_template" , $this );
			}
			$this->oSubmit = new FrontendSubmit( "smb_quote" , $this );
			$this->oSubmit->setValue( __("quotepage_Send_quote","attr") );
			return $retval;
		}
		
		protected function generateEmptyValidator() {
			return "if (\$(this).attr(\"value\").length)
				\$(this).removeClass( \"invalid\" );
			else
				\$(this).addClass( \"invalid\" );";
		}

		protected function addEmptyValidator( $widget ) {
			FNTHPage::addUniquePageFullInit(
				sprintf( "\$(\"#%s\").change( function() { %s } );\n",
					$widget->getId(),$this->generateEmptyValidator() ) );
		}

		protected function initializeWidgets() {
			$this->oCommunityToolbar->setCommunityLinks( false );
			$title = ($this->bPreview) ?
				sprintf( "%s (%s)" , __("quotepage_My_quote") ,  __("preview") ) :
				__("quotepage_My_quote");

			if ($this->bPreview) {
				fo3_object_change_warning( "content_widget" , __("confirm_Leave_job_quote_page") , true );
			}

			$this->oCommunityToolbar->setTitle( $title );

			$val = sprintf( "<h2>%s</h2>",$this->job["job_title"] );
			if ($this->bAvailable)
				$val.=sprintf( "<a class=\"nrm\" href=\"javascript:JQPToggleJobDetails();\">%s &raquo;</a>",
					__("quotepage_Job_details") );
			$this->oCommunityToolbar->setSubTitle2( $val );

			if (!$this->bAvailable) return;
			$this->oJobDetails->setJobId( $this->job["job_id"] );
			$this->oJobDetails->setJobData( $this->job );
			$this->oJobDetails->setDetails( true );

			if ($this->bPreview) return;

			$this->oQuotePricing->setCSSAttribute( "text-align" , "right" );
			$this->oQuotePricing->setAttribute( "maxlength" , 20 );
			$this->addEmptyValidator( $this->oQuotePricing );

			$ctrlh = 160;
			$this->oQuote->setColumns( 78 );
			$this->oQuote->setRows( 10 );
			$this->oQuote->setHeight( $ctrlh );
			$this->addEmptyValidator( $this->oQuote );

			$this->oTemplates->setAttribute( "size" , "11" );
			$this->oTemplates->setWidth( 260 );
			$this->oTemplates->addOption( -1 , __("Loading") );
			$this->oTemplates->setCSSAttribute( "height" , $ctrlh."px" );

			$this->oLoadTemplate->setValue( __("quotepage_Load_template","attr") );
			$this->oLoadTemplate->setAttribute( "disabled" , "disabled" );
			$this->oSaveTemplate->setValue( __("quotepage_Save_template") );
			$this->oSaveTemplate->setAttribute( "disabled" , "disabled" );
			$this->oDeleteTemplate->setValue( __("quotepage_Delete_template" ) );
			$this->oDeleteTemplate->setAttribute( "disabled" , "disabled" );
		}

		protected function handleAjaxEvents() {
			if (!$this->model_mymember->isMemberLoggedin()) return;
			if (!isset( $this->aP["ajaxevent"] )) return;
			switch ($this->aP["ajaxevent"]) {
			case "refresh_templates":
				$mm = new MemberModel();
				$datas = $mm->getmemberTemplates( $this->model_mymember->getLoggedinMemberId() );
				FNTH_echo_json_response( $datas , 0 , "fo3_exit" );
				break;
			case "delete_template":
				$mm = new MemberModel();
				$member_template = $mm->deleteMemberTemplate( $this->model_mymember->getLoggedinMemberId(),
					$this->aP["member_template_id"] );
				FNTH_echo_json_response( true , 0 , "fo3_exit" );	
				break;
			case "load_template":
				$mm = new MemberModel();
				$member_template = $mm->getMemberTemplate( $this->model_mymember->getLoggedinMemberId(),
					$this->aP["member_template_id"] );
				FNTH_echo_json_response( $member_template , 0 , "fo3_exit" );	
				break;
			case "save_template":
				$mm = new MemberModel();
				if (isset( $this->aP["update"] )) {
					$mm->updateMemberTemplate( $this->model_mymember->getLoggedinMemberId() , $this->aP["member_template_id"] , $this->aP );
					$member_template_id = $this->aP["member_template_id"];
				} else {
					$member_template_id = $mm->addMemberTemplate( $this->model_mymember->getLoggedinMemberId(), $this->aP );
				}
				$datas = array();
				$datas["member_template_id"] = $member_template_id;
				FNTH_echo_json_response( $datas , 0 , "fo3_exit" );	
				break;
			}
		}
		
		protected function isPreview() {
			return isset( $this->aG["preview"] );
		}

		protected function cameFromPreview() {
			$url = (isset( $_SERVER["HTTP_REFERER"] )) ? $_SERVER["HTTP_REFERER"] : "";
			if (isset( $_SESSION["http_current_page"] ) &&
				isset( $_SESSION["http_referer"] ) &&
				($_SESSION["http_current_page"]!=$_SESSION["http_referer"]) &&
				strlen( $_SESSION["http_referer"] )) $url = $_SESSION["http_referer"];

			$eurl = FNTH_explode_url( $url );
			$rqu = new JobURL();
			$previewurl = $rqu->renderJobQuotePreviewURL( $this->job_id );
			return ($eurl["path"]==$previewurl);
		}
		
		protected function goToPreview() {
			$rqu = new JobURL();
			$url = $rqu->renderJobQuotePreviewURL( $this->job_id );
			FNTH_redirect( $url );
		}

		protected function validateJobQuote() {
			$retval  = true;
			if (!strlen( $this->oQuotePricing->getValue() )) {
				GlobalWarningMessage( "no_quote_price" , __("quotepage_No_quote_pricing_filled") );
				$retval = false;
			}

			if (!strlen( $this->oQuote->getValue() )) {
				GlobalWarningMessage( "no_quote" , __("quotepage_No_quote_filled") );
				$retval = false;
			}
			return $retval;
		}
		
		protected function saveState() {
			$_SESSION["job_quote"]=$this->aP;
		}

		protected function loadState() {
			if (!isset( $_SESSION["job_quote"] )) return;
			$this->aP = $_SESSION["job_quote"];
		}
		
		protected function clearState() {
			if (isset( $_SESSION["job_quote"] )) return;
			unset( $_SESSION["job_quote"] );
		}
		
		protected function renderPreview() {
			$rqu = new JobURL();
			$this->setParam( "url_back" , $rqu->renderJobQuoteURL( $this->job_id ) );
		}
	
		protected function saveJobQuote() {
			$mum = new MyMemberModel();
			$p = array();
			$p["job_id"]=$this->job_id;
			$p["member_id"]=$mum->getLoggedinMemberId();
			$p["quote"]=$this->oQuote->getValue();
			$p["quote_pricing"]=$this->oQuotePricing->getValue();

			$jm = new JobQuoteModel();
			$job_quote_id = $jm->addJobQuote( $p );
			if (!$job_quote_id ) return false;
	
			$attachments = $this->oAttachments->getAttachments();
			if (is_array( $attachments ) && !empty( $attachments )) {
				foreach ($attachments as $att) $jm->addJobQuoteAttachment( $job_quote_id , $att );
			}
			$ulm = new UserLogModel();

			// logging
			$ulm->logMemberActivity( USER_LOG_JOB_QUOTE | USER_JOB_QUOTE_SENT ,
				sprintf( "ajánlatra (#%d) küldött választ (#%d)",
					$this->job_id , $job_quote_id ) );

			$jm = new JobModel();
			$this->job = $jm->getJobFromId( $this->job_id , true );

			$um = new UserModel();
			$owner_user = $um->getUserFromUserId( $this->job["poster_user_id"] );
			
			$mm = new MemberModel();
			$poster_member = $mm->getMemberFromMemberId( $p["member_id"] , true );
			$poster_user = $um->getUserFromUserId( $poster_member["user_id"] );

			// 1. levelkuldes az arcnak, hogy jott munkaajanlata
			$lang = $GLOBALS["backlang"][ $this->job["site_language_id"] ];
			$mail_to_job_owner = new TemplateMailModel( "sys_job_quote_received" , $lang );
			$cm = new ConstantsModel( $mail_to_job_owner , $lang );
			$cm->addSystemParametersToTemplate();
			$cm->addUserConstantsToTemplate( $owner_user["user_id"] , "receiver_user" );
			$cm->addUserConstantsToTemplate( $poster_member["user_id"] , "poster_user" , $poster_user );
			$cm->addMemberConstantsToTemplate( $p["member_id"] , "poster_member" , $poster_member );
			$cm->addJobConstantsToTemplate( $this->job_id , "job" );
			$cm->addJobQuoteConstantsToTemplate( $job_quote_id );
			$mail_to_job_owner->sendMail( $owner_user["email"] );


			// 2. levelkuldes a forditonak, hogy tett ajanlatot
			$mail_to_translator = new TemplateMailModel( "sys_job_quote_sent" );
			$cm = new ConstantsModel( $mail_to_translator );
			$cm->addSystemParametersToTemplate();
			$cm->addUserConstantsToTemplate( $owner_user["user_id"] , "receiver_user" );
			$cm->addUserConstantsToTemplate( $poster_member["user_id"] , "poster_user" , $poster_user );
			$cm->addMemberConstantsToTemplate( $p["member_id"] , "poster_member" , $poster_member );
			$cm->addJobConstantsToTemplate( $this->job_id , "job" );
			$cm->addJobQuoteConstantsToTemplate( $job_quote_id );
			$mail_to_translator->sendMail( $poster_user["email"] );

			// FIXME logolni

		}

		protected function handleNormalPageEvent() {
			// vagy inditunk, vagy previewrol jottunk vissza
			$this->oSubmit->refreshValueFromArray();
			if (!$this->oSubmit->isSubmitted()) {
				if ($this->cameFromPreview()) {	// ha previewbol jottunk vissza
					$this->loadState();			// akkor toltsuk vissza();
					$this->refreshChildValuesFromArray( $this->aP );
				}
				return parent::handleEvents();		// egyebkent meg tok ures a form
			}
			$this->handleChildEvents();
			$this->refreshChildValuesFromArray( $this->aP );	// felulbasszuk a default parametereket
			if (!$this->validateJobQuote()) return parent::handleEvents();
			$this->saveState();
			$this->goToPreview();
		}
		
		protected function handlePreviewEvent() {
			// previewban vagyunk
			$saved = $this->aP;		// mentsuk a postot
			$this->loadState();		// sessionbol turjuk felul a postot
			$this->aP = array_merge( $this->aP , $saved ); // toltsuk vissza a post cuccait
			$this->oSubmit->setValue( __("quotepage_Post_a_quote_after_preview" ) );
			$this->refreshChildValuesFromArray( $this->aP );
			if (!$this->oSubmit->isSubmitted()) {
				// preview elokeszites
				$this->setParam( "preview_quote_pricing" , $this->oQuotePricing->getValue() );
				$this->setParam( "preview_quote" , $this->oQuote->getValue() );
				return parent::handleEvents();
			}

			// tenyleges submit
			$mum = new MyMemberModel();
			if (!$mum->isMemberLoggedin()) return parent::handleEvents();		// nem belepett member
			$jm = new JobModel();
			if (!$jm->isJobQuoteAvailableForUser( $this->job_id , $mum->getLoggedinUserId() ))
				return parent::handleEvents();

			// emlekezteto kuldese a forditonak

			$_SESSION["job_quote_saved"]=true;
			// job quote mentese
			$this->saveJobQuote();

			// ugras vissza a gridre
			$turl = new TranslatorJobsURL();
			$url = $turl->renderURL();
			FNTH_redirect( $url );
		}

		public function handleEvents() {
			if (!$this->bAvailable) return parent::handleEvents();

			// handle ajax events
			if (isset( $this->aP["inajax"] )) {
				$this->handleAjaxEvents();
				return parent::handleEvents();
			}
			if ($this->isPreview()) return $this->handlePreviewEvent();
			return $this->handleNormalPageEvent();
		}

		protected function generateLangDefs() {
			fo3_add_js_langdef( "quotepage_Are_you_sure_to_delete_template" );
			fo3_add_js_langdef( "quotepage_Are_you_sure_to_overwrite_template" );
			fo3_add_js_langdef( "quotepage_No_quote_pricing_filled" );
			fo3_add_js_langdef( "quotepage_No_quote_filled" );
			fo3_add_js_langdef( "quotepage_Are_you_sure_to_load_template" );
		}

		protected function renderForm() {

		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$this->setParam( "url_quote_post_terms_and_conditions",
				ArticleURL::renderURLFromArticleName( "sys_quote_post_terms_and_conditions" ) );
			$this->generateLangDefs();

			$this->setParam( "bLoggedin" , $this->bLoggedin );
			$this->setParam( "bActiveSubscriber" , $this->bActiveSubscriber );
			$this->setParam( "bAvailable" , $this->bAvailable );

			$this->bPreview = $this->isPreview();
			$this->setParam( "bPreview" , $this->bPreview );
			
			$datas = array();
			$jm = new JobModel();
			$this->job = $jm->getJobFromId( $this->job_id , true );

			$this->initializeWidgets();
			if (!$this->bLoggedin) return parent::render();

			if ($this->bPreview) {
				$this->oAttachments->setReadOnly( true );
				$this->renderPreview();
			} else {
				if ($this->bAvailable) {
					if (!strlen( trim( $this->oQuotePricing->getValue() ) ) )
						$this->oQuotePricing->setAttribute( "class" , "FrontendTextbox invalid" );
					if (!strlen( trim( $this->oQuote->getValue() ) ) )
						$this->oQuote->setAttribute( "class" , "FrontendTextarea invalid" );
					$mm = new MemberModel();
					$datas["templates"]=$mm->getMemberTemplates( $this->model_mymember->getLoggedinMemberId() );
					FNTHPage::addUniquePageFullInit(
						sprintf( "InitJobQuotePane( '%s' , %s );\n",$this->getId(),json_encode( $datas ) ) );	
				}
			}
			fo3_form_change_warning();
			return parent::render();
		}
	}
?>
