<?php
	require_once( $GLOBALS["site_root"] . "/includes/widgets/BackendGrid.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/widgets/AdminSelect.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/widgets/AdminTextbox.inc.php" );
	
	require_once( $GLOBALS["site_root"]."/includes/models/Newsletter.inc.php" );
	
	class AdminNewsletterNewslettersGridHeader 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 );
		}
		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$nm = new NewsletterModel();
			$this->oNewsletterGroup->setOptions( $nm->getNewsletterGroupOptions() );
			return parent::render();
		}
	}

	class AdminNewsletterNewslettersGrid extends BackendGrid {
		protected $bAjax = false;

		public function __construct( $id , $parent = null ) {
			parent::__construct( $id , $parent );
			$this->sTableName = "newsletter_newsletters";
			$this->sTitle = __("newsletters_Newsletters");
			$this->setSelectable( true );
			$this->iPagesize = 20;
			$this->addToolbarButton( "filter" , __("Filter","attr") , "search",$this->renderStandardAction( "filter" ) );
			$this->addToolbarButton( "new" , __("New","attr") , "page_add" , $this->renderStandardAction( "new" ) , false );
			$this->addToolbarButton( "modify" , __("Modify","attr") , "page_edit" , $this->renderStandardAction( "modify" ) , false );
			$this->addToolbarButton( "delete" , __("Delete","attr") , "page_remove",$this->renderStandardAction( "delete" ) , false );

			FNTH_include_3rdparty( "tooltip" );
		}

		public function modifyGetPost( &$g , &$p ) {
			parent::modifyGetPost( $g , $p );
			if (empty( $this->sOrdering )) {
				$this->sOrdering = "newsletter_newsletter_id";
				$this->bAscending = false;
			}
			if (isset( $g["newsletter_group_id"] ) && strlen( trim( $g["newsletter_group_id"] ) )) {
				$this->setToolbarButton( "new" , __("New","attr") , "page_add" ,
					$this->renderStandardAction( "new" , 
						array( "newsletter_group_id" => $g["newsletter_group_id"] )
					)
				);
			}
		}

		protected function addSuperGridHeaderFactory( $id , $parent ) {
			return new AdminNewsletterNewslettersGridHeader( $id , $parent );
		}
		
		public function constructFilterHeader() {
			$headerrow = new FNTHGridRow( "filterrow" , $this , "header" );
			$field = new FNTHGridField( uniqid("") , $headerrow );	// ures

			$field = new FNTHGridField( "nl_id" , $headerrow );

			$field = new FNTHGridField( "nl_title" , $headerrow );
			$this->nl_title_filter = new AdminTextbox( "nl_title" , $field );

			$field = new FNTHGridField( "nl_subject" , $headerrow );
			$this->nl_subject_filter = new AdminTextbox( "nl_subject" , $field );
			
			$field = new FNTHGridField( "admin" , $headerrow );
			return $headerrow;
		}

		protected function orderClause() {
			if (isset( $this->aP["inajax"] )) return "";	// ajaxban minek rendezzunk
			$retval = "";
			if (empty( $this->sOrdering)) return;
			switch ($this->sOrdering) {
			case "newsletter_newsletter_id":
			case "nl_title":
			case "nl_subject":
				$retval = $this->sOrdering;
			}
			if (empty( $retval )) return $retval;
			if (!$this->bAscending) $retval.=" desc";
			return " order by " . $retval;
		}

		protected function limitClause() {
			if (isset( $this->aP["inajax"] )) return "";	// ajax megmondja milyen sorok kellenek
			return parent::limitClause();
		}

		protected function whereClause() {
			$filters = array();
			if (isset( $this->aP["inajax"] )) {
				if (isset( $this->aP["uids"] ) && !empty( $this->aP["uids"])) {
					$filters[]=sprintf( "newsletter_newsletter_id in (%s)" , implode( "," , $this->aP["uids"] ) );
				}
			}

			// direkt nem oSuperGridHeader-en keresztul, mert az akkor ugye meg nincsen
			$ng_id = (isset( $this->aG["newsletter_group_id"] ) && strlen( $this->aG["newsletter_group_id"] )) ? $this->aG["newsletter_group_id"] : 0;
			if ($ng_id>0) {
				$filters[]=sprintf( "newsletter_newsletters.newsletter_group_id=%d" , $ng_id );
			}

			if (empty( $filters )) return "";
			return sprintf( " where %s" , implode( " and " , $filters ) );
		}
	
		public function constructColumns() {
			$this->addColumn( "newsletter_newsletter_id" , "#" , true );
			$this->addColumn( "nl_title" , __("newsletters_Newsletter_title","attr") , true );
			$this->addColumn( "nl_subject" , __("newsletters_Newsletter_subject","attr") , true );
			$this->addColumn( "status" , __("newsletters_Newsletter_status","attr") , false );
			$this->addColumn( "admin" , __("newsletters_Admin","attr") , false );
		}

		protected function fieldsClause() {
			return "newsletter_newsletters.newsletter_newsletter_id as id, newsletter_newsletters.*";
		}

		protected function renderFieldNewsletterTitle( $d , $script = false ) {
			$id = sprintf( "title_%d" , $d["newsletter_newsletter_id"] );
			$u = array();
			$u["mode"]="modify";
			$u["id"]=$d["newsletter_newsletter_id"];
			$url = FNTH_render_url( "newsletter_edit.php" , $u );

			$val = sprintf( "<a id=\"%s\" href=\"javascript:AdminNewsletterNewslettersGridModify( %d );\">%s</a>",
				$id,$d["newsletter_newsletter_id"],$d["nl_title"] );
			$js = "";
			return ($script) ? $js : $val;
		}

		protected function renderFieldStatus( $d , $script = false ) {
			$js = "";
			$val = "";
			// esetleg elkuldott
			if (isset( $d["nl_senttstamp"] )) {
				$val = __("newsletters_Sent_at") . "<br/>" . fo3_format_tstamp_to_screen( $d["nl_senttstamp"] );
				return ($script) ? $js : $val;
			}

			// meg nincs elkuldve
			if ($d["nl_is_activated"]=="f") {
				// meg nincs aktivalva
				if (isset( $d["activate_task_id"] )) {
					// aktivalas alatt
					$tm = new TaskManagerModel();
					$ts = $d["activate_task"]["task_state"];
					if (isset( $ts["number_of_recipients"] )) {
						$val = sprintf( "%s<div id=\"progress_%d\" class=\"progress\"></div>%d / %d",
							__("newsletters_Under_activation"),
							$d["id"] ,
							$ts["offset"],
							$ts["number_of_recipients"] );
						$percent = round( $ts["offset"]*100.0/$ts["number_of_recipients"] );
						$js = sprintf( "\$(\"#progress_%d\").progressbar( { value: %d } );",$d["id"],$percent );
					} else {
						$val = __("newsletters_Under_activation" );
					}
				} else {
					$val = __("newsletters_Waiting_for_activation" );
				}
			} else {
				// mar aktivalva van
				if (isset( $d["send_task_id"] )) {
					$tm = new TaskManagerModel();
					$ts = $d["send_task"]["task_state"];
					if (isset( $ts["number_of_recipients"] )) {
						$val = sprintf( "%s<div id=\"progress_%d\" class=\"progress\"></div>%d / %d",
							__("newsletters_Sending" ),
							$d["id"] ,
							$ts["offset"],
							$ts["number_of_recipients"] );
						$percent = round( $ts["offset"]*100.0/$ts["number_of_recipients"] );
						$js = sprintf( "\$(\"#progress_%d\").progressbar( { value: %d } );",$d["id"],$percent );
					} else {
						$val = __("newsletters_Sending");
					}
				} else {
					$val = __("newsletters_Waiting_for_send");
				}
			}
			return ($script) ? $js : $val;
		}
		
		protected function renderFieldAdmin( $d , $script = false ) {
			$prefix = $this->getId() . "_" . $d["id"];
			$js = "";
			$buttons = array();
			// test email
			$buttons[]=$this->renderMiniButton(
				$prefix,
				"test_email",
				__("newsletters_Test_email","attr"),
				"mail",
				$this->renderStandardAction(
					"test_email",
					array( "newsletter_newsletter_id" => $d["id"] )
				)
			);
			$buttons[]=$this->renderMiniButton(
				$prefix,
				"clone",
				__("newsletters_Clone_newsletter","attr"),
				"page_add",
				$this->renderStandardAction(
					"clone_email",
					array( "newsletter_newsletter_id" => $d["id"],
						"newsletter_group_id" => $d["newsletter_group_id"] )
				)
			);
			// ha el van kuldve
			if (isset( $d["nl_senttstamp"] )) {
				$val = implode( " " , $buttons );
				return ($script) ? $js : $val;
			}


			// nincs meg elkuldve
			if ($d["nl_is_activated"]=="f") {
				// nem aktiv
				if (!isset( $d["activate_task_id"] )) {
					$buttons[]=$this->renderMiniButton(
						$prefix,
						"activate",
						__("newsletters_Activate","attr"),
						"accept",
						$this->renderStandardAction(
							"activate",
							array( "newsletter_id" => $d["id"] )
						)
					);
				}
			} else {
				// aktiv, kuldesre var
				if (!isset( $d["send_task_id"] )) {
					$buttons[]=$this->renderMiniButton(
						$prefix,
						"send",
						__("newsletters_Send","attr"),
						"play",
						$this->renderStandardAction(
							"send",
							array( "newsletter_id" => $d["id"] )
						)
					);
				}
				/*
				$buttons[]=$this->renderMiniButton(
					$prefix,
					"send_at",
					__("newsletters_Send_at","attr"),
					"clock",
					$this->renderStandardAction(
						"send_at",
						array( "newsletter_id" => $d["id"] )
					)
				);
				*/
			}
			$val = implode( " " , $buttons );
			return ($script) ? $js : $val;
		}

		protected function renderField( $colname , $d ) {
			switch ($colname) {
			case "nl_title": return $this->renderFieldNewsletterTitle( $d );
			case "nl_title_js": return $this->renderFieldNewsletterTitle( $d , true );
			case "status": return $this->renderFieldStatus( $d );
			case "status_js": return $this->renderFieldStatus( $d , true );
			case "admin": return $this->renderFieldAdmin( $d );
			case "admin_js": return $this->renderFieldAdmin( $d , true );
			}
		}

		public function constructField( $rownum , $row , $colname ) {
			$field = parent::constructField( $rownum , $row , $colname );
			$d = $this->aData[$rownum];
			switch ($colname) {
			case "nl_title":
				$field->setValue( $this->renderField( $colname , $d ) );
				FNTHPage::addUniquePageFullInit( $this->renderField( "nl_title_js" , $d ) );
				break;
			case "status":
				$field->setAttribute( "align" , "center" );
				$field->setValue( $this->renderField( $colname , $d ) );
				FNTHPage::addUniquePageFullInit( $this->renderField( "status_js" , $d ) );
			case "admin":
				$field->setAttribute( "align" , "center" );
				$field->setValue( $this->renderField( $colname , $d ) );
				FNTHPage::addUniquePageFullInit( $this->renderField( "admin_js" , $d ) );
			}
			return $field;
		}

		protected function generateClearScript( $ids ) {
			$retval="";
			// foreach ($ids as $id) $retval.=sprintf( "\$(\"#title_%d\").qtip(\"hide\");",$id );
			return $retval;
		}

		protected function prepareDataset() {
			$tm = new TaskManagerModel();
			// get task_ids
			$task_ids = array();
			foreach ($this->aData as $row) {
				if (isset( $row["activate_task_id"] )) $task_ids[]=$row["activate_task_id"];
				if (isset( $row["send_task_id"] )) $task_ids[]=$row["send_task_id"];
			}
			$task_ids = array_unique( $task_ids );
			if (empty( $task_ids )) return;
			$tasks = $tm->returnTasks( $task_ids );
			// put tasks in dataset
			foreach ($this->aData as $i => $row) {
				if (isset( $row["activate_task_id"] ))
					$row["activate_task"]=$tasks[$row["activate_task_id"]];
				if (isset( $row["send_task_id"] ))
					$row["send_task"]=$tasks[$row["send_task_id"]];
				$this->aData[$i]=$row;
			}
		}

		protected function handleRefreshGridRowsEvent() {
			$this->bAjax = true;
			$query = $this->buildQuery();
			$this->aData = FNTH_db_get_resultset( $query );
			$this->prepareDataset();
			$retval = array();
			if (isset( $this->aP["uids"] )) {
				$newsletter_newsletter_ids = $this->aP["uids"];
				$retval["id"]=$this->aP["id"];
				$retval["ids"]=$newsletter_newsletter_ids;
				// $retval["clearscript"] = $this->generateClearScript( $newsletter_newsletter_ids );
				$retval["datas"]=array();
				$fields = array(
					"nl_title",
					"nl_title_js",
					"status",
					"status_js",
					"admin",
					"admin_js" );
				foreach ($this->aData as $row) {
					$newsletter_newsletter_id = $row["newsletter_newsletter_id"];
					$item = array ();
					$item["clearscript"] = $this->generateClearScript( array( $newsletter_newsletter_id ) );
					foreach ($fields as $f) $item[$f]=$this->renderField( $f , $row );
					$retval["datas"][$newsletter_newsletter_id]=$item;
				}
			}
			FNTH_echo_json_response( $retval , 0 , "fo3_exit" );
		}

		public function handleEvents() {
			// simple POST tasks
			if (isset( $this->aP["task"] )) {
				switch ($this->aP["task"]) {
				case "filter":
					$this->handleFilterEvent();
				case "test_email":
					$nm = new NewsletterModel();
					$nl_id = $this->aP["newsletter_newsletter_id"];
					$nu_id = $nm->addNewsletterUser( array( "newsletter_user_email" => $this->aP["test_email"] ) );
					$nm->sendNewsletterToUser( $nl_id , $nu_id );
					FNTH_refresh();
				case "clone_email":
					$nm = new NewsletterModel();
					$old = $nm->getNewsletterFromId( $this->aP["newsletter_newsletter_id"] );
					$new = $old;
					unset( $new["newsletter_newsletter_id"] );
					$new["newsletter_group_id"]=$this->aP["newsletter_group_id"];
					$new["newsletter_title"]=$this->aP["newsletter_title"];
					$new["newsletter_subject"]=$this->aP["newsletter_subject"];
					$nm->addNewsletter( $new );
					FNTH_refresh();
				}
			}

			if (isset( $this->aP["inajax"] )) {
				if (!isset( $this->aP["ajaxevent"] )) return parent::handleEvents();
				switch ($this->aP["ajaxevent"]) {
				case "refresh_grid_rows": return $this->handleRefreshGridRowsEvent();
				case "table_event":
					$action_reply = "";
					switch ($this->aP["action"]) {
					case "activate":
						$nm = new NewsletterModel();
						$nm->activateNewsletter( $this->aP["newsletter_id"] );
						$this->refreshGrid();
						break;
					case "send":
						$nm = new NewsletterModel();
						$nm->sendNewsletter( $this->aP["newsletter_id"] );
						$this->refreshGrid();
						break;
					case "deactivate":
						$nm = new NewsletterModel();
						$nm->deactivateNewsletter( $this->aP["newsletter_id"] );
						$this->refreshGrid();
						break;
					case "delete":
						if (!empty( $this->aP["ids"])) {
							$nm = new NewsletterModel();
							foreach ($this->aP["ids"] as $nu_id)
								$nm->deleteNewsletter( $nu_id );
						}	
						$this->refreshGrid();
						break;
					}
					FNTH_direct_echo( $action_reply );
					fo_exit();
				}
				return parent::handleEvents();
			}
			return parent::handleEvents();
		}

		protected function prepareInitialDatas() {
			$datas = array();
			$mtstamps = array();
			// row ids
			$ids = array();foreach ($this->aData as $r) {
				$ids[]=$r["id"];
			}
			$datas["ids"]=$ids;
			$nm = new NewsletterModel();
			$datas["newsletter_groups"] = $nm->getNewsletterGroupOptions( false );
			return $datas;
		}

		protected function generateLangDefs() {
			fo3_add_js_langdef( "newsletters_Confirm_delete_newsletter" );
			fo3_add_js_langdef( "newsletters_Confirm_activate_newsletter" );
			fo3_add_js_langdef( "newsletters_Confirm_send_newsletter" );
			fo3_add_js_langdef( "newsletters_Confirm_deactivate_newsletter" );
			fo3_add_js_langdef( "newsletters_Test_email" );
			fo3_add_js_langdef( "newsletters_Cancel" );
			fo3_add_js_langdef( "newsletters_Send" );
			fo3_add_js_langdef( "newsletters_Clone" );
			fo3_add_js_langdef( "newsletters_Clone_newsletter" );
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$this->generateLangDefs();
			$retval = parent::render();
			$datas = $this->prepareInitialDatas();
			FNTHPage::addUniquePageFullInit( sprintf( "InitAdminNewsletterNewslettersGrid( '%s',%s );",
				$this->getId(),json_encode( $datas ) ) );
			return $retval;
		}

	}

?>
