<?php
	require_once( $GLOBALS["site_root"]."/includes/widgets/Widget.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/TaskManager.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Status.inc.php" );
	

	class BackendTodo extends Widget {
		protected $bPoll = true;
		protected $iAdvisedNextPoll = 5000;

		public function __construct( $id = "BackendTodo" , $parent = null ) {
			parent::__construct( $id , $parent );
		}

		public function modifyGetPost( &$g , &$p ) {
			if (isset( $g["nopoll"] )) $this->bPoll = false;
			$retval = parent::modifyGetPost( $g , $p );
			if (!isset( $this->aP["last_poll_delay"] ) || $this->aP["last_poll_delay"]==0)
				$this->iAdvisedNextPoll = 1000;		// a legelso is kicsit vadabb

			return $retval;
		}

		protected function renderStatusRegen() {
			$retval = array();
			$retval["html"]="";
			$retval["js"]="";

			$tm = new TaskManagerModel();
			$p = array();
			$p["task_type"]="status_regen";
			$p["task_status"]=array( "active" , "inactive" );
			$p["limit"]=1;
			$tasks = $tm->getTasks( $p );
			if (empty( $tasks )) return $retval;
			
			$this->iAdvisedNextPoll = 1000;			// gyorsabb poll, hogy ha tortenik valami latvanyos

			$task = $tasks[0];
			$task_state = $tm->extractTaskState( $task["task_state"] );
			$val = ($task_state["offset"]*100.0/$task_state["number_of_members"]);

			$retval["html"].=sprintf( "<div class=\"alignc\">%s</div><div id=\"sr_progressbar\"></div><hr/>",__("Status_regeneration") );
			$retval["js"].=sprintf( "\$(\"#sr_progressbar\").progressbar( { value: %d } );",$val );

			return $retval;
		}
		
		protected function renderStatusSend() {
			$retval = array();
			$retval["html"]="";
			$retval["js"]="";

			$tm = new TaskManagerModel();
			$p = array();
			$p["task_type"]="status_send";
			$p["task_status"]=array( "active" , "inactive" );
			$p["limit"]=1;
			$tasks = $tm->getTasks( $p );
			if (empty( $tasks )) return $retval;

			$this->iAdvisedNextPoll = 1000;

			$task = $tasks[0];
			$task_state = $tm->extractTaskState( $task["task_state"] );
			if (!isset( $task_state["number_of_members"] )) return $retval;

			$offset = (isset( $task_state["offset"] )) ? $task_state["offset"] : 0;
			$val = ($task_state["offset"]*100.0/$task_state["number_of_members"]);

			$retval["html"].=sprintf( "<div class=\"alignc\">%s</div><div id=\"sr_progressbar\"></div><hr/>",__("Status_sending") );
			$retval["js"].=sprintf( "\$(\"#sr_progressbar\").progressbar( { value: %d } );",$val );

			return $retval;
		}

		protected function renderUnsentStatus() {
			$retval = array();
			$retval["html"]="";
			$retval["js"]="";
			
			$tm = new TaskManagerModel();
			$p = array();
			$p["task_type"]="status_regen";
			$p["task_status"]=array( "active" , "inactive" , "pending" );
			$p["limit"]=1;
			$tasks = $tm->getTasks( $p );
			if (!empty( $tasks )) return $retval;	// ha valami fut, akkor nem rajzolunk linkeket

			$query = sprintf( "select distinct current_status,count(*) as num from members
				where status_senttstamp is null and not is_deleted and user_id in (select user_id from users where not is_deleted)
				group by current_status" );
			$statuses = FNTH_db_get_associative( $query , "current_status" , "num" );
			if (empty( $statuses )) return $retval;

			// now generate links
			$sm = new StatusModel();
			$allstatuses = $sm->getStatusOptions( false );

			$links = array();
			foreach ($allstatuses as $status => $status_title) {
				if (!isset( $statuses[$status] )) continue;
				$page = "/admin/members/";
				$p = array();
				switch ($status) {
				default:
					$p["current_status_filter"]=$status;
				}
				$url = FNTH_render_url( $page , $p );
				$label = __("status_".$status,"attr");
				$num = $statuses[$status];
				$links[]=sprintf( "<a href=\"%s\">%s (%d) &raquo;</a>", $url, $label, $num );
			}

			$retval["html"]=$this->renderTodoBoxHeader( __("Unsent_statuses" ) );
			$retval["html"].=$this->renderTodoBoxContent( sprintf( "<ul><li>%s</li></ul>", implode( "</li><li>",$links ) ) );
			// $retval["html"].=implode( "<br/>" , $links )."<br/><br/>";	// FNTH_da( $statuses , false , true );

			return $retval;
		}

		protected function renderTodoBoxHeader( $string ) {
			return sprintf( "<h3 class=\"ui-accordion-header ui-helper-reset ui-state-default ui-state-active ui-corner-top\" role=\"tab\" aria-expanded=\"true\">
				<span class=\"ui-icon ui-icon-triangle-1-s\"></span>%s</h3>",$string );
		}
		protected function renderTodoBoxContent( $string ) {
			return sprintf( "<div class=\"ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active\">%s</div>",$string );
		}

		protected function renderNewUsers() {
			$retval = array();
			$retval["html"]="";
			$retval["js"]="";

			$filters = array();
			$filters["num_of_new_users"]=array(
				"query" => sprintf( "select count(*) as num from users where user_id not in (select user_id from members) and not is_admin_acknowledged and not is_deleted" ),
				"title" => "Új ajánlatkérők",
				"url" => "/admin/users/?is_admin_acknowledged=0" );
			$filters[STATUS_NEW_USER]=array(
				"query" => sprintf( "select count(*) as num from members where current_status='%s' and user_id in (select user_id from users where not is_deleted and not is_admin_acknowledged)",
					STATUS_NEW_USER ),
				"title" => __("status_".STATUS_NEW_USER),
				"url" => "/admin/members/?is_admin_acknowledged=0&current_status_filter=".STATUS_NEW_USER );

			// elvileg ez az unsent statusban is van, de kozben meg nem
			$filters[STATUS_NEW_USER_HAS_TO_PAY]=array(
				"query" => sprintf( "select count(*) as num from members where current_status='%s' and user_id in (select user_id from users where not is_deleted and not is_admin_acknowledged)",
					STATUS_NEW_USER_HAS_TO_PAY ),
				"title" => __("status_".STATUS_NEW_USER_HAS_TO_PAY),
				"url" => "/admin/members/?is_admin_acknowledged=0&current_status_filter=".STATUS_NEW_USER_HAS_TO_PAY );

			$filters["modified_members"]=array(
				"query" => sprintf( "select count(*) as num from members where user_id in (select distinct user_id from dirty_flags) and not is_deleted" ),
				"title" => __("Modified_members","attr"),
				"url" => "/admin/members/?dirty=1" );

			$maxnum = 0;
			foreach ($filters as $id => $filter) {
				$filters[$id]["result"] = $num = FNTH_db_get_field( $filter["query"] , "num" );
				if ($maxnum<$num) $maxnum=$num;
			}

			if ($maxnum>0) {
				$retval["html"].=$this->renderTodoBoxHeader( "Ajánlatkérők/Tagok" );
				// inner html
				$ih = "<ul>";

				foreach ($filters as $id => $filter) {
					if (!$filter["result"]) continue;
					$ih.=sprintf( "<li><a href=\"%s\">%s (%d) &raquo;</a></li>",
						$filter["url"],$filter["title"],$filter["result"] );
				}
				$ih.= "</ul>";
				// do it
				$retval["html"].=$this->renderTodoBoxContent( $ih );
			}
			return $retval;
		}

		protected function renderServerTime() {
			$retval = array();
			$retval["html"]=$this->renderTodoBoxHeader( "Szerveridő" );
			$retval["html"].=$this->renderTodoBoxContent( sprintf( "<div id=\"server_time\" class=\"alignc\">%s <span style=\"font-family: Courier;\" id=\"server_time_elapsed\">-</span></div>",fo3_date( "Y-m-d H:i:s" ) ) );
			$retval["js"]="";
			// $retval["js"].=sprintf( "iLastServerTime='%s';",fo3_date( "Y-m-d H:i:s" ) );
			return $retval;
		}
		
		protected function renderMisc() {
			$retval = array( "html" => "" , "js" => "" );

			$show = false;

			// get new jobs
			$numofjobs = FNTH_db_get_field(	sprintf( "select count(*) as num from jobs where not is_proofread" ) , "num" );
			if ($numofjobs) $show = true;

			// get user comments
			$numofusercommentdetails = FNTH_db_get_field( sprintf( "select count(*) as num from user_comment_details where not is_proofread" ) , "num" );

			$html = "";
			if ($show) {
				$html.=$this->renderTodoBoxHeader( __("Jobs") . "/" . "Egyéb" );
				$h = "<ul>";
				if ($numofjobs) $h.=sprintf( "<li><a href=\"/admin/jobs/?is_proofread_filter=0\">Új munkaajánlatok (%d) &raquo;</a></li>", $numofjobs );
				if ($numofusercommentdetails) $h.=sprintf( "<li><a href=\"/admin/feedback/?is_proofread=0\">Új visszajelzések (%d) &raquo;</a></li>", $numofusercommentdetails );

				$h.="</ul>";

				$html.=$this->renderTodoBoxContent( $h );
				$retval["html"]=$html;
			}
			return $retval;
		}


		protected function getTodoListDatas() {
			$retval = array();
			$html = "";
			$js = "";

			$st = $this->renderServerTime();
			$html.=$st["html"];
			$js.=$st["js"];

			// new users
			$nu = $this->renderNewUsers();
			$html.=$nu["html"];
			$js.=$nu["js"];

			// status_regen
			$sr = $this->renderStatusRegen();
			$html.=$sr["html"];
			$js.=$sr["js"];
			
			// status_send
			$ss = $this->renderStatusSend();
			$html.=$ss["html"];
			$js.=$ss["js"];

			$mi = $this->renderMisc();
			$html.=$mi["html"];
			$js.=$mi["js"];

			// unsent status
			$uss = $this->renderUnsentStatus();
			$html.=$uss["html"];
			$js.=$uss["js"];

			$retval["html"]=$html;
			$retval["js"]=$js;

			$retval["next_poll"]=$this->iAdvisedNextPoll;
			return $retval;
		}

		public function handleEvents() {
			if (!isset( $this->aP["inajax"] )) return parent::handleEvents();
			if (!isset( $this->aP["ajaxevent"] )) return parent::handleEvents();
			if ($this->aP["ajaxevent"]!="refresh_todolist") return parent::handleEvents();
			$datas = $this->getTodoListDatas();
			fo3_set_session_readonly();
			FNTH_echo_json_response( $datas , 0 , "fo3_exit" );
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$datas = $this->getTodoListDatas();
			$this->setParam( "content" , $datas["html"] );
			FNTHPage::addUniquePageFullInit( sprintf( "InitBackendTodo( '%s' , %s , %s );\n" , $this->getId(),
				($this->bPoll) ? "true" : "false",
				json_encode( $datas["js"] ) ) );
			return parent::render();
		}
	}
?>
