<?php
	require_once( $GLOBALS["site_root"] . "/includes/widgets/FrontendSuperGrid.inc.php" );

	require_once( $GLOBALS["site_root"]."/includes/models/MyMember.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Keywords.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/ExtendedProperties.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Member.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Languages.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/UserNameTag.inc.php" );

	class SearchHitsGrid extends FrontendSuperGrid {
		protected $mmm;
		protected $mm;
		protected $lm;
		protected $bActiveAgency;
		protected $epm;

		protected $sKeywordField = "keyword";
		protected $bOmitHeader = true;
		protected $bFreetextSearch = false;

		public function setKeywordField( $v ) { $this->sKeywordField = $v; }
		public function setOmitHeader( $v ) { $this->bOmitHeader = $v; }
		public function setFreetextSearch( $v ) { $this->bFreetextSearch = $v; }

		public function __construct( $id , $parent ) {
			parent::__construct( $id , $parent );
			$this->sTableName = "members,users";
			$this->setCSSAttribute( "width" , "100%" );
			$this->_pagenum = "pn";
			$this->_pagesize = "ps";
			$this->_ordering = "ord";
			$this->_orderingdir = "ordd";
			$this->sNoRows = __("searchhits_No_translators_found" );
			$this->bFooterPager = true;
			
			$this->mmm = new MyMemberModel();
			$this->mm = new MemberModel();
			$this->lm = new LanguagesModel();
			$this->bActiveAgency = ($this->mmm->isLoggedinMemberActiveSubscriber() && $this->mmm->getLoggedInUserType()=="agency");
			$this->epm = new ExtendedPropertiesModel();
		}

		protected function orderClause() {
			$retval = "";
			if (empty( $this->sOrdering)) {
				return " order by ordering,users.user_name";
			}
			switch ($this->sOrdering) {
			case "member":$retval="users.user_name";break;
			case "member_type":$retval="members.member_type";break;
			case "location":$retval="members.city";break;
			case "expires_tstamp":$retval="members.expires_tstamp";break;
				break;
			}
			if (empty( $retval )) return "";
			if (!$this->bAscending) $retval.=" desc";
			return " order by ".$retval;
		}

		protected function prepareDataset() {
			$nd = array();
			$languages = $this->lm->getLanguageOptions();
			foreach ($this->aData as $row) {
				$mlangs = $this->mm->getMemberLanguages( $row["member_id"] );
				$langs=array();
				$i=0;
				foreach ($mlangs as $lang_id) {
					if ($i>5) {
						$langs[]="...";
						break;
					}
					$langs[]=$languages[$lang_id];
					$i++;
				}
				$row["languages"]=implode( ", " , $langs );
				$nd[]=$row;
			}
			$this->aData = $nd;
		}

		protected function generateTextualFilters() {
			$retval = array();
			// keyword
			if (isset( $this->aG["keyword"] ) && strlen( $this->aG["keyword"] )) {
				$retval[]=sprintf( "%s: %s",
					FNTH_strtolower( __("searchpage_Keyword") ) , $this->aG["keyword"] );
			}
			// source_language
			if (isset( $this->aG["source_language"] ) && strlen( $this->aG["source_language"]) ) {
				if (!isset( $languages )) {
					require_once( $GLOBALS["site_root"]."/includes/models/Languages.inc.php" );
					$languages = LanguagesModel::getLanguageOptions( false );
				}
				if (isset( $languages[$this->aG["source_language"]]))	
					$retval[]=sprintf( "%s: %s",
					FNTH_strtolower( __("searchpage_Source_language") ),$languages[$this->aG["source_language"]] );
			}
			// target_language
			if (isset( $this->aG["target_language"] ) && strlen( $this->aG["target_language"]) ) {
				if (!isset( $languages )) {
					require_once( $GLOBALS["site_root"]."/includes/models/Languages.inc.php" );
					$languages = LanguagesModel::getLanguageOptions( false );
				}
				if (isset( $languages[$this->aG["target_language"]]))	
					$retval[]=sprintf( "%s: %s",
					FNTH_strtolower( __("searchpage_Target_language") ),$languages[$this->aG["target_language"]] );
			}
			// servicetype
			if (isset( $this->aG["servicetype"] ) && strlen( $this->aG["servicetype"]) ) {
				if (!isset( $servicetypes )) {
					require_once( $GLOBALS["site_root"]."/includes/models/ServiceTypes.inc.php" );
					$servicetypes = ServiceTypesModel::getServiceTypeOptions( false );
				}
				if (isset( $servicetypes[$this->aG["servicetype"]]))	
					$retval[]=sprintf( "%s: %s",
					FNTH_strtolower( __("searchpage_Servicetype") ),$servicetypes[$this->aG["servicetype"]] );
			}
			// megye
			if (isset( $this->aG["megye"] ) && strlen( $this->aG["megye"]) ) {
				if (!isset( $megyek )) {
					require_once( $GLOBALS["site_root"]."/includes/models/Counties.inc.php" );
					$megyek = CountiesModel::getCountyOptions( false );
				}
				if (isset( $megyek[$this->aG["megye"]]))	
					$retval[]=sprintf( "%s: %s",
					FNTH_strtolower( __("searchpage_County_or_district") ),
						str_replace( "&nbsp;","",$megyek[$this->aG["megye"]]) );
			}
			// orszag
			if (isset( $this->aG["orszag"] ) && strlen( $this->aG["orszag"]) ) {
				if (!isset( $orszagok )) {
					require_once( $GLOBALS["site_root"]."/includes/models/Countries.inc.php" );
					$orszagok = CountriesModel::getCountryOptions( false );
				}
				if (isset( $orszagok[$this->aG["orszag"]]))	
					$retval[]=sprintf( "%s: %s",
					FNTH_strtolower( __("searchpage_Foreign_countries") ),$orszagok[$this->aG["orszag"]] );
			}
			// utype
			if (isset( $this->aG["utype"] ) && strlen( $this->aG["utype"]) ) {
				$retval[]=sprintf( "%s: %s",
				FNTH_strtolower( __("searchpage_Agency_or_freelancer") ),__("users_".$this->aG["utype"] ) );
			}
			// membership
			if (isset( $this->aG["membership"] ) && strlen( $this->aG["membership"]) ) {
				if (!isset( $memberships )) {
					require_once( $GLOBALS["site_root"]."/includes/models/Memberships.inc.php" );
					$memberships = MembershipsModel::getMembershipOptions( false );
				}
				if (isset( $memberships[$this->aG["membership"]]))	
					$retval[]=sprintf( "%s: %s",
					FNTH_strtolower( __("searchpage_Professional_membership") ),$memberships[$this->aG["membership"]] );
			}

			if (empty( $retval )) {
				// ha nincs, akkor kiirjuk, hogy mind
				$retval[]=__("searchpage_All_translators");
			}
			$text_retval = implode( "; " , $retval );	
			return $text_retval;
		}

		protected function whereClause() {
			$textual_filters = $this->generateTextualFilters();
			$this->oParent->setParam( "search_params" , $textual_filters );
			fo3_set_meta_description( $textual_filters );
			$filters = array();
			$filters[]="members.user_id=users.user_id";
			$filters[]="not members.is_deleted";
			$filters[]="not users.is_deleted";

			if ($GLOBALS["language"]!="hu") {
				require_once( $GLOBALS["site_root"]."/includes/models/ExtendedProperties.inc.php" );
				$epm = new ExtendedPropertiesModel();
				$eprop_id = $epm->getEPropIdFromName( "use_langsite" );
				$site_language_id = $GLOBALS["langcode"];

				$filters["show_foreign"]=sprintf( "member_id in (select member_id from member_extended_properties where extended_property_id=%d and language_id=%d and value='on')",
					$eprop_id,
					$site_language_id );
			}

			// aktiv irodaknak nincs szures
			$filter_inactives = true;
			$this->bActiveAgency = ($this->mmm->isLoggedinMemberActiveSubscriber() && $this->mmm->getLoggedInUserType()=="agency");
			$this->bLoggedInMember = $this->mmm->isMemberLoggedIn();
			if (isset( $this->aG["inactive"] ) || $this->bFreetextSearch ) {
				$filter_inactives = false;
			}

			if ($filter_inactives)
				$filters[] = sprintf( "members.expires_tstamp>now()" );

			// source language (ezt muszaj igy csinalni)
			if (isset( $this->aG["source_language"] ) && strlen( $this->aG["source_language"]) ) {
				$filters[]=sprintf( "member_id in (select distinct member_id from member_languages where language_id=%d)" , $this->aG["source_language"] );
			}
			// target language
			if (isset( $this->aG["target_language"] ) && strlen( $this->aG["target_language"]) ) {
				$filters[]=sprintf( "member_id in (select distinct member_id from member_languages where language_id=%d)" , $this->aG["target_language"] );
			}

			if (isset( $this->aG["servicetype"]) && strlen( $this->aG["servicetype"] ) && ( $this->aG["servicetype"] > 0) ) {
				$servicetype_id = $this->aG["servicetype"];
				$filters[]=sprintf( "member_id in (select distinct member_id from member_languagepairs where servicetype_id=%d)" , $servicetype_id );
			}
			if (isset( $this->aG["megye"]) && strlen( $this->aG["megye"] ) && $this->aG["megye"] > 0 ) {
				$county_id = $this->aG["megye"];
				$county_ids = CountiesModel::getCountySubTree( $county_id );
				$filters[]=sprintf( "member_id in (select member_id from members where county_id in (%s))" , implode( "," , $county_ids ) );
			}

			if (isset( $this->aG["orszag"]) && strlen( $this->aG["orszag"] ) ) {
				$country_id = $this->aG["orszag"];
				$filters[]=sprintf( "member_id in (select member_id from members where country_id='%s')",
					FNTH_db_addslashes( $country_id ) );
			}
			if (isset( $this->aG["utype"]) && strlen( $this->aG["utype"] )) {
				switch ($this->aG["utype"]) {
				case "freelancer":
				case "parttime":
					$filters[]=sprintf( "member_type in ('freelancer','parttime')" );	// ba hack
					break;
				default:
					$filters[]=sprintf( "member_type='%s'" , FNTH_db_addslashes( $this->aG["utype"] ) );
					break;
				}
			}
			if (isset( $this->aG["membership"] ) && strlen( $this->aG["membership"] ) && $this->aG["membership"]>0) {
				$membership_id = $this->aG["membership"];
				$filters[]=sprintf( "member_id in (select member_id from member_memberships where membership_id=%d)",$membership_id );
			}
			if (isset( $this->aG[$this->sKeywordField] ) && strlen( $this->aG[$this->sKeywordField] )) {
				$ks = trim( $this->aG[$this->sKeywordField] );
				$keywords = explode( " " , $ks );
				$km = new KeywordsModel();
				foreach ($keywords as $keyword) {
					$keyword_id = $km->addGetKeyword( $keyword );
					$filters[]=sprintf( "users.user_id in (select user_id from users_keywords where keyword_id=%d)",$keyword_id );
				}
			}
			if ($this->bActiveAgency) {
				if (isset( $this->aG["specialty"]) && $this->aG["specialty"]>0) {
					$filters[]=sprintf( "member_id in (select member_id from member_specialties where specialty_id=%d)" , $this->aG["specialty"] );
				}
				if (isset( $this->aG["cat"]) && $this->aG["cat"]>0) {
					$catq = sprintf( "select member_id from member_cats where cat_id=%d" , $this->aG["cat"] );
					if (isset( $this->aG["cat_req"] ) && strlen( $this->aG["cat_req"] ))
						$catq.=sprintf( " and level>=%d" , $this->aG["cat_req"] );
					$filters[]=sprintf( "member_id in (%s)",$catq );
				}
				if (isset( $this->aG["native_language"] )) {
					$eprop_id = $this->epm->getEPropIdFromName( "native_language" );
					$filters[]=sprintf( "member_id in (select member_id from member_extended_properties where extended_property_id=%d and value='on')" , $eprop_id );
				}
				if (isset( $this->aG["invoice"] )) {
					$eprop_id = $this->epm->getEPropIdFromName( "invoice" );
					$filters[]=sprintf( "member_id in (select member_id from member_extended_properties where extended_property_id=%d and value='on')" , $eprop_id );
				}
				if (isset( $this->aG["experience"] )) {
					$eprop_id = $this->epm->getEPropIdFromName( "experience_5+" );
					$filters[]=sprintf( "member_id in (select member_id from member_extended_properties where extended_property_id=%d and value='on')" , $eprop_id );
				}
				if (isset( $this->aG["certificate"] )) {
					$eprop_id = $this->epm->getEPropIdFromName( "certificate" );
					$filters[]=sprintf( "member_id in (select member_id from member_extended_properties where extended_property_id=%d and value='on')" , $eprop_id );
				}
			}
			if (empty( $filters )) return "";
			return " where " . implode( " and " , $filters );
		}

		protected function addSuperGridHeaderFactory( $id , $parent ) {
			if ($this->bOmitHeader) return null;
			return parent::addSuperGridHeaderFactory( $id , $parent );
		}
		
		public function constructColumns() {
			$this->addColumn( "member" , "<b>". __("searchpage_name","attr") . "</b>" , true );
			$this->addColumn( "member_type" , "<b>".__("searchpage_type","attr")."</b>" , true , array( "width" => 100 , "align" => "center" ) );
			$this->addColumn( "languages" , "<b>". __("searchpage_language","attr")."</b>" , false , array( "align" => "center" ) );
			$this->addColumn( "location" , "<b>".__("searchpage_location","attr")."</b>" , true , array( "align" => "center" ) );
		}

		protected function fieldsClause() {
			return "members.user_id as id,'member' as member,members.member_id,members.member_type,'langs' as languages,city as location";
		}

		public function constructField( $rownum , $row , $colname ) {
			$field = parent::constructField( $rownum , $row , $colname );
			switch ($colname) {
			case "member":
				$field->setValue( "" );	// clear for child widget acceptance
				$member = new UsernameTag( sprintf( "member_%d",$rownum ) , $field );
				$member->setId( $this->aData[$rownum]["id"] );
				break;
			case "member_type":
				$field->setAttribute( "align" , "center" );
				$field->setValue( __($this->aData[$rownum]["member_type"]) );
				break;
			case "languages":
				$field->setAttribute( "align" , "center" );
				break;
			case "location":
				$field->setAttribute( "align" , "center" );
				break;
			}
			return $field;
		}
	}


?>
