<?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/Newsletter.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/TaskManager.inc.php" );

	class AdminNewsletterUsersGridHeader extends AdminSuperGridHeader {
		public $oNewsletterGroup;

		public function __construct( $id , $parent = null ) {
			parent::__construct( $id , $parent );
			$this->oNewsletterGroup = new AdminSelect( "newsletter_group_id" , $this );
			$this->oNewsletterGroup->setTitle( __("newsletters_Newsletter_group" ));
			$this->oNewsletterGroup->setShowTitle( true );

			$this->oShowUsers = new AdminSelect( "show_users" , $this );
			$this->oShowUsers->addOption( "all" , __("newsletters_All") );
			$this->oShowUsers->setValue( "all" );
			$this->oShowUsers->addOption( "gfiltered" , __("newsletters_Group_filtered") );
			$this->oShowUsers->setTitle( __("newsletters_Users") );
			$this->oShowUsers->setShowTitle( true );
		}


		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$nm = new NewsletterModel();
			$this->oNewsletterGroup->setOptions( $nm->getNewsletterGroupOptions() );
			return parent::render();
		}
	}

	class AdminNewsletterUsersGrid extends BackendGrid {
		protected $nu_email_filter;
		protected $nu_name_filter;

		protected function prepareDataset() {
			if (!isset( $this->aG["newsletter_group_id"] )) return;
			$ng_id = (int) $this->aG["newsletter_group_id"];
			if (!$ng_id) return;

			$nu_ids = array();
			foreach ($this->aData as $r) $nu_ids[]=$r["id"];
			$query = sprintf( "select newsletter_user_id from newsletter_group_users where newsletter_group_id=%d" , $ng_id );
			$selnu_ids = FNTH_db_get_column( $query , "newsletter_user_id" );
			$sids = array();
			foreach ($selnu_ids as $snu_id) $sids[$snu_id]=true;
			foreach ($this->aData as $id => $row) {
				$row["in_group"]=(isset( $sids[$row["id"]] ));
				$this->aData[$id]=$row;
			}

			if (isset( $this->aG["export"] )) {
				foreach ($this->aData as $row)
					printf( "%s<br/>" , $row['nu_email'] );
				exit();
			}
		}

		public function __construct( $id , $parent ) {
			parent::__construct( $id , $parent );
			$this->sTableName = "newsletter_users";
			$this->sTitle = __("newsletters_Newsletter_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( "import" , __("newsletters_Import_users","attr") , "user_add",$this->renderStandardAction( "import" ) );
			$this->addToolbarButton( "export" , __("Export","attr") , "blog_post",$this->renderStandardAction( "export" ) );
			FNTH_include_3rdparty( "contextmenu" );
			FNTH_include_3rdparty( "tooltip" );
		}

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

		public function modifyGetPost( &$g , &$p ) {
			$retval = parent::modifyGetPost( $g , $p );
			if (isset( $g["newsletter_group_id"] ) && strlen( $g["newsletter_group_id"] )) {
				$this->setToolbarButton( "import" , __("Import","attr") , "user_add",
					$this->renderStandardAction( "import" ,
						array( "newsletter_group_id" => $g["newsletter_group_id"] )
					)
				);
				$this->addToolbarButton( "add_to_group" , __("newsletters_Add_user_to_group","attr"),"application_add",
					$this->renderStandardAction( "add_to_group",
						array( "newsletter_group_id" => $g["newsletter_group_id"] )
					)
				);
				$this->addToolbarButton( "del_from_group" , __("newsletters_Del_user_from_group","attr"),"application_remove",
					$this->renderStandardAction( "del_from_group",
						array( "newsletter_group_id" => $g["newsletter_group_id"] )
					)
				);
			}
			return $retval;
		}

		protected function whereClause() {
			$filters = array();
			$this->oSuperGridHeader->refreshChildValuesFromArray( $this->aG );

			$filter = $this->oSuperGridHeader->oShowUsers->getValue();
			switch ($filter) {
			case "all":
				break;
			case "gfiltered":
				$ng_id = $this->oSuperGridHeader->oNewsletterGroup->getValue();
				if ($ng_id>0) {
					$filters[]=sprintf( "newsletter_users.newsletter_user_id in (select distinct newsletter_user_id from newsletter_group_users where newsletter_group_id=%d)" , $ng_id );
				}	
				break;
			}
			// FNTH_da( $this->oSuperGridHeader->oShowUsers->getValue() );
			


			// nu_name_filter
			$val = $this->nu_name_filter->getValue();
			if (!empty($val))
				$filters[]=sprintf( "newsletter_users.nu_name like '%%%s%%'", FNTH_db_addslashes( $val ));
			
			// nu_email_filter
			$val = $this->nu_email_filter->getValue();
			if (!empty($val))
				$filters[]=sprintf( "newsletter_users.nu_email like '%%%s%%'", FNTH_db_addslashes( $val ));
		
			if (empty( $filters )) return "";
			return sprintf( " where %s" , implode( " and " , $filters ) );
		}

		protected function fieldsClause() {
			return "newsletter_users.newsletter_user_id as id,
				newsletter_users.nu_name,
				newsletter_users.nu_email";
		}

		protected function limitClause() {
			if (!isset( $this->aG["export"] )) return parent::limitClause();
			$this->iPagesize = 100000;
			return array();
		}

		public function constructColumns() {
			$this->addColumn( "nu_email" , __("newsletters_Newsletter_user_email","attr") , true );
			$this->addColumn( "nu_name" , __("newsletters_Newsletter_user_name","attr") , true );
			// $this->addColumn( "admin" , __("newsletters_Admin","attr") , false );
		}

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

			$field = new FNTHGridField( "nu_email" , $headerrow );
			$this->nu_email_filter = new AdminTextbox( "nu_email" , $field );

			$field = new FNTHGridField( "nu_name" , $headerrow );
			$this->nu_name_filter = new AdminTextbox( "nu_name" , $field );
			
			// $field = new FNTHGridField( "admin" , $headerrow );
			return $headerrow;
		}

		protected function handleImportUsersEvent() {
			if (!isset( $_FILES["file_import"] )) return;
			if (!isset( $_FILES["file_import"]["error"] )) return;
			if ($_FILES["file_import"]["error"]) return;
			$file = fopen( $_FILES["file_import"]["tmp_name"] , "r" );
			if (!$file) return;
			$nm = new NewsletterModel();
			$ngid = 0;
			if (isset( $this->aG["newsletter_group_id"] ) && strlen( $this->aG["newsletter_group_id"] ))
				$ngid = (int) $this->aG["newsletter_group_id"];

			while (!feof( $file )) {
				$s = fgets( $file );
				$s = trim( str_replace( array( "\r" , "\n" , "\t" ) , array( "","","" ) , $s ) );
				if (!fo3_is_email_valid( $s )) continue;
				$p = array();
				$p["newsletter_user_email"]=$s;
				$user_id = $nm->addNewsletterUser( $p );
				if (!$user_id) continue;
				if (!$ngid) continue;
				$nm->addNewsletterUserToGroup( $user_id , $ngid );
			}
		}

		public function handleEvents() {
			// simple POST tasks
			if (isset( $this->aP["task"] )) {
				switch ($this->aP["task"]) {
				case "import":
					$this->handleImportUsersEvent();
					FNTH_refresh();
				case "filter":
					$this->handleFilterEvent();
				}
			}

			// 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 "add_to_group":
				if (!empty( $this->aP["ids"])) {
					$nm = new NewsletterModel();
					foreach ($this->aP["ids"] as $nu_id) {
						$nm->addNewsletterUserToGroup( $nu_id , $this->aG["newsletter_group_id"] );
					}
					$action_reply = "document.location.href=document.location.href;";
					break;	
				}
				break;
			case "del_from_group":
				if (!empty( $this->aP["ids"])) {
					$nm = new NewsletterModel();
					foreach ($this->aP["ids"] as $nu_id) {
						$nm->deleteNewsletterUserFromGroup( $nu_id , $this->aG["newsletter_group_id"] );
					}
					$action_reply = "document.location.href=document.location.href;";
					break;	
				}
				break;
			case "delete":
				if (!empty( $this->aP["ids"])) {
					$nm = new NewsletterModel();
					foreach ($this->aP["ids"] as $nu_id)
						$nm->deleteNewsletterUser( $nu_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 );
			if (!isset( $datarow["in_group"] )) return $retval;
			$retval->setSelected( $datarow["in_group"] );
			return $retval;
		}

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

			switch ($colname) {
			case "nu_email":
				$val=sprintf( "<a class=\"green\" href=\"javascript:AdminNewsletterUsersGridModify( %d );\">%s</a>",
					$rd["id"],$rd["nu_email"] );
				$field->setValue( $val );
				break;
			}
			return $field;
		}

		protected function generateLangDefs() {
			fo3_add_js_langdef( "newsletters_Confirm_delete_newsletter_user" );
			fo3_add_js_langdef( "newsletters_Confirm_add_users_to_group" );
			fo3_add_js_langdef( "newsletters_Import_users" );
			fo3_add_js_langdef( "newsletters_Import" );
			fo3_add_js_langdef( "newsletters_Cancel" );
		}

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

	}

?>
