<?php
	require_once( $GLOBALS["site_root"]."/includes/widgets/BackendGrid.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminCheckbox.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminTextbox.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminSuperGridHeader.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminTristate.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminDeleted.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/AdminDateRange.inc.php" );

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

	class AdminUsersGridHeader extends AdminSuperGridHeader {
		public $oKeywordFilter = null;
		public $oDeletedFilter = null;
		public $oDeveloperFilter = null;
		public $oShowMembers = null;

		public function __construct( $id , $parent = null ) {
			parent::__construct( $id , $parent );
			$this->oKeywordFilter = new AdminTextbox( "keyword" , $this );
			$this->oKeywordFilter->setTitle( __("users_Keyword" ));
			$this->oKeywordFilter->setShowTitle( true );

			$this->oDeletedFilter = new AdminDeleted( "deleted" , $this );
			$this->oRegisteredFilter = new AdminTristate( "registered" , $this );
		}

		public function modifyGetPost( &$g , &$p ) {
			$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 );

			}
			$this->oShowMembers = new AdminCheckbox( "show_members" , $this );
			$this->oShowMembers->setShowTitle( true );
			$this->oShowMembers->setTitle( __("Show_members") );
			return $retval;
		}
	}

	class AdminUsersGrid extends BackendGrid {
		protected $reg_tstamp_filter;
		protected $user_name_filter;
		protected $email_filter;
		protected $contact_phone_filter;
		protected $is_acknowledged_filter;
		protected $is_admin_acknowledged_filter;
		protected $is_instant_sender_filter;
		
		protected $bIsSelector = false;

		public function setSelector( $v ) { $this->bIsSelector = $v; }

		public function __construct( $id , $parent ) {
			parent::__construct( $id , $parent );
			$this->sTableName = "users";
			$this->sTitle = __("users_Users");
			$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( "ack" , __("Acknowledge","attr") , "user_accept",$this->renderStandardAction( "ack" ) , false );
			FNTH_include_3rdparty( "contextmenu" );
			FNTH_include_3rdparty( "tooltip" );
		}

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

		protected function orderClause() {
			$retval = "";
			switch ($this->sOrdering) {
			default:
			case "user_name": $retval = "user_name";break;
			case "reg_tstamp": $retval = "reg_tstamp";break;
			case "email": $retval = "email";break;
			case "contact_phone": $retval = "contact_phone";break;
			case "is_acknowledged": $retval = "is_acknowledged";break;
			case "is_admin_acknowledged": $retval = "is_admin_acknowledged";break;
			case "is_instant_sender": $retval = "is_instant_sender";break;
			}
			if (empty( $retval )) return $retval;
			if (!$this->bAscending) $retval.=" desc";
			return " order by ".$retval;
		}

		protected function whereClause() {
			// refresh supergrid
			// refresh filter values
			// $this->oFilterHeader->refreshSubChildValuesFromArray( $this->aG );

			$filters = array();

			if (!$this->show_members)
				$filters["only_users"]="users.user_id not in (select user_id from members)";

			$val = $this->oSuperGridHeader->oDeletedFilter->getValue();
			switch ($val) {
			default:
			case "":$filters[]="(not users.is_deleted)";break;
			case "all":break;
			case "del":$filters[]="(users.is_deleted)";break;
			}

			$val = $this->oSuperGridHeader->oKeywordFilter->getValue();
			if (!empty($val)) {
				$v = FNTH_db_addslashes( $val );
				$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 );
				$filters[]="(".$filter.")";
			}

			// reg_tstamp_filter
			if ($this->reg_tstamp_filter->isFromDate())
				$filters[]=sprintf( "users.reg_tstamp>='%s 00:00:00'" , $this->reg_tstamp_filter->getFromDate() );
			if ($this->reg_tstamp_filter->isToDate())
				$filters[]=sprintf( "users.reg_tstamp<='%s 23:59:59'" , $this->reg_tstamp_filter->getToDate() );

			// user_name_filter
			$val = $this->user_name_filter->getValue();
			if (!empty($val))
				$filters[]=sprintf( "users.user_name ilike '%%%s%%'", FNTH_db_addslashes( $val ));
			
			// email_filter
			$val = $this->email_filter->getValue();
			if (!empty($val))
				$filters[]=sprintf( "users.email like '%%%s%%'", FNTH_db_addslashes( $val ));
			
			// contact_phone_filter
			$val = $this->contact_phone_filter->getValue();
			if (!empty($val))
				$filters[]=sprintf( "users.contact_phone like '%%%s%%'", FNTH_db_addslashes( $val ));
			
			// is_acknowledged_filter
			$val = $this->is_acknowledged_filter->getValue();
			if (strlen($val))
				$filters[]=sprintf( "%s users.is_acknowledged", ($val>0) ? "" : "not" );
			
			// is_admin_acknowledged_filter
			$val = $this->is_admin_acknowledged_filter->getValue();
			if (strlen($val))
				$filters[]=sprintf( "%s users.is_admin_acknowledged", ($val) ? "" : "not" );
			
			// is_instant_sender_filter
			$val = $this->is_instant_sender_filter->getValue();
			if (strlen($val))
				$filters[]=sprintf( "%s users.is_instant_sender", ($val) ? "" : "not" );

			if (isset( $this->oSuperGridHeader->oDeveloperFilter )) {
				$val = $this->oSuperGridHeader->oDeveloperFilter->getValue();
				if (strlen( $val )) $filters[]=$val;
			}

			if (isset( $this->oSuperGridHeader->oRegisteredFilter )) {
				$val = $this->oSuperGridHeader->oRegisteredFilter->getValue();
				switch ($val) {
				case "":
				default:
					break;
				case 0:	$filters[]="not is_registered";break;
				case 1:	$filters[]="is_registered";break;
				}
			}

			return sprintf( " where %s" , implode( " and " , $filters ) );
		}

		protected function fieldsClause() {
			$fields = array();
			$fields[]="users.user_id as id";
			if ($this->show_members)
				$fields[]="members.member_id";
			$fields[]="users.reg_tstamp";
			$fields[]="users.email as email";
			$fields[]="users.contact_phone as contact_phone";
			$fields[]="users.user_name as user_name";
			$fields[]="users.is_acknowledged";
			$fields[]="users.is_admin_acknowledged";
			$fields[]="users.is_instant_sender";
			return implode( "," , $fields );
		}

		protected function tablesClause() {
			if (!$this->show_members) return $this->sTableName;
			return sprintf( "%s left outer join members on (members.user_id = users.user_id)",$this->sTableName );
		}

		public function constructColumns() {
			$this->addColumn( "reg_tstamp" , __("users_Registration_tstamp","attr") , true );
			$this->addColumn( "user_name" , __("users_Name","attr") , true );
			$this->addColumn( "email" , __("users_Email","attr") , true );
			$this->addColumn( "contact_phone" , __("users_Phone","attr") , true );
			$this->addColumn( "is_acknowledged" , __("users_Acknowledged","attr") , true );
			$this->addColumn( "is_admin_acknowledged" , __("users_Admin_acknowledged" , "attr" ) , true );
			$this->addColumn( "is_instant_sender" , __("users_Instant_sender" , "attr" ) , true );
			$this->addColumn( "admin" , __("Admin","attr"), false );
		}

		public function constructFilterHeader() {
			$headerrow = new FNTHGridRow( "filterrow" , $this , "header" );
			$field = new FNTHGridField( uniqid("") , $headerrow );	// ures

			$field = new FNTHGridField( "reg_tstamp" , $headerrow );
			$this->reg_tstamp_filter = new AdminDateRange( "reg_tstamp" , $field );
			
			$field = new FNTHGridField( "user_name" , $headerrow );
			$this->user_name_filter = new AdminTextbox( "user_name" , $field );
			$this->addOnEnterCallbackToWidget( $this->user_name_filter );
			
			$field = new FNTHGridField( "email" , $headerrow );
			$this->email_filter = new AdminTextbox( "email" , $field );
			$this->addOnEnterCallbackToWidget( $this->email_filter );
			
			$field = new FNTHGridField( "contact_phone" , $headerrow );
			$this->contact_phone_filter = new AdminTextbox( "contact_phone" , $field );
			$this->addOnEnterCallbackToWidget( $this->contact_phone_filter );
			
			$field = new FNTHGridField( "is_acknowledged" , $headerrow );
			$field->setAttribute( "align" , "center" );
			$this->is_acknowledged_filter = new AdminTristate( "is_acknowledged" , $field );
			
			$field = new FNTHGridField( "is_admin_acknowledged_field" , $headerrow );
			$field->setAttribute( "align" , "center" );
			$this->is_admin_acknowledged_filter = new AdminTristate( "is_admin_acknowledged" , $field );


			$field = new FNTHGridField( "is_instant_sender" , $headerrow );
			$field->setAttribute( "align" , "center" );
			$this->is_instant_sender_filter = new AdminTristate( "is_instant_sender" , $field );
				
			return $headerrow;
		}

		protected function buildQuery() {
			$this->oSuperGridHeader->refreshChildValuesFromArray( $this->aG );
			$this->show_members = false;
			if (isset( $this->oSuperGridHeader->oShowMembers ))
				$this->show_members = $this->oSuperGridHeader->oShowMembers->isChecked();

			return parent::buildQuery();
		}

		public function handleEvents() {
			// simple POST tasks
			if (isset( $this->aP["task"] )) {
				switch ($this->aP["task"]) {
				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 "ack":
				if (!empty( $this->aP["ids"])) {
					$um = new UserModel();
					foreach ($this->aP["ids"] as $user_id)
						$um->adminAcknowledgeUser( $user_id );
				}	
				$action_reply = "document.location.href=document.location.href;";
				break;
			case "delete":
				if (!empty( $this->aP["ids"])) {
					$um = new UserModel();
					foreach ($this->aP["ids"] as $user_id)
						$um->deleteUser( $user_id );
				}	
				$action_reply = "document.location.href=document.location.href;";
				break;
			case "dlg_merge_user":
				$um = new UserModel();
				$source_user = $um->getUserFromUserId( $this->aP["source_user_id"] );
				$target_user = $um->getUserFromUserId( $this->aP["target_user_id"] );
				$action_reply.=sprintf( "\$(\"#dlg_merge_user_content\").html( \"%s (#%d) =&gt;<br/> %s (#%d)\" );",
					$source_user["user_name"],
					$source_user["user_id"],
					$target_user["user_name"],
					$target_user["user_id"] );
				break;
			case "merge_user":
				$um = new UserModel();
				$um->mergeUserInto( $this->aP["source_user_id"] , $this->aP["target_user_id"] );
				$action_reply = "document.location.href=document.location.href;";
				break;
			}
			FNTH_direct_echo( $action_reply );
			fo3_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 "reg_tstamp":
				$field->setValue( fo3_format_tstamp_to_screen( $rd["reg_tstamp"] ) );
				break;
			case "user_name":
				$val="";
				if ($this->bIsSelector) {
					$prefix = sprintf( "select_user_%d" , $rd["id"] );
					$val.=$this->renderMiniButton(
						$prefix,
						"sel_user",
						__("Select_user","attr"),
						"user_add",
						sprintf( "AdminUsersGridSelectUser( %d , '%s' , '%s' );",
							$rd["id"],
							$this->aG["scb"],
							$this->aG["scbparam"] ) ) . " ";
				}
				if ($this->show_members) {
					$val.=sprintf( "<img src=\"%s/www/icons/16x16/%s\" /> ",
						$GLOBALS["FNTH_www"],
						(isset( $rd["member_id"] )) ? "user.png" : "she_user.png" );
				}
				$val.=sprintf( "<a class=\"green\" href=\"javascript:AdminUsersGridModify( %d );\">%s</a>",
					$rd["id"],$rd["user_name"] );
				$field->setValue( $val );
				break;
			case "contact_phone":
				$field->setAttribute( "align" , "center" );
				break;
			case "is_acknowledged":
			case "is_admin_acknowledged":
			case "is_instant_sender":
				$field->setValue( fo3_render_yesno_from_db( $rd[$colname] ));
				$field->setAttribute( "align" , "center" );
				break;
			case "admin":
				$field->setAttribute( "align" , "center" );
				$prefix = sprintf( "merge_user_%d" , $rd["id"] );
				$val = "";
				$val.=$this->renderMiniButton(
					$prefix,
					"merge_user",
					__("Merge_user","attr"),
					"user",
					sprintf( "AdminUsersGridMergeUserDialog( '%s', %d );",$this->getId() , $rd["id"] ) );
				$field->setValue( $val );
				break;
			}
			return $field;
		}

		protected function generateLangDefs() {
			fo3_add_js_langdef( "userspage_confirm_Delete_users" );
			fo3_add_js_langdef( "userspage_confirm_Admin_acknowledge" );
			fo3_add_js_langdef( "Merge" );
			fo3_add_js_langdef( "Merge_user" );
			fo3_add_js_langdef( "Cancel" );
		}

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

	}

?>
