<?php
	require_once( $GLOBALS["site_root"]."/includes/widgets/BackendGrid.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminTextbox.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminNumeric.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminSelect.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminTristate.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminUserStatusFilter.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminSuperGridHeader.inc.php" );

	require_once( $GLOBALS["site_root"]."/includes/models/TaskManager.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Member.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Utype.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Status.inc.php" );

	class AdminMembersGridHeader extends AdminSuperGridHeader {
		public $oKeywordFilter;
		public $oAdminAcknowledged;
		public $oDeveloperFilter = null;

		public function __construct( $id , $parent = null ) {
			parent::__construct( $id , $parent );
			$grid = $parent->getParent()->getParent();

			$this->oKeywordFilter = new AdminTextbox( "keyword_filter" , $this );
			$this->oKeywordFilter->setTitle( __("Keyword" ));
			$this->oKeywordFilter->setShowTitle( true );
			$grid->addOnEnterCallbackToWidget( $this->oKeywordFilter );

			$this->oAdminAcknowledged = new AdminTristate( "is_admin_acknowledged" , $this );
			$this->oAdminAcknowledged->setTitle( __("users_Admin_acknowledged" ));
			$this->oAdminAcknowledged->setShowTitle( true );

		}

		public function modifyGetPost( &$g, &$p ) {
			$this->current_status = (isset( $g["current_status_filter"] )) ? $g["current_status_filter"] : "";
			if (!empty( $this->current_status)) {
				$this->oCurrentStatusFilter = new AdminUserStatusFilter( "current_status_filter" , $this );
				$this->oCurrentStatusFilter->setTitle( __("members_Status" ));
				$this->oCurrentStatusFilter->setShowTitle( true );
			}
			$retval = parent::modifyGetPost( $g , $p );
			if (isset( $this->aG["dev"] )) {
				$this->oDeveloperFilter = new AdminTextbox( "developer" , $this );
				$this->oDeveloperFilter->setTitle( "Developer" );
				$this->oDeveloperFilter->setShowTitle( true );
				$this->oDeveloperFilter->setWidth( 500 );
				$this->oParent->oParent->oParent->addOnEnterCallbackToWidget( $this->oDeveloperFilter );
			}
			return $retval;
		}
	}

	class AdminMembersGrid extends BackendGrid {
		protected $bIsSelector = false;

		protected $username_filter = null;
		protected $fullname_filter = null;
		protected $current_status_filter = null;

		// string
		protected $current_status = "";

		protected $sm = null;

		public function __construct( $id , $parent ) {
			parent::__construct( $id , $parent );

			$this->sm = new StatusModel();

			$this->sTableName = "members,users";
			$this->sTitle = __("members_Members");
			$this->setSelectable( true );

			$this->addToolbarButton( "filter" , __("Filter","attr") , "search",$this->renderStandardAction( "filter" ) );
			// $this->addToolbarButton( "new" , __("New","attr") , "page_add" , $this->renderStandardAction( "new" ) );
			$this->addToolbarButton( "modify" , __("Modify","attr") , "page_edit" , $this->renderStandardAction( "modify" ) , false );
			// $this->addToolbarButton( "delete" , __("Delete","attr") , "page_remove",$this->renderStandardAction( "delete" ) , false );
			$this->addToolbarButton( "status_send" , __("Send_status_notifications","attr") , "mail",$this->renderStandardAction( "status_send" ) , false );
			$this->addToolbarButton( "status_regen" , __("Status_regeneration","attr"), "fast_forward" , $this->renderStandardAction( "status_regen" ) , true );
			FNTH_include_3rdparty( "contextmenu" );
			FNTH_include_3rdparty( "tooltip" );
		}
		
		public function setSelector( $v ) { $this->bIsSelector = $v; }

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

		public function modifyGetPost( &$g, &$p ) {
			$retval = parent::modifyGetPost( $g , $p );
			$this->current_status = "";
			$title = __("members_Members");
			if (isset( $g["current_status_filter"] ) && !empty( $g["current_status_filter"] )) {
				$this->current_status = $g["current_status_filter"];
				$current_status = $g["current_status_filter"];
				$mail_template_id = $this->sm->getStatusTemplateMailIdFromStatus( $current_status );
				if ($mail_template_id) {
					FNTHPage::setPageHead( "admin_mail_templates_grid_js",
						FNTH_embed_js_file( $GLOBALS["site_www"] . "/design/rp/js/widgets/AdminMailtemplatesGrid.js" ) );
					$this->addToolbarButton( "view_status_mail", __("View_status_email","attr"),"forward_new_mail",$this->renderStandardAction( "view_status_mail" ,
						array( "mail_template_id" => $mail_template_id ) ) );
				}
				$title.=sprintf( " - %s" , __("status_".$this->current_status,"attr") );
				$this->sTitle = $title;
			} else if (isset( $g["dirty"] ) && $g["dirty"]>0) {
				$title.=sprintf( " - %s" , __("Modified_members","attr") );
				$this->sTitle = $title;
			}
			FNTHPage::setPageTitle( $title );
			return $retval;
		}

		protected function orderClause() {
			$retval = "";
			switch ($this->sOrdering) {
			case "username": $retval = "member_username";break;
			default:
			case "fullname": $retval = "fullname";break;
			case "member_id": $retval= "member_id";break;
			case "current_status": $retval = "current_status";break;
			case "utype": $retval = "utype";break;
			case "expires_tstamp": $retval = "expires_tstamp";break;
			case "reg_tstamp": $retval = "reg_tstamp";break;
			}
			if (empty( $retval )) return $retval;
			if (!$this->bAscending) $retval.=" desc";

			// ha van statusz szuro
			if (isset( $this->aG["current_status_filter"] ) && !empty( $this->aG["current_status_filter"] )) {
				switch ($this->sOrdering) {
				case "reg_tstamp":
				case "username":
				case "fullname":
				case "member_id":
				case "current_status":
				case "utype":
				case "reg_tstamp":
					// itt nincs default
					break;
				default:
					// de mas nincs megadva, akkor johet az aniko fele juharszirup
					switch ($this->aG["current_status_filter"]) {
					case STATUS_NEW_USER_HAS_TO_PAY:
						// $retval = "reg_tstamp";
						return " order by reg_tstamp desc";
						break;
					default:
						// egyebkent az oirignal default rendezesi feltetel
						break;
					}
				}
				return " order by status_senttstamp desc,".$retval;
			}
			return " order by " . $retval;
		}

		protected function whereClause() {
			$filters = array();
			$filters["member_user"]="members.user_id=users.user_id";
			$filters["user_not_deleted"]="not users.is_deleted";
			$filters["member_not_deleted"]="not members.is_deleted";

			// keyword filter
			$f = $this->oSuperGridHeader->oKeywordFilter->getId();
			if (!empty( $this->aG[$f] )) {
				$v = FNTH_db_addslashes( $this->aG[$f] );
				$filter = sprintf( "users.user_name ilike '%%%s%%'" ,$v );
				$filter.= sprintf( " or users.email ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or users.contact_phone ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.city ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.address ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.phone ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.url ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.billing_name ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.billing_zip ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.billing_city ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.billing_address ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.shipping_name ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.shipping_zip ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.shipping_city ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.shipping_address ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.contact_name ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.contact_email ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.npublic_comment ilike '%%%s%%'" , $v );
				$filter.= sprintf( " or members.member_id in (select member_id from member_extended_properties where value ilike '%%%s%%')" , $v );
				$filters["keyword"]=sprintf( "(%s)" , $filter );
			}

			$f = $this->oSuperGridHeader->oAdminAcknowledged->getValue();
			if (strlen( $f )) {
				switch ($f) {
				case 0:
					$filters["admin_acknowledged"]="not users.is_admin_acknowledged";break;
				case 1:
					$filters["admin_acknowledged"]="users.is_admin_acknowledged";break;
				}
			}

			// username_filter
			$f = $this->username_filter->getId();
			if (!empty( $this->aG[$f] )) {
				$filters["username"]=sprintf( "members.member_username like '%%%s%%'", FNTH_db_addslashes( $this->aG[$f] ) );
			}
			
			// member_id_filter
			$f = $this->member_id_filter->getId();
			if (!empty( $this->aG[$f] )) {
				$v = $this->aG[$f];
				$v = str_replace( "f" , "" , strtolower( $v ) );
				$filters["member_id"]=sprintf( "members.member_id=%d" , $v );
			}

			// fullname_filter
			$f = $this->fullname_filter->getId();
			if (!empty( $this->aG[$f] )) {
				$filters["fullname"]=sprintf( "users.user_name ilike '%%%s%%'", FNTH_db_addslashes( $this->aG[$f] ) );
			}

			// status filter
			if (!empty( $this->current_status )) {
				$filters["current_status"]=sprintf( "current_status='%s'" , FNTH_db_addslashes( $this->current_status ) );
				switch ($this->current_status) {
				case STATUS_DELETED:
				case STATUS_NEW_USER_DELETED:
					unset( $filters["user_not_deleted"] );
					unset( $filters["member_not_deleted"] );
					break;
				}
			}

			// utype filter
			$f = $this->utype_filter->getId();
			if (!empty( $this->aG[$f] ))
				$filters["member_type"]=sprintf( "member_type='%s'" , FNTH_db_addslashes( $this->aG[$f] ) );

			// extra field filter
			$f = "dirty";
			if (!empty( $this->aG[$f])) {
				$dirty = $this->aG[$f];
				switch ($dirty) {
				case 1:
					$filters["dirty"]=sprintf( "members.user_id in (select distinct user_id from dirty_flags)" );
					// FNTH_da( $retval );
					break;
				}
			}
			
			// developer filter
			if (isset( $this->oSuperGridHeader->oDeveloperFilter )) {
				$val = $this->oSuperGridHeader->oDeveloperFilter->getValue();
				if (strlen( $val )) $filters[]=$val;
			}


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

		protected function fieldsClause() {
			return "members.member_id as id,
				members.member_id,
				members.expires_tstamp,
				users.reg_tstamp,
				users.user_id as user_id,
				members.member_username as username,
				users.user_name as fullname,
				members.current_status,
				members.member_type as utype,
				members.status_senttstamp";
		}

		public function constructColumns() {
			$w_tstamp = 120;
			$w_member_id = 50;
			$w_username = 200;
			$w_fullname = 300;
			$w_current_status = 200;
			$w_utype = 120;
			$w_admin = 50;
			$this->addColumn( "member_id" , "#" , true , array( "width" => $w_member_id ) );
			$this->addColumn( "username" , __("members_Username","attr") , true , array( "width" => $w_username ) );
			$this->addColumn( "fullname" , __("members_Name","attr") , true , array( "width" => $w_fullname )  );
			$this->addColumn( "utype" , __("members_Type","attr") , true , array( "width" => $w_utype ) );
			$this->addColumn( "reg_tstamp" , __("users_Registration_tstamp","attr") , true , array( "width" => $w_tstamp ) );
			$this->addColumn( "expires_tstamp" , __("users_Expires_at","attr") , true , array( "width" => $w_tstamp ) );
			if (empty( $this->current_status ))
				$this->addColumn( "current_status" , __("members_Status","attr") , true ,array( "width" => $w_current_status ) );
			$this->addColumn( "admin" , __("members_Admin","attr") , false , array( "width" => $w_admin ) );
		}

		public function constructFilterHeader() {
			$headerrow = new FNTHGridRow( "filterrow" , $this , "header" );

			foreach ($this->aColumns as $colname => $column) {
				$field = new FNTHGridField( "fld_".$colname , $headerrow );
				switch ($colname) {
				default:break;
				case "member_id":
					$this->member_id_filter = new AdminNumeric( "member_id_filter" , $field );
					$this->member_id_filter->setWidth( 40 );
					$this->member_id_filter->setAttribute( "maxlength" , 5 );
					$this->addOnEnterCallbackToWidget( $this->member_id_filter );
					break;
				case "username":
					$this->username_filter = new AdminTextbox( "username_filter" , $field );
					$this->addOnEnterCallbackToWidget( $this->username_filter );
					break;
				case "fullname":
					$this->fullname_filter = new AdminTextbox( "fullname_filter" , $field );
					$this->addOnEnterCallbackToWidget( $this->fullname_filter );
					break;
				case "current_status":
					if (empty( $this->current_status )) {
						$this->current_status_filter = new AdminUserStatusFilter( "current_status_filter" , $field );
						$this->current_status_filter->setCSSAttribute( "width" , "200px" );
					}
					break;
				case "utype":
					$this->utype_filter = new AdminSelect( "utype_filter" , $field );
					$utm = new UtypeModel();
					$this->utype_filter->addOptions( $utm->getUtypeOptions() );
					break;
				}	
			}
		}

		public function handleEvents() {
			// simple POST tasks
			if (isset( $this->aP["task"] )) {
				switch ($this->aP["task"]) {
				case "soft_delete":
					// soft delete - statuszallitas
					$mm = new MemberModel();
					$member = $mm->getMemberFromMemberId( $this->aP["member_id"] );
					$new_status = (strpos( $member["current_status"] , "new_user" )!==false) ?
						STATUS_NEW_USER_DELETED : STATUS_DELETED;
					$mm->updateMemberStatus( $this->aP["member_id"] , $new_status );
					// aztan direkte folyatva a hard
				case "hard_delete":
					// eloszor hard delete
					$mm = new MemberModel();
					$mm->deleteMember( $this->aP["member_id"] );
					FNTH_refresh();
					break;
				case "to_expire":
					$mm = new MemberModel();
					$mm->deleteMember( $this->aP["member_id"] , false );	// undelete
					$member = $mm->getMemberFromMemberId( $this->aP["member_id"] );
					$new_status = (in_array( $member["current_status"] , 
						array(
							STATUS_NEW_USER,
							STATUS_NEW_USER_HAS_TO_PAY,
							STATUS_NEW_USER_EXPIRED_1W,
							STATUS_NEW_USER_EXPIRED_2W,
							STATUS_NEW_USER_EXPIRED_3W,
							STATUS_NEW_USER_EXPIRED_4W,
							STATUS_NEW_USER_EXPIRED_5W,
							STATUS_NEW_USER_EXPIRED_6W,
							STATUS_NEW_USER_EXPIRED_TOTAL,
							STATUS_NEW_USER_DELETED) ));
					$mm->updateMemberStatus( $this->aP["member_id"] , ($new_status) ? 
						STATUS_NEW_USER_EXPIRED_TOTAL : STATUS_EXPIRED_TOTAL , false );
					FNTH_refresh();
					break;
				case "filter":
					$u = $this->aG;
					foreach ($this->aP as $k => $v) {
						if ($k=="task") continue;
						$u[$k]=$v;
					}
					unset( $u[ $this->getId()."_pagenum"] );
					FNTH_redirect( FNTH_render_url( $_SERVER["PHP_SELF"] , $u ) );
					fo_exit();
				}
			}

			// ajax events
			if (!isset( $this->aP["ajaxevent"] )) {
				return parent::handleEvents();
			}
			if (!isset( $this->aP["tbl"] )) {
				return parent::handleEvents();
			}
			if ($this->aP["tbl"]!=$this->getId()) {
				return parent::handleEvents();
			}
			$action_reply = "";
			switch ($this->aP["action"]) {
			case "status_send":
				$tm = new TaskManagerModel();
				$tm->newTask();
				$tm->setTaskName( sprintf( "sending status" ) );
				$tm->setTaskDescription( "status sending" );
				$tm->setTaskType( "status_send" );
				$tm->setTaskState(
					array( "member_ids" => $this->aP["ids"] ) );
				$task_id = $tm->saveNewTask();
				$action_reply = "document.location.href=document.location.href;";
				break;
			case "status_regen":
				$tm = new TaskManagerModel();

				$p = array();
				$p["task_type"]="status_regen";
				$p["task_status"]=array( "closed" , "failed" );
				$p["task_status_negative"]=true;
				$p["limit"]=1;
				$tasks = $tm->getTasks( $p );
				if (count($tasks)) {
					$action_reply = sprintf( "alert( '%s');" , __("userspage_Status_regeneration_already_in_queue","attr") );
				} else {
					$tm->newTask();
					$tm->setTaskName( sprintf( "regenerating status" ) );
					$tm->setTaskDescription( "status regeneration" );
					$tm->setTaskType( "status_regen" );
					$tm->setTaskUID( fo3_time() );
					$task_id = $tm->saveNewTask();
					// $action_reply = sprintf( "alert( '%s');" , __("userspage_Status_regeneration_started_in_bg","attr") );
				}
				break;
			case "delete":
				if (!empty( $this->aP["ids"])) {
					$mm = new MemberModel();
					foreach ($this->aP["ids"] as $member_id)
						$mm->deleteMember( $member_id );
				}	
				$action_reply = "document.location.href=document.location.href;";
				break;
			case "status_activate":
				$mm = new MemberModel();
				$mm->activateMemberStatusEmail( $this->aP["member_id"] );
				$action_reply = "document.location.href=document.location.href;";
				break;
			case "status_deactivate":
				$mm = new MemberModel();
				$mm->deactivateMemberStatusEmail( $this->aP["member_id"] );
				$action_reply = "document.location.href=document.location.href;";
				break;
			}
			FNTH_direct_echo( $action_reply );
			fo_exit();
		}

		public function constructRow( $datarow , $rownum ) {
			$retval = parent::constructRow( $datarow , $rownum );
			$retval->setSelectable( !isset( $datarow["status_senttstamp"] ));
			return $retval;
		}

		public function constructField( $rownum , $row , $colname ) {
			$rd = $this->aData[$rownum];
			$field = parent::constructField( $rownum , $row , $colname );


			switch ($colname) {
			case "username":
				$val="";
				if ($this->bIsSelector) {
					$prefix = sprintf( "select_member_%d" , $rd["id"] );
					$val.=$this->renderMiniButton(
						$prefix,
						"sel_member",
						__("Select_member","attr"),
						"user_add",
						sprintf( "AdminMembersGridSelectMember( %d , '%s' , '%s' );",
							$rd["id"],
							$this->aG["scb"],
							$this->aG["scbparam"] ) ) . " ";
				}
				$val.=  sprintf( "<a class=\"green\" href=\"javascript:AdminMembersGridModify( %d );\">%s</a>" , $rd["id"] , $rd["username"] );
				$field->setValue( $val );
				break;
			case "member_id":
				$field->setAttribute( "align" , "right" );
				break;
			case "current_status":
				$spanid = $field->getFullId() . "_span";
				$statustext = __("status_".$rd["current_status"],"attr");
				$field->setValue( FNTH_simple_span( $spanid , $statustext ) );
				$tooltiptext = "hello world " . md5( uniqid("" ) );
				$tooltip = sprintf( "$('#%s').qtip( { content: '%s' } );",$spanid,$tooltiptext );
				FNTHPage::addUniquePageFullInit( $tooltip );
				$field->setAttribute( "align" , "center" );
				break;
			case "reg_tstamp":
				$field->setAttribute( "align" , "center" );
				$field->setValue( fo3_format_datetime_to_screen( $rd[$colname] ) );
				break;
			case "expires_tstamp":
				$field->setValue( fo3_format_date_to_screen( $rd[$colname] ) );
				$field->setAttribute( "align" , "center" );
				break;
			case "utype":
				$spanid = $field->getFullId() . "_span";
				$field->setValue( FNTH_simple_span( $spanid , __("users_".$this->aData[$rownum]["utype"],"attr" ) ) );
				$field->setAttribute( "align" , "center" );
				$menu = "{\n\tbindings: {\n\t\t";
				$menu.= "'item_1':function(t) { alert( t ); }";
				$menu.= ",'item_2':function(t) { alert( t ); }";
				$menu.= ",'item_3':function(t) { alert( t ); }";
				$menu.= "\t}\n";
				$menu.= "}";
				$context = sprintf( "$('#%s').contextMenu( 'menu1' , %s );" , $spanid , $menu );
				FNTHPage::addUniquePageFullInit( $context );
				break;
			case "admin":
				$field->setAttribute( "nowrap" , "nowrap" );
				$prefix = $this->getId() . "_" . $rd["id"];
				$buttons = array();
				if (isset( $rd["status_senttstamp"] )) {
					// activate
					$buttons[]=$this->renderMiniButton(
						$prefix,
						"status_activate",
						__("Activate_status_email","attr"),
						"page_accept",
						$this->renderStandardAction(
							"status_activate" , array( "member_id" => $rd["id"] )
						)
					);
				} else {
					// deactivate
					$buttons[]=$this->renderMiniButton(
						$prefix,
						"status_deactivate",
						__("Deactivate_status_email","attr"),
						"page_remove",
						$this->renderStandardAction(
							"status_deactivate" , array( "member_id" => $rd["id"] )
						)
					);
				}
				
				$buttons[]=$this->renderMiniButton(
					$prefix,
					"expire",
					__("Expire_member","attr"),
					"user_remove",
					$this->renderStandardAction(
						"expire" , array( "member_id" => $rd["id"] )
					)
				);

				$buttons[]=$this->renderMiniButton(
					$prefix,
					"delete",
					__("Delete_member","attr"),
					"user_remove",
					$this->renderStandardAction(
						"delete" , array( "member_id" => $rd["id"] )
					)
				);
				
				$field->setAttribute( "align" , "center" );
				$field->setValue( implode( "&nbsp;&nbsp;&nbsp;" , $buttons ) );
				break;
			default:
			}
			return $field;
		}

		protected function generateLangDefs() {
			fo3_add_js_langdef( "memberspage_confirm_Delete_members" );
			fo3_add_js_langdef( "memberspage_confirm_Expire_members" );
			fo3_add_js_langdef( "memberspage_confirm_Status_regeneration" );
			fo3_add_js_langdef( "memberspage_confirm_Status_send" );
			fo3_add_js_langdef( "memberspage_confirm_Activate_status_email" );
			fo3_add_js_langdef( "memberspage_confirm_Deactivate_status_email" );

			fo3_add_js_langdef( "memberspage_Delete_members" );
			fo3_add_js_langdef( "memberspage_Expire" );
			fo3_add_js_langdef( "memberspage_Expire_members" );
			fo3_add_js_langdef( "memberspage_Soft_delete" );
			fo3_add_js_langdef( "memberspage_Hard_delete" );
			fo3_add_js_langdef( "Cancel" );
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$this->generateLangDefs();
			return parent::render();
		}

	}

?>
