<?php
	require_once( $GLOBALS["site_root"] . "/includes/widgets/FrontendSuperGrid.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/urlgen/Blueboard.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Member.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/MyMember.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/User.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/SystemParameters.inc.php" );

	class BlueboardGrid extends FrontendSuperGrid {
		protected $mym = null;
		// select u.*,uc.mtstamp,uc.number_of_comments,uc.score_average from users as u left outer join user_comments as uc on (u.user_id = uc.user_id)

		public function __construct( $id , $parent ) {
			parent::__construct( $id , $parent );
			$this->iPagesize = 30;
			$this->setCSSAttribute( "width" , "100%" );
			$this->_pagenum = "pn";
			$this->_pagesize = "ps";
			$this->_ordering = "ord";
			$this->_orderingdir = "ordd";

			$this->mym = new MyMemberModel();
			$this->um = new UserModel();
			$this->member_model = new MemberModel();
		}

		protected function fieldsClause() {
			return "u.user_id as id,u.user_name,uc.mtstamp,uc.number_of_comments,uc.score_average,m.member_id,'operations' as operations";
		}
		protected function tablesClause() {
			return "users as u
				left outer join user_comments as uc on (u.user_id = uc.user_id)
				left outer join members as m on (u.user_id = m.user_id)";
		}

		protected function addSuperGridHeaderFactory( $id , $parent ) {
			return null;
		}

		public function whereClause() {

			$ff = $this->oParent->oFilterForm;
			if (!isset( $ff )) return "";
			
			$filters = array();
			$filters["not_deleted"]="not u.is_deleted";
			// $filters["admin_acknowledged"]="u.is_admin_acknowledged";

			// only commented
			if ($ff->oAlreadyCommented->isChecked()) $filters[]="mtstamp is not null";

			// commented by me
			if ($ff->oCommentedByMe->isChecked()) {
				$filters[]=sprintf( "u.user_id in (select target_user_id from user_comment_details where poster_user_id=%d and parent_user_comment_detail_id is null)",
					$this->mym->getLoggedinUserId() );
			}

			// name filter
			$f = $ff->oNameFilter->getValue();
			if (strlen( $f )) $filters[]=sprintf( "user_name ilike '%%%s%%'" , FNTH_db_addslashes( $f ) );

			$utype = array();
			if ($ff->oUserType->getChecked("u_users")) $utype[]="(u.is_registered and m.member_type is null)";
			if ($ff->oUserType->getChecked("u_unregistered_users")) $utype[]="(not u.is_registered and m.member_type is null)";
			if ($ff->oUserType->getChecked("u_parttimers")) $utype[]="(m.member_type='parttime')";
			if ($ff->oUserType->getChecked("u_freelancers")) $utype[]="(m.member_type='freelancer')";
			if ($ff->oUserType->getChecked("u_agencies")) $utype[]="(m.member_type='agency')";

			if (!empty( $utype )) {
				$filters[]=sprintf( "(%s)" , implode( " or " , $utype ) );
			} else {
				$filters[]="1=2";
			}

			if (empty( $filters )) return "";
			return " where " . implode( " and " , $filters );
		}

		public function orderClause() {
			$retval = "";
			switch ($this->sOrdering) {
			case "user_name":
			case "mtstamp":
			case "number_of_comments":
				$retval.=$this->sOrdering;
				break;	
			case "score_average":
				if (!$this->mym->isLoggedinMemberActiveSubscriber())
					break;
				$retval.=$this->sOrdering;
				break;
			default:
				return " order by u.feedback_ordering_tstamp desc,u.user_name";
			}
			if (!$this->bAscending) $retval.=" desc";
			return " order by " . $retval;
		}

		public function constructColumns() {
			$this->addColumn( "user_name" ,"<b>".__("blueboardpage_Feedback_target","attr")."</b> ", true );
			$this->addColumn( "mtstamp" , "<b>".__("blueboardpage_Last_comment","attr")."</b> ", true , array( "align" => "center" ) );
			$this->addColumn( "number_of_comments" , "<b>".__("blueboardpage_Number_of_comments","attr")."</b> " , true , array( "align" => "center" ) );
			if ($this->mym->isLoggedinMemberActiveSubscriber())
				$this->addColumn( "score_average" , "<b>".__("blueboardpage_Score_average","attr")."</b> " , true , array( "align" => "center" ) );
			// $this->addColumn( "operations" , __("blueboardpage_Operations","attr") , false );
		}

		public function prepareDataset() {
			$retval = array();

			$is_active_subscriber = $this->mym->isLoggedinMemberActiveSubscriber();
			$is_member = ($this->mym->getLoggedInMemberId()>0);
			$member_id = $this->mym->getLoggedInMemberId();
			$member_type = $this->mym->getLoggedInMemberType();

			$user_id = $this->mym->getLoggedInUserId();

			// userek az adott lapon
			$user_ids = array();
			$member_ids = array();
			$m2u = array();
			$userdata = array();
			foreach ($this->aData as $row) {
				$userdata[$row["id"]]=array(
					"enabled_details" => false,
					"posted_quote" => false,
					"quote_requested" => false,
					"is_member" => isset( $row["member_id"] ) );
				$user_ids[]=$row["id"];
				if (isset( $row["member_id"] )) {
					$member_ids[] = $row["member_id"];
					$m2u[$row["member_id"]]=$row["id"];
				}
			}

			/*
			// posted quote to the user
			if ($is_member) {
				// forditoknak
				$query = sprintf( "select distinct poster_user_id from jobs where job_id in (select job_id from job_quotes where member_id = %d)" , $member_id );
				$poster_users = FNTH_db_get_column( $query , "poster_user_id" );
				foreach ($poster_users as $uid) {
					if (!isset( $userdata[$uid])) continue;
					$userdata[$uid]["posted_quote"]=true;
				}
			}
			*/

			// enabled member details
			$prop_id = $this->member_model->getExtendedPropertyIdFromName( "show_blueboard_details" );
			if ($prop_id && !empty( $member_ids )) {
				$query = sprintf( "select member_id from member_extended_properties where extended_property_id=%d and value='on' and member_id in (%s)" , $prop_id , implode( "," , $member_ids ) );
				// FNTH_da( $query );
				$pmember_ids = FNTH_db_get_column( $query , "member_id" );
				if (!empty( $pmember_ids ))
					foreach ($pmember_ids as $pmember_id) $userdata[ $m2u[$pmember_id] ]["enabled_details"]=true;
			}
				
			foreach ($this->aData as $row) {
				if ($user_id == $row["id"]) {
					// sajat maga
					$row["rowtype"]="own";
				} else if ($is_active_subscriber /* && $member_type!="parttime" */) {
					// olyan aktiv member, aki mindent lat
					if (isset( $row["member_id"] )) {
						// akit megnez az member
						$valid = false;
						if ($userdata[$row["id"]]["enabled_details"]) $valid = true;
						$row["rowtype"]=($valid) ? "valid" : "invalid";
					} else {
						$row["rowtype"]="valid";
					}
				} else {
					// itt jon az egyeb, amikor felteteles
					$valid = false;
					if ($userdata[$row["id"]]["enabled_details"]) $valid = true;		// ha a fordito kifejezetten engedi a dolgot
					/*
					// ha esetleg a forditason mulik
					if ($is_member) {
						// forditoknal
						$valid = (isset( $userdata[ $row["id"]] ) && $userdata[$row["id"]]["posted_quote"]);
					}
					*/
					$row["rowtype"] = ($valid) ? "valid" : "invalid";
				}
				$retval[]=$row;
			}
			$this->aData = $retval;
		}

		public function constructRow( $datarow , $rownum ) {
			$retval = parent::constructRow( $datarow , $rownum );
			switch ($datarow["rowtype"]) {
			case "valid": $f = "job_bgcolor_permitted";break;
			case "own": $f = "job_bgcolor_owned";break;
			case "invalid": $f = "job_bgcolor_disabled";break;
			}
			$col = SystemParametersModel::getVar( $f );
			$retval->setAttribute( "style" , sprintf( "background-color: #%s;" , $col ) );
			return $retval;
		}

		public function constructField( $rownum , $row , $colname ) {
			$field = parent::constructField( $rownum , $row , $colname );
			$rd = $this->aData[$rownum];
			switch ($colname) {
			case "user_name":
				$val = $rd["user_name"];
				$type = $this->um->getUserType( $rd["id"] );
				$val.=sprintf( " (%s)" , __("usertype_about_".$type) );

				$p = $this->aG;
				unset( $p["lang"] );
				$p["user_id"] = $rd["id"];
				$url = BlueboardURL::renderURL( $p , true );

				$val = sprintf( "<a class=\"nrm\" href=\"%s\">%s</a>", $url, $val );
				$field->setValue( $val );
				break;
			case "mtstamp":
				$field->setCSSAttribute( "text-align" , "center" );
				if (!isset( $rd["mtstamp"] )) {
					$field->setValue( "-" );
					break;
				}
				$field->setValue( substr( $rd["mtstamp"] , 0 , 16 ) );
				break;
			case "number_of_comments":
				if (!isset( $rd["number_of_comments"] )) {
					$field->setCSSAttribute( "text-align" , "center" );
					$field->setValue( "-" );
					break;
				}
				$field->setCSSAttribute( "text-align" , "right" );
				break;
			case "score_average":
				if ($rd["rowtype"]=="invalid") {
					$field->setValue( "" );
					break;
				}

				if (!isset( $rd["score_average"] )) {
					$field->setCSSAttribute( "text-align" , "center" );
					$field->setValue( "-" );
					break;
				}
				$field->setCSSAttribute( "text-align" , "right" );
				$field->setValue( number_format( $rd["score_average"] , 2 , "." , " " ) );
				break;
			}
			return $field;
		}

	}

?>
