<?php
	require_once( $GLOBALS["site_root"]."/includes/widgets/Widget.inc.php");
	require_once( $GLOBALS["site_root"]."/includes/widgets/LanguagePairs.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/CommunityToolbar.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/CaptchaHtmlHide.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/Languages.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Specialties.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Memberships.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Cat.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/ExtendedProperties.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/SelectedUsers.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Counties.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Countries.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/AdminUser.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Blueboard.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Youtube.inc.php" );

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

	class MemberInfoPanel extends Widget {
		protected $oLangPairMatrix;
		protected $oCommunityToolbar;

		protected $mm = null;
		protected $um = null;
		protected $sm = null;
		protected $mem = null;
		protected $epm = null;
		protected $mmm = null;

		protected $member_id = 0;
		protected $user_id = 0;
		protected $bShowEmail = false;

		public function __construct( $id , $parent = null ) {
			parent::__construct( $id , $parent );
			$this->mm = new MemberModel();
			$this->lm = new LanguagesModel();
			$this->sm = new SpecialtiesModel();
			$this->mem = new MembershipsModel();
			$this->bbm = new BlueboardModel();
			$this->epm = new ExtendedPropertiesModel();
			$this->mmm = new MyMemberModel();

			$this->oLangPairMatrix = new LanguagePairs( "langpairmatrix" , $this );
			$this->oCommunityToolbar = new CommunityToolbar( "CommunityToolbar" , $this );
			$this->oEmailCaptcha = new CaptchaHtmlHide( "email_captcha" , $this );
			$this->oMSN = new CaptchaHtmlHide( "msn_captcha" , $this );
			$this->oSkype = new CaptchaHtmlHide( "skype_captcha" , $this );
			if (AdminUserModel::isAdminLoggedIn()) $this->bShowEmail = true;
			if ($this->mmm->isLoggedinMemberActiveSubscriber()) $this->bShowEmail = true;
		}

		public function modifyGetPost( &$g , &$p ) {
			if (isset( $g["prnc"] )) {
				$this->oParent->setFullScreen( true );
				$this->oParent->setPrint( true );
			}
			return parent::modifyGetPost( $g , $p );
		}

		public function setId( $v ) { FNTH_da( "setid" );$this->member_id = $v; }

		public function setUsername( $v ) {
			$this->member_id = $this->mm->getMemberIdFromUsername( $v );
		}

		public function setAliasname( $v ) {
			$this->member_id = $this->mm->getMemberIdFromAliasname( $v );
		}

		public function distortEmail( $email ) {
			return str_rot13( $email );
		}


		public function handleEvents() {
			if (!isset( $this->aP["quote_req"] )) return parent::handleEvents();
			if (isset( $this->aP["smb_quote_request"] )) {
				$selusers = new SelectedUsersModel();
				$selusers->addSelectedUser( $this->aP["quote_req"] );
				FNTH_redirect( RequestQuoteURL::renderURL() );
			} else if (isset( $this->aP["smb_select"] )) {
				$selusers = new SelectedUsersModel();
				$selusers->addSelectedUser( $this->aP["quote_req"] );
				FNTH_refresh();
			} else if (isset( $this->aP["smb_deselect"] )) {
				$selusers = new SelectedUsersModel();
				$selusers->deleteSelectedUser( $this->aP["quote_req"] );
				FNTH_refresh();
			} else {
				return parent::handleEvents();
			}
		}

		protected function renderWorkingLanguages() {
			$this->languages = $this->lm->getLanguageOptions();
			$this->member_lang_ids = $this->mm->getMemberLanguages( $this->member_id );
			$retval="";
			foreach ($this->member_lang_ids as $lang_id ) {
				$retval.=(empty( $retval )) ? "" : ", ";
				$retval.=$this->languages[$lang_id];
			}
			return $retval;
		}
		
		protected function renderSpecialties( $member ) {
			$specialties = $this->sm->getSpecialtyOptions();
			$spec_ids = $this->mm->getMemberSpecialties( $this->member_id );
			$retval="";
			foreach ($spec_ids as $spec_id ) {
				$retval.=(empty( $retval )) ? "" : ", ";
				$retval.=$specialties[$spec_id];
			}

			if (isset( $member["custom_specialty"] ) && strlen( trim( $member["custom_specialty"] ) )) {
				$retval.=(empty( $retval )) ? "" : ", ";
				$retval.=trim( $member["custom_specialty"] );
			}
			return $retval;
		}

		protected function renderMemberships( $member ) {
			$memberships = $this->mem->getMembershipOptions( false , false , true );
			$membership_ids = $this->mm->getMemberMemberships( $this->member_id );
			$retval="";
			foreach ($membership_ids["memberships"] as $membership_id ) {
				$retval.=(empty( $retval )) ? "" : ", ";
				$retval.=$memberships[$membership_id];
			}

			
			if (isset( $member["custom_membership"] ) && strlen( trim( $member["custom_membership"] ) )) {
				$retval.=(empty( $retval )) ? "" : ", ";
				$retval.=trim( $member["custom_membership"] );
			}
			return $retval;

		}

		public function renderCats( $member ) {
			$cm = new CatModel();
			$cats = $cm->getCatOptions();
			$mcats = $this->mm->getMemberCats( $this->member_id );
			$retval = "";
			$acats = array();
			if (isset( $mcats["cats"] ) && !empty( $mcats["cats"] ))
				foreach ($mcats["cats"] as $cat_id => $level)
					$acats[]=sprintf( "%s (%s)" , $cats[$cat_id] , __("mycat_level".$level) );
			if (isset( $mcats["custom_cat"] ) && !empty( $mcats["custom_cat"] ))
				$acats[]=$mcats["custom_cat"];
			if (empty( $acats )) return "";
			return implode( ", " , $acats );
		}

		protected function generateLangdefs() {
			fo3_add_js_langdef( "details" );
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$this->generateLangdefs();
			// member
			$this->setParam( "member_id" , $this->member_id );



			if (!$this->member_id) {
				$this->show_page = false;	// kocsog smarty
				header( "HTTP/1.1 404 Not found" );
				$this->oCommunityToolbar->setTitle( __("Member_page") );
				return parent::render();
			} else {
				$this->member = $member = $this->mm->getMemberFromMemberId( $this->member_id );
				$this->is_active = $this->mm->isMemberActiveSubscriber( $this->member_id , $this->member );
				$this->setParam( "bIsActiveSubscriber" , $this->is_active );
				$this->is_owned = ($this->mmm->getLoggedinMemberId() == $this->member_id );

				$this->setParam( "bOwned" , $this->is_owned );
				$this->bActiveAgency = ($this->mmm->isLoggedinMemberActiveSubscriber() && $this->mmm->getLoggedInUserType()=="agency");
				$this->show_page = (!in_array( $this->member["current_status"] , array(
					STATUS_DELETED , STATUS_NEW_USER_DELETED) ) );	// true;	// ($this->is_active || $this->is_owned || $this->bActiveAgency );
				$this->show_contact = ($this->is_active || $this->bActiveAgency );
				$this->show_details = $this->show_contact;
				if (!$this->show_page) {
					// nem nyilvanos	
					header( "HTTP/1.1 404 Not found" );
					$this->oCommunityToolbar->setTitle( __("Member_page") );
					return parent::render();
				}
			}
			$this->setParam( "bShowPage" , $this->show_page );
			$this->setParam( "bShowContact" , $this->show_contact );
			$this->setParam( "bShowDetails" , $this->show_details );

			FNTH_include_3rdparty( "fancybox" );

			$this->setParam( "member" , $member );
			// user
			$this->user_id = $member["user_id"];
			$this->um = new UserModel();
			$user = $this->um->getUserFromUserId( $this->user_id );
			$this->setParam( "user" , $user );

			// extended properties
			$epropfields = array();
			$epropfields[]="experience_5+";
			$epropfields[]="native_language";
			$epropfields[]="certificate";
			$epropfields[]="invoice";

			$eprops = array();
			foreach ($epropfields as $field) {
				$prop_id = $this->epm->getEPropIdFromName( $field );
				$val = $this->mm->getMemberExtendedPropertyFromId( $this->member_id , $prop_id );
				if ($val!="on") continue;
				$prop = array(
					"prop_id" => $prop_id,
					"langdef" => $this->epm->getEPropLangdefFromName( $GLOBALS["langcode"] , $field ),
					"value" => $val );
				$eprops[]=$prop;
			}	
			$this->setParam( "eprops" , $eprops );
			$this->setParam( "tick" , sprintf( "<img src=\"/images/icons/tick_icon.png\" alt=\"%s\" />" , __("_yes_","attr") ) );

			// blueboard
			$prop_id = $this->epm->getEPropIdFromName( "show_blueboard_score" );
			$this->bShowBlueBoardScore = false;
			if ($prop_id) {
				$val = $this->mm->getMemberExtendedPropertyFromId( $this->member_id , $prop_id );
				if ($val=="on") {
					// megjelenitjuk a blueboard adatat
					$bb = $this->bbm->getUserComments( $this->user_id );
					if ($bb) {
						$this->bShowBlueBoardScore = true;
						$this->setParam( "bb_avg_score" , $bb["score_average"] );
						$this->setParam( "bb_numofcomments" , $bb["number_of_comments"] );
					}
				}
			}
			$this->setParam( "bShowBlueBoardScore" , $this->bShowBlueBoardScore );

			// searchbot
			$prop_id = $this->epm->getEPropIdFromName( "searchbot_index" );
			if ($prop_id) {
				$val = $this->mm->getMemberExtendedPropertyFromId( $this->member_id , $prop_id );
				if (!strlen( $val )) {
					FNTHPage::setPageHead( "searchbot_noindex" , "<meta name=\"robots\" content=\"noindex\" />" );
				}
			}

			// member since
			$this->setParam( "member_since_date" , fo3_format_date_to_screen( $user["reg_tstamp"] ) );
			$this->setParam( "member_since_days" , 
				(int)((fo3_time()-FNTH_convert_YmdHis_to_unix($user["reg_tstamp"]))/86400)
			);

			// member attachments
			$attachments = $this->mm->getMemberAttachments( $this->member_id );
			$this->setParam( "attachments" , $attachments );

			$data = array();	
			// $data["email"]=$this->distortEmail( $user["email"] );
			$this->oEmailCaptcha->setHiddenHtml( sprintf( "<a class=\"nrm\" href=\"mailto:%s\">%s</a>",$user["email"],$user["email"] ) );
			$this->oEmailCaptcha->setEnable( !$this->bShowEmail );

			if (isset( $member["msn"] ) && strlen( $member["msn"] ))
				$this->oMSN->setHiddenHtml( sprintf( "<a class=\"nrm\" href=\"mailto:%s\">%s</a>",$member["msn"],$member["msn"] ) );
			
			if (isset( $member["skype"] ) && strlen( $member["skype"] ))
				$this->oSkype->setHiddenHtml( sprintf( "<a class=\"nrm\" href=\"callto:%s\">%s</a>",$member["skype"],$member["skype"] ) );


			$this->setParam( "working_languages" , $this->renderWorkingLanguages() );
			$this->setParam( "specialties" , $this->renderSpecialties( $member ) );
			$this->setParam( "memberships" , $this->renderMemberships( $member ) );
			$this->setParam( "cats" , $this->renderCats( $member ) );
			
			$this->oLangPairMatrix->setSelectedLanguages( $this->mm->getMemberLanguages( $this->member_id ) );
			$this->oLangPairMatrix->setValue( $this->mm->getMemberLanguagePairs3D( $this->member_id ) );
			$this->oLangPairMatrix->setReadOnly( true );
			$this->oLangPairMatrix->setShowIntro( true );
			$this->oLangPairMatrix->setCSSAttribute( "display" , "none" );

			if ($this->is_active) {
				$this->oCommunityToolbar->setSubTitle(
					sprintf( "<h2 class=\"member_type_page\">%s | %s</h2>",
						__("users_".$member["member_type"],"attr") , 
						__("member_profile_page","attr" ) ) );
			} else {
				$this->oCommunityToolbar->setSubTitle(
					sprintf( "<h2 class=\"member_type_page\">%s | %s <span style=\"color: red;\"><br/>%s</span></h2>",
						__("users_".$member["member_type"],"attr") , 
						__("member_profile_page","attr" ),
						__("inactive_member_page") ) );
			}

			$st2 = 	sprintf( "<input type=\"submit\" class=\"minismb\" name=\"smb_quote_request\" value=\"%s\" />",__("Quote","attr") );
			$selusers = new SelectedUsersModel();
			if ($selusers->isUserSelected( $member["user_id"] )) {
				$st2.=sprintf( " <input type=\"submit\" class=\"minismb\" name=\"smb_deselect\" value=\"%s\" />",__("Deselect_translator" , "attr" ) );
			} else {
				$st2.=sprintf( " <input type=\"submit\" class=\"minismb\" name=\"smb_select\" value=\"%s\" />",__("Select_translator" , "attr" ) );
			}
			// adjunk meg hozza gombot, hogy ha be van jelentkezve es jogosult meg a kommentezesre
			$viewer_user_id = $this->mmm->getLoggedinUserId();
			if ($viewer_user_id) {
				// be van jelentkezve a user
				$bbu = new BlueboardURL();
				$url = $bbu->renderURL( array( "user_id" => $this->user_id ) );
				if ($this->bbm->canViewComments( $viewer_user_id , $this->user_id )) {
					$st2.=sprintf( " <input type=\"button\" class=\"minismb\" name=\"btn_feedback\" value=\"%s\" onclick=\"document.location.href='%s';\" />",
					__("Post_feedback","attr"),
					$url );
				}
			}
			$this->oCommunityToolbar->setSubTitle2( $st2 );

			$prop_services = $this->mm->getExtendedPropertyIdFromName( "services" );
			$prop_references = $this->mm->getExtendedPropertyIdFromName( "references" );

			$this->setParam( "services" , $this->mm->getMemberExtendedPropertyFromId( $this->member_id , $prop_services , $GLOBALS["langcode"] ) );
			$this->setParam( "references" , $this->mm->getMemberExtendedPropertyFromId( $this->member_id , $prop_references , $GLOBALS["langcode"] ) );

			$this->setParam( "show_email" , $this->bShowEmail );

			switch ($GLOBALS["language"]) {
			case "hu":$user_name = $user["user_name"];break;
			default:
				$langsite_name_id = $this->epm->getEPropIDFromName( "langsite_name" );
				$user_name = $this->mm->getMemberExtendedPropertyFromId( $this->member_id , $langsite_name_id , $GLOBALS["langcode"] );
			}
			$this->oCommunityToolbar->setTitle( $user_name );

			switch ($GLOBALS["language"]) {
			default:
			case "hu":
				// page title
				$page_title = sprintf( "%s | %s",
					$user_name,
					__( $member["member_type"],"attr" ) );
				$description = sprintf( "%s",
					__( $member["member_type"],"attr" ) );

				if (isset( $member["is_address_visible"] )) { // && $member["is_address_visible"]=="t") {
					$cm = new CountiesModel();
					$cym = new CountriesModel();
					$counties = $cm->getCountyOptions( false , false );
					$countries = $cym->getCountryOptions( false , false );
					$parent_id = $cm->getCountyParentId( $member["county_id"] );
					// hekkeles
					if ($parent_id==1) {
						// budapest keruletek
						switch ($GLOBALS["language"]) {
						case "hu":
							$page_title.=sprintf( " | %s",
								$counties[ $member["county_id"] ] );
							$description.=sprintf( ", %s",
								$counties[ $member["county_id"] ] );
							break;
						default:
							// kulfoldbe nem kellenek a keruletek, csak a budapest
							$page_title.=sprintf( " | %s" , $member["city"] );
							$description.=sprintf( ", %s" , $member["city"] );
							break;
						}
					} else if ($member["county_id"]==1) {
						// budapest maga
						$page_title.=sprintf( " | %s",$counties[$member["county_id"]] );
						$description.=sprintf( " , %s",$counties[$member["county_id"]] );
					} else if ($member["county_id"]==21) {
						// kulfold hekk
						$page_title.=sprintf( " | %s, %s",$member["city"],$countries[$member["country_id"]] );
						$description.=sprintf( " , %s, %s",$member["city"],$countries[$member["country_id"]] );
					} else {
						// egyeb varosok
						switch ($GLOBALS["language"]) {
						case "hu":
							// magyar: varos, megye
							$page_title.=sprintf( " | %s, %s",
								$member["city"],
								$counties[ $member["county_id"] ] );
							$description.=sprintf( ", %s, %s, ",
								$member["city"],
								$counties[ $member["county_id"] ] );
							break;
						default:
							// kulfoldi: varos
							$page_title.=sprintf( " | %s" , $member["city"] );
							$description.=sprintf( ", %s" , $member["city"] );
							break;
						}
					}
				}
				$page_title.=sprintf( " | %s" , GlobalsModel::getSiteName() );
				fo3_set_page_title( $page_title );

				// keywords
				$keywords = array();
				$keywords[]=__($member["member_type"],"attr");
				$limit = 18;
				foreach ($this->member_lang_ids as $lang_id ) {
					$keywords[]=$this->languages[$lang_id];
					$limit--;
					if (!$limit) break;
				}
				fo3_set_meta_keywords( implode( ", " , $keywords ) );
				$description=__("Languages").": ".implode( ", " , array_slice( $keywords , 1 ) ) . ".";	// direkt feluliras, meg meg fogjak magukat gondolni
				fo3_set_meta_description( $description );
				break;
			}

			FNTHPage::addUniquePageFullInit(
				sprintf( "InitMemberInfoPanel( %s );\n",json_encode( $data ) ) );
			// FNTH_da( $member , false );
			$this->setParam( "print" , isset( $this->aG["prnc"] ) );

			if (isset( $member["youtube"] ) && strlen( trim( $member["youtube"] ) )) {
				$this->setParam( "youtube" , YoutubeModel::embedLink( $member["youtube"] ) );
			}
			$retval = parent::render();
			return $retval;
		}
		
	}

?>
