<?php
	require_once( $GLOBALS["site_root"] . "/includes/models/User.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Member.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/ExtendedProperties.inc.php" );
	

	class BlueboardModel {
		protected $iCommentTimeout = 86400;

		protected function prepareUserCommentDetailRow( $row , $p = array() ) {
			$row["ctstamp"]=substr( $row["ctstamp"] , 0 , 19 );
			return $row;
		}

		public function getUserComments( $user_id ) {
			$query = sprintf( "select * from user_comments where user_id=%d" , $user_id );
			return FNTH_db_get_row( $query );
		}

		public function getUserCommentDetail( $user_comment_detail_id , $p = array() ) {
			$query = sprintf( "select * from user_comment_details where user_comment_detail_id=%d" , $user_comment_detail_id );
			$row = FNTH_db_get_row( $query );
			return $this->prepareUserCommentDetailRow( $row , $p );
		}

		public function updateUserCommentDetail( $user_comment_detail_id , $p = array() ) {
			$upd = array();
			if (isset( $p["user_comment_detail"] ))
				$upd["user_comment_detail"]=sprintf( "'%s'" , FNTH_db_addslashes( $p["user_comment_detail"] ) );
			if (isset( $p["score"] )) 
				$upd["score"]=sprintf( "%d" , FNTH_db_addslashes( $p["score"] ) );
			FNTH_db_free_result(
				FNTH_db_query(
					FNTH_db_generate_update_query( "user_comment_details" , $upd , sprintf( "user_comment_detail_id=%d" , $user_comment_detail_id ) ) ) );
			if (isset( $p["score"] )) {
				$row = $this->getUserCommentDetail( $user_comment_detail_id );
				if (isset( $row["parent_user_comment_detail_id"] )) return;	// valasz, nem kell ujraszamolni
				if (!isset( $row["score"] )) return;	// esetleg nincs pontszam
				$this->recalculateUserAverage( $row["target_user_id"] );
			}
		}

		public function getUserCommentDetails( $user_id , $p = array() ) {
			if (!isset( $p["reply_tree"] )) $p["reply_tree"]=false;
			if (!isset( $p["viewer_user_id"] )) $p["viewer_user_id"]=0;

			// ajanlatkero => meg tudja nezni azokat a forditokat, akik engedtek magukat es a sajat kommentjeit
			// fordito => amennyiben aktiv elofizeto, meg tudja nezni az ajanlatkeroket, illetve azokat a forditokat, akik engedtek magukat

			// csak azokat lehet megnezni, ami vagy sajat, vagy pedig
			// hozzajarult a user

			$allowed_content = false;
			$mm = new MemberModel();
			$member = $mm->getMemberFromUserId( $user_id );
			if ($member) {
				// a target az fordito
				$epm = new ExtendedPropertiesModel();
				$prop_id = $epm->getEPropIdFromName( "show_blueboard_details" );
				$show_blueboard_details = $mm->getMemberExtendedPropertyFromId( $member["member_id"], $prop_id );
				$allowed_content = ($show_blueboard_details=="on");
			} else {
				// a target ajanlatkero
				$allowed_content = false;
				if (isset( $p["viewer_user_id"] )) {
					$viewer_member = $mm->getMemberFromUserId( $p["viewer_user_id"] );
					if ($viewer_member && $viewer_member["member_type"]!="parttime") {
						// ha a source az member, akkor
						$allowed_content = $mm->isMemberActiveSubscriber( $viewer_member["member_id"] , $viewer_member );
					} else {
						// ajanlatkero nem nezhet meg 
						$allowed_content = false;
					}
				}
			}

			$q1=sprintf("select ucd.*,u.* from user_comment_details as ucd,users as u where
				ucd.poster_user_id=u.user_id and
				ucd.parent_user_comment_detail_id is null and
				ucd.target_user_id=%d and
				ucd.is_admin_acknowledged",$user_id);
			$subquery=sprintf("select ucd.user_comment_detail_id from user_comment_details as ucd,users as u where
				ucd.poster_user_id=u.user_id and
				ucd.parent_user_comment_detail_id is null and
				ucd.target_user_id=%d and
				ucd.is_admin_acknowledged",$user_id);
			$q2=sprintf("select ucd.*,u.* from user_comment_details as ucd,users as u where
				ucd.poster_user_id=u.user_id and
				ucd.parent_user_comment_detail_id is not null and
				ucd.parent_user_comment_detail_id in (%s) and
				ucd.poster_user_id=%d and
				ucd.is_admin_acknowledged",
				$subquery,
				$user_id );
			$q = sprintf( "select * from (%s union %s) as alltables order by ctstamp" , $q1 , $q2 );
			$ds = FNTH_db_get_resultset( $q );
			$preorder = array();
			foreach ($ds as $row) {
				$row = $this->prepareUserCommentDetailRow( $row , $p );
				$row["visible"] = ($row["poster_user_id"]==$p["viewer_user_id"] || $row["target_user_id"]==$p["viewer_user_id"]) ? true : $allowed_content;
				$ordid = (isset( $row["parent_user_comment_detail_id"] )) ?
					$row["parent_user_comment_detail_id"] :
					$row["user_comment_detail_id"];
				if (!isset( $preorder[$ordid] )) $preorder[$ordid]=array();
				$preorder[$ordid][]=$row;
			}
			$retval = array();
			if ($p["reply_tree"]) {
				foreach ($preorder as $arrays) {
					$len = count( $arrays );
					switch ($len) {
					case 1:$retval[]=$arrays[0];break;
					case 2:
						$row = $arrays[0];
						$row["reply"]=$arrays[1];
						$retval[]=$row;	
						break;
					}
				}
				return $retval;
			} else {
				// ha nem replytree, akkor kiegyenesites
				foreach ($preorder as $arrays) foreach ($arrays as $row) $retval[]=$row;
			}
			return $retval;
		}

		public function postUserComment(
			$parent_id,
			$poster_user_id,
			$target_user_id,
			$comment,
			$score) {
			$query = sprintf( "select sp_post_user_comment(%s,%d,%d,'%s',%f) as num",
				(isset( $parent_id )) ? sprintf( "%d" , $parent_id ) : "null",
				$poster_user_id,
				$target_user_id,
				FNTH_db_addslashes( $comment ),
				$score );
			return FNTH_db_get_field( $query , "num" );
		}

		public function recalculateUserAverage( $user_id ) {
			$query = sprintf( "select * from user_comment_details where parent_user_comment_detail_id is null and target_user_id=%d and is_admin_acknowledged" , $user_id );
			$ds = FNTH_db_get_resultset( $query );
			
			$exists = (FNTH_db_get_field(
				sprintf( "select count(*) as num from user_comments where user_id=%d" , $user_id ),
				"num" ) > 0 );

			if (empty( $ds )) {
				// ha nincs rekordja de letezik, akkor toroljuk
				if ($exists) {
					FNTH_db_free_result(
						FNTH_db_query( sprintf( "delete from user_comments where user_id=%d" , $user_id ) )
					);
				}
			} else {
				// van, akkor
				$i = 0;
				$score = 0.0;
				foreach ($ds as $row) {
					$score+=$row["score"];
					$i++;
				}
				$avg_score = $score / $i;
				$d = array();
				$d["mtstamp"]="now()";
				$d["user_id"]=sprintf( "%d" , $user_id );
				$d["score_average"]=sprintf( "%.f" , $avg_score );
				$d["score_overall"]=sprintf( "%d" , $score );
				$d["number_of_comments"]=$i;

				if ($exists) {
					$q = FNTH_db_generate_update_query( "user_comments" , $d , sprintf( "user_id=%d" , $user_id ) );
				} else {
					$q = FNTH_db_generate_insert_query( "user_comments" , $d );
				}
				FNTH_db_free_result( FNTH_db_query( $q ) );
			}
		}

		public function alreadyCommented( $poster_user_id , $target_user_id ) {
			$query = sprintf( "select count(*) as num from user_comment_details
				where
					poster_user_id=%d and
					target_user_id=%d and
					parent_user_comment_detail_id is null and
					ctstamp>'%s'",
					$poster_user_id,
					$target_user_id,
					fo3_date( "Y-m-d H:i:s" , fo3_time()-$this->iCommentTimeout ) );
			return (FNTH_db_get_field( $query , "num" )>0);
		}

		public function alreadyReplied( $poster_user_id , $target_user_id ) {
			$query = sprintf( "select count(*) as num from user_comment_details
				where
					poster_user_id=%d and
					target_user_id=%d and
					parent_user_comment_detail_id is not null and
					ctstamp<'%s'",
					$poster_user_id,
					$target_user_id,
					fo3_date( "Y-m-d H:i:s" , fo3_time()-$this->iCommentTimeout ) );
			return (FNTH_db_get_field( $query , "num" )>0);
		}

		public function canViewSearch( $user_id , $user = false , $member = false ) {
			if (!$user) {
				$um = new UserModel();
				$user = $um->getUserFromUserId( $user_id );
			}
			// ha nem user nem nezhet
			if (!$user) return false;
			return true;
			/*
			if (!$member) {
				$mm = new MemberModel();
				$member = $mm->getMemberFromUserId( $user_id );
			}
			// ha nem member, akkor nem nezhet
			if (!$member) return false;
			// ha lejart, akkor sem nezhet

			if ($member["member_type"]=="parttime") return false;
			if (substr( $member["expires_tstamp"] , 0 , 19 )<fo3_date("Y-m-d H:i:s")) return false;
			return true;
			*/
		}

		public function canViewComments( $user_id , $target_user_id ) {
			return true;	// mindenkepp latja a dolgokat, max ki van szurkitve es megsem
			if ($user_id==$target_user_id) return true;
			return $this->canViewSearch( $user_id );
		}
		
		public function hasAbilityToViewComments( $user_id , $user = false , $member = false ) {
			// egyaltalan van-e ra lehetoseg, hogy nezzen
			if (!$user) {
				$um = new UserModel();
				$user = $um->getUserFromUserId( $user_id );
			}
			// ha nem user nem nezhet
			if (!$user) return false;
			if (!$member) {
				$mm = new MemberModel();
				$member = $mm->getMemberFromUserId( $user_id );
			}
			// ha nem member, akkor nem nezhet
			return ($member) ? true : false;
		}

		public function getSearchFilterTypes( $user_id , $user = false , $member = false ) {
			if (!$user) {
				$um = new UserModel();
				$user = $um->getUserFromUserId( $user_id );
			}
			if (!$user) return array();
			if (!$member) {
				$mm = new MemberModel();
				$member = $mm->getMemberFromUserId( $user_id );
			}
			// ha nem member, akkor nem nezhet
			// if (!$member) return array();
			if (!$this->canViewSearch( $user_id , $user , $member )) return array();
			$retval = array();

			switch ($member["member_type"]) {
			case "parttime":

			
			case "freelancer":
				$retval["users"]=true;
				$retval["unregistered_users"]=true;
				$retval["parttimers"]=true;
				$retval["freelancers"]=true;
				$retval["agencies"]=true;
				break;
			case "agency":
				$retval["users"]=true;
				$retval["unregistered_users"]=true;
				$retval["parttimers"]=true;
				$retval["freelancers"]=true;
				$retval["agencies"]=true;
				break;
			default:
				// user
				$retval["users"]=false;
				$retval["unregistered_users"]=false;
				$retval["parttimers"]=true;
				$retval["freelancers"]=true;
				$retval["agencies"]=true;
			}
			return $retval;
		}

		public function proofreadUserComment( $user_comment_detail_id , $proofread = true ) {
			$upd = array();
			$upd["is_proofread"]=($proofread) ? "true" : "false";
			$q = FNTH_db_generate_update_query( "user_comment_details" , $upd,
				sprintf( "user_comment_detail_id=%d" , $user_comment_detail_id ) );
			FNTH_db_free_result( FNTH_db_query( $q ) );
		}

		public function updateUserBlueboardScore( $user_id ) {
			$this->recalculateUserAverage( $suer_id );

			/*
			// TENYLEG MEGEGYSZER MEGIRTAM??? es mennyivel tisztabb mint az elozo...az ember mindig tanul
			$filters = array();
			$filters["user_id"]=sprintf( "target_user_id=%d" , $user_id );
			$filters["ack"]="is_admin_acknowledged";
			$filters["noparent"]="parent_user_comment_detail_id is null";
		
			$query = sprintf( "select * from user_comment_details where %s" , implode( " and " , $filters ) );
			$ds = FNTH_db_get_resultset( $query );
			if (empty( $ds )) return;
			$num=0;
			$score=0;
			foreach ($ds as $row) {
				$score+=$row["score"];
				$num++;
			}
			// now update
			$upd = array();
			$upd["score_overall"]=$score;
			$upd["score_average"]=($num) ? $score/$num : 0;
			$upd["number_of_comments"]=$num;
			FNTH_db_free_result( FNTH_db_query(
				FNTH_db_generate_update_query( "user_comments" , $upd , sprintf( "user_id=%d" , $user_id ) ) ) );
			*/
		}
		
		public function moderateUserComment( $user_comment_detail_id , $is_admin_acknowledged = true ) {
			$upd = array();
			$upd["is_admin_acknowledged"]=($is_admin_acknowledged) ? "true" : "false";
			$q = FNTH_db_generate_update_query( "user_comment_details" , $upd,
				sprintf( "user_comment_detail_id=%d" , $user_comment_detail_id ) );
			FNTH_db_free_result( FNTH_db_query( $q ) );
			$q = sprintf( "select target_user_id as user_id from user_comment_details where user_comment_detail_id=%d" , $user_comment_detail_id );
			$user_id = FNTH_db_get_field( $q , "user_id" );
			$this->recalculateUserAverage( $user_id );
		}

		public function deleteUserComment( $user_comment_detail_id ) {
			$query = sprintf( "select * from user_comment_details where user_comment_detail_id=%d" , $user_comment_detail_id );
			$row = FNTH_db_get_row( $query );
			if (!$row) return;
			if (isset( $row["parent_use_comment_detail_id"] )) {
				// sima valasz
				// akkor csak toroljuk a bejegyzest
				FNTH_db_free_result( FNTH_db_query( sprintf(
					"delete from user_comment_details where user_comment_detail_id=%d" , $user_comment_detail_id ) ) );
			} else {
				// ha komment, akkor eloszor is toroljuk a valaszokat
				FNTH_db_free_result( FNTH_db_query( sprintf(
					"delete from user_comment_details where parent_user_comment_detail_id=%d" , $user_comment_detail_id ) ) );
				// csokkentjuk a bejegyzesek szamat
				$query = sprintf( "update user_comments set number_of_comments = number_of_comments-1 where user_id=%d" , $row["target_user_id"] );
				FNTH_db_free_result( FNTH_db_query( $query ) );
				// es toroljuk a kommentet magat
				FNTH_db_free_result( FNTH_db_query( sprintf(
					"delete from user_comment_details where user_comment_detail_id=%d" , $user_comment_detail_id ) ) );
				$this->recalculateUserAverage( $row["target_user_id"] );
			}
		}
	}
?>
