<?php
	require_once( $GLOBALS["site_root"] . "/includes/widgets/BackendGrid.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/widgets/AdminSelect.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/widgets/AdminTristate.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/widgets/AdminUserNameTag.inc.php" );
	
	require_once( $GLOBALS["site_root"] . "/includes/models/Job.inc.php" );
	
	class AdminJobsGridHeader extends AdminSuperGridHeader {
	}

	class AdminJobsGrid extends BackendGrid {
		protected $bAjax = false;
		protected $iAdvisedNextPoll = 5000;

		public function __construct( $id , $parent = null ) {
			parent::__construct( $id , $parent );
			$this->sTableName = "jobs";
			$this->sTitle = __("Jobs");
			$this->setSelectable( true );
			$this->iPagesize = 20;
			FNTH_include_3rdparty( "tooltip" );
			
			$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( "all_admin_ack" , __("Acknowledge","attr") , "page_accept",$this->renderStandardAction( "all_admin_ack" ) , false );
			$this->addToolbarButton( "all_admin_resend" , __("Select_for_resend","attr") , "mail_remove",$this->renderStandardAction( "all_admin_resend" ) , false );
			$this->addToolbarButton( "all_send" , __("Send","attr") , "mail",$this->renderStandardAction( "all_send" ) , false );
			$this->job_model = new JobModel();

		}

		public function modifyGetPost( &$g , &$p ) {
			$retval = parent::modifyGetPost( $g , $p );
			if (empty( $this->sOrdering )) {
				$this->sOrdering = "ctstamp";
				$this->bAscending = false;
			}
			if (isset( $this->aP["last_poll"] ) && $this->aP["last_poll"]==0) $this->iAdvisedNextPoll = 1000;
			return $retval;
		}

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

			foreach ($this->aColumns as $colname => $column) {
				$field = new FNTHGridField( uniqid( "" ) , $headerrow );
				switch ($colname) {
				case "job_id":
					$this->job_id_filter = new AdminTextbox( "job_id" , $field );
					$this->job_id_filter->setCSSAttribute( "width" , "30px" );
					$this->addOnEnterCallbackToWidget( $this->job_id_filter );
					break;
				case "job_status":
					$this->job_status_filter = new AdminSelect( "job_status" , $field );
					$this->job_status_filter->addOption( "" , __("Choose") );
					$this->job_status_filter->addOption( "open" , __("myquoterequestspage_status_open") );
					$this->job_status_filter->addOption( "revoked" , __("myquoterequestspage_status_revoked") );
					$this->job_status_filter->addOption( "closed" , __("myquoterequestspage_status_closed") );
					$this->job_status_filter->addOption( "expired" , __("myquoterequestspage_status_after_quote_deadline") );
					break;
				case "job_title":
					$this->job_title_filter = new AdminTextbox( "job_title" , $field );
					$this->addOnEnterCallbackToWidget( $this->job_title_filter );
					break;
				case "poster_name":
					$this->poster_name_filter = new AdminTextbox( "poster_name" , $field );
					$this->addOnEnterCallbackToWidget( $this->poster_name_filter );
					break;
				case "poster_acknowledged":
					$field->setAttribute( "align" , "center" );
					$this->poster_acknowledged_filter = new AdminTristate( "poster_acknowledged" , $field );
					break;
				case "admin_acknowledged":
					$field->setAttribute( "align" , "center" );
					$this->admin_acknowledged_filter = new AdminTristate( "admin_acknowledged" , $field );
					break;
				case "is_sent":
					$field->setAttribute( "align" , "center" );
					$this->is_sent_filter = new AdminTristate( "is_sent" , $field );
					break;
				default:
					break;	
				}
			}
			return $headerrow;
		}

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

		protected function orderClause() {
			if (isset( $this->aP["inajax"] )) return "";	// ajaxban minek rendezzunk
			$retval = "";
			if (empty( $this->sOrdering)) return;
			switch ($this->sOrdering) {
			case "job_title":
			case "poster_name":
			case "poster_acknowledged":
			case "admin_acknowledged":
			case "is_sent":
			case "ctstamp":
			case "job_dealine":
				$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( "job_id in (%s)" , implode( "," , $this->aP["uids"] ) );
				else
					$filters[]=sprintf( "job_id in (0)" );
			} else {
				// job_id
				$v = $this->job_id_filter->getValue();
				if (strlen( $v )) $filters[]=sprintf( "job_id=%d" , $v );
				// job_name
				$v = $this->job_title_filter->getValue();
				if (strlen( $v ))
					$filters[]=sprintf( "job_title ilike '%%%s%%'" , FNTH_db_addslashes( $v ) );
				
				// poster_name
				$v = $this->poster_name_filter->getValue();
				if (strlen( $v ))
					$filters[]=sprintf( "poster_name ilike '%%%s%%'" , FNTH_db_addslashes( $v ) );
				
				// poster_acknowledged
				$v = $this->poster_acknowledged_filter->getValue();
				if (strlen( $v ))
					$filters[]=sprintf( "%s poster_acknowledged",($v==0) ? "not " :"" );
				
				// admin_acknowledged
				$v = $this->admin_acknowledged_filter->getValue();
				if (strlen( $v )) {
					$filters[]=sprintf( "%s admin_acknowledged",($v==0) ? "not " :"" );
				}
				
				// is_sent
				$v = $this->is_sent_filter->getValue();
				if (strlen( $v )) {
					$filters[]=sprintf( "%s is_sent",($v==0) ? "not " :"" );
				}

				if (isset( $this->aG["is_proofread_filter"] )) {
					$v = $this->aG["is_proofread_filter"];
					if (strlen( $v )) {
						$filters[]=sprintf( "%sis_proofread" , ($v) ? "" : "not " );
					}
				}

				$v = $this->job_status_filter->getValue();
				if (strlen( $v )) {
					$filters[]=$this->job_model->getJobFilter( "status_".$v );
				}

			}
			// FNTH_da( $this->admin_acknowledged_filter );
			if (empty( $filters )) return "";
			return " where ".implode( " and " , $filters );
		}
	
		public function constructColumns() {
			$this->addColumn( "job_id" , "#" , true );
			$this->addColumn( "job_title" , __("jobs_Title","attr") , true );
			$this->addColumn( "job_status" , __("jobs_Status","attr") , false );
			$this->addColumn( "poster_name" , __("jobs_Poster_name","attr") , true );
			$this->addColumn( "poster_acknowledged" , __("jobs_Acknowledged","attr") , true );
			$this->addColumn( "admin_acknowledged" , __("jobs_Admin_acknowledged","attr") , true );
			$this->addColumn( "is_sent" , __("jobs_Is_sent","attr") , true );
			$this->addColumn( "ctstamp" , __("jobs_Posted_at","attr") , true );
			$this->addColumn( "job_quote_deadline" , __("jobs_Deadline","attr") , true );
			$this->addColumn( "admin" , __("jobs_Administration","attr") , false );
		}

		protected function fieldsClause() {
			return "jobs.job_id as id, jobs.*";
		}

		protected function isJobAbleToSend( $d ) {
			if ($d["is_sent"]=="t") return false;
			if ($d["admin_acknowledged"]=="f") return false;
			if (isset( $d["activate_task_id"] )) return false;
			if ($d["job_quote_deadline"]<fo3_date( "Y-m-d H:i:s" )) return false;
			return true;
		}

		protected function isJobAbleToAdminAck( $d ) {
			if ($d["admin_acknowledged"]=="t") return false;
			return true;
		}

		protected function renderFieldJobTitle( $d , $ft = FIELD_TYPE_HTML ) {
			$pre_js = $html = $post_js = "";

			$c = "";
			if ($d["is_revoked"]=="t") {
				// revoked
				$c="revoked";
			} else if (substr($d["job_deadline"],0,10)<fo3_date("Y-m-d")) {
				// expired
				$c="deadline";
			} else {
				$c = ($d["is_sent"]=="t") ? "sent" : "unsent";
			}
			$id = sprintf( "title_%d" , $d["job_id"] );
			$u = array();
			$u["mode"]="modify";
			$u["id"]=$d["job_id"];
			$url = FNTH_render_url( "edit.php" , $u );

			$html = sprintf( "<a class=\"%s\" id=\"%s\" href=\"javascript:AdminJobsGridModify( %d );\">%s</a>",
				$c,$id,$d["job_id"],$d["job_title"] );
			$url = sprintf( "/admin/ajax/job_info.php?id=%d" , $d["job_id"] );
			$pre_js = sprintf( "\$(\"#%s\").qtip('hide');",$id );
			$post_js = sprintf( "\$(\"#%s\").qtip( {
				content : { url : '%s' },
				show : { delay: 500 },
				position: 'topLeft',
				hide : {
					fixed: true
				},
				style : { padding: 0, width: { min: 450 , max : 800 } } } );", $id,$url );
			switch ($ft) {
			case FIELD_TYPE_HTML: return $html;
			case FIELD_TYPE_PRE_JS: return $pre_js;
			case FIELD_TYPE_POST_JS: return $post_js;
			}
		}

		protected function renderFieldPosterAcknowledged( $d , $ft = FIELD_TYPE_HTML ) {
			$pre_js = $post_js = "";
			$html = fo3_render_boolean_yesno($d["poster_acknowledged"]);
			switch ($ft) {
			case FIELD_TYPE_HTML: return $html;
			case FIELD_TYPE_PRE_JS: return $pre_js;
			case FIELD_TYPE_POST_JS: return $post_js;
			}
		}

		protected function renderFieldAdminAcknowledged( $d , $ft = FIELD_TYPE_HTML ) {
			$pre_js = $post_js = "";
			$html = fo3_render_boolean_yesno($d["admin_acknowledged"]);
			switch ($ft) {
			case FIELD_TYPE_HTML: return $html;
			case FIELD_TYPE_PRE_JS: return $pre_js;
			case FIELD_TYPE_POST_JS: return $post_js;
			}
		}

		protected function renderFieldIsSent( $d , $ft = FIELD_TYPE_HTML ) {
			$pre_js = $html = $post_js = "";
			if ($d["is_sent"]=="t") {
				// mar kikuldve
				$html = fo3_format_datetime_to_screen( $d["sent_at"] , true );
			} else if (isset( $d["send_task_id"] )) {
				// kuldes alatt van
				if ($d["send_task"]["task_status"]=="failed") {
					$html = __("jobs_Send_failed");
				} else {
					$ts = $d["send_task"]["task_state"];
					if (!isset( $ts ) || empty( $ts ) || !$ts || !isset( $ts["offset"] ) ) {
						$html = __("jobs_Sending");
					} else {
						// progressbaros
						$html = sprintf( "%s<div id=\"progress_%d\" class=\"progress\"></div>%d / %d",
							__("jobs_Sending"),
							$d["id"] ,
							$ts["offset"],
							$ts["number_of_recipients"] );
						$percent = round( $ts["offset"]*100.0/$ts["number_of_recipients"] );
						$post_js = sprintf( "\$(\"#progress_%d\").progressbar( { value: %d } );",$d["id"],$percent );
					}
				}
			} else if (isset( $d["activate_task_id" ] )) {
				// aktivalas alatt
				// progressbaros
				$ts = $d["activate_task"]["task_state"];
				if (isset( $ts["offset"] )) {
					$html = sprintf( "%s<div id=\"progress_%d\" class=\"progress\"></div>%d / %d",
						__("jobs_Activating" ),
						$d["id"] ,
						$ts["offset"],
						$ts["number_of_recipients"] );
					$percent = round( $ts["offset"]*100.0/$ts["number_of_recipients"] );
					$post_js = sprintf( "\$(\"#progress_%d\").progressbar( { value: %d } );",$d["id"],$percent );
				} else {
					$html = __("jobs_Activating" );
				}
			} else {
				$html = __("_no_");
			}
			switch ($ft) {
			case FIELD_TYPE_HTML: return $html;
			case FIELD_TYPE_PRE_JS: return $pre_js;
			case FIELD_TYPE_POST_JS: return $post_js;
			}
		}

		protected function renderFieldAdmin( $d , $ft = FIELD_TYPE_HTML ) {
			$pre_js = "";
			$html = "";
			$post_js = "";

			$buttons = array();
			$prefix = $this->getId() . "_" . $d["id"];

			if ($this->isJobAbleToAdminAck( $d )) {
				// send gombocska
				$buttons[]=$this->renderMiniButton(
					$prefix,
					"admin_ack",
					__("Acknowledge","attr"),
					"page_accept",
					$this->renderStandardAction(
						"admin_ack" , array( "job_id" => $d["id"] )
					)
				);
			}
			if ($this->isJobAbleToSend( $d )) {
				// send gombocska
				$buttons[]=$this->renderMiniButton(
					$prefix,
					"send",
					__("jobs_Send","attr"),
					"mail",
					$this->renderStandardAction(
						"send",
						array( "job_id" => $d["id"] )
					)
				);
			}

			$html = implode( " " , $buttons );
			switch ($ft) {
			case FIELD_TYPE_HTML: return $html;
			case FIELD_TYPE_PRE_JS: return $pre_js;
			case FIELD_TYPE_POST_JS: return $post_js;
			}
		}

		protected function renderFieldJobId( $d , $ft = FIELD_TYPE_HTML ) {
			$pre_js = "";
			$html = $d["job_id"];
			$post_js = "";
			switch ($ft) {
			case FIELD_TYPE_HTML: return $html;
			case FIELD_TYPE_PRE_JS: return $pre_js;
			case FIELD_TYPE_POST_JS: return $post_js;
			}
		}

		protected function renderField( $colname , $d ) {
			switch ($colname) {
			case "job_id": return $this->renderFieldJobId( $d );
			case "job_title": return $this->renderFieldJobTitle( $d );
			case "job_title_pre_js": return $this->renderFieldJobTitle( $d , FIELD_TYPE_PRE_JS );
			case "job_title_post_js": return $this->renderFieldJobTitle( $d , FIELD_TYPE_POST_JS );
			case "poster_acknowledged": return $this->renderFieldPosterAcknowledged( $d );
			case "admin_acknowledged": return $this->renderFieldAdminAcknowledged( $d );
			case "is_sent": return $this->renderFieldIsSent( $d );
			case "is_sent_pre_js": return $this->renderFieldIsSent( $d , FIELD_TYPE_PRE_JS );
			case "is_sent_post_js": return $this->renderFieldIsSent( $d , FIELD_TYPE_POST_JS );
			case "admin": return $this->renderFieldAdmin( $d );
			case "admin_pre_js": return $this->renderFieldAdmin( $d , FIELD_TYPE_PRE_JS );
			case "admin_post_js": return $this->renderFieldAdmin( $d , FIELD_TYPE_POST_JS );
			case "tech_mtstamp":
				return $d[$colname];
			}
		}

		public function constructField( $rownum , $row , $colname ) {
			$field = parent::constructField( $rownum , $row , $colname );
			$d = $this->aData[$rownum];
			switch ($colname) {
			case "job_id":
				$field->setAttribute( "align" , "right" );
				$field->setValue( $this->renderField( $colname , $d ) );
				break;
			case "job_title":
				$field->setValue( $this->renderField( $colname , $d ) );
				FNTHPage::addUniquePageFullInit( $this->renderField( "job_title_post_js" , $d ) );
				break;
			case "job_status":
				$field->setValue( $this->job_model->getJobStatusString( $d ) );
				$field->setAttribute( "align" , "center" );
				break;
			case "poster_name":
				$name = sprintf( "user%d" , $d["id"] );
				$f = new AdminUserNameTag( $name , $field );
				$f->setId( $d["poster_user_id"] );
				$f->setPostfix( "<br/>".$d["ipaddress"] );
				$field->setValue( "" );
				break;
			case "poster_acknowledged":
				$field->setAttribute( "align" , "center" );
				$field->setValue( $this->renderField( $colname , $d ) );
				break;
			case "admin_acknowledged":
				$field->setAttribute( "align" , "center" );
				$field->setValue( $this->renderField( $colname , $d ) );
				break;
			case "is_sent":
				$field->setAttribute( "align" , "center" );
				$field->setValue( $this->renderField( $colname , $d ) );
				FNTHPage::addUniquePageFullInit( $this->renderField( "is_sent_post_js" , $d ) );
				break;
			case "admin":
				$field->setAttribute( "align" , "center" );
				$field->setValue( $this->renderField( $colname , $d ) );
				FNTHPage::addUniquePageFullInit( $this->renderField( "admin_post_js" , $d ) );
				break;
			case "ctstamp":
			case "job_deadline":
			case "job_quote_deadline":
				$field->setAttribute( "align" , "center" );
				$field->setValue(
					(isset($d[$colname])) ? fo3_format_datetime_to_screen( $d[$colname] , true ) : "---"
				);
				break;
			}
			return $field;
		}

		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;
			// get tasks
			$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();

			$furgezzunk = false;
			if (isset( $this->aP["uids"] )) {
				$job_ids = $this->aP["uids"];
				$retval["id"]=$this->aP["id"];
				$retval["ids"]=$job_ids;
				$retval["datas"]=array();
				$fields = array(
					"job_title",
					"job_title_pre_js",
					"job_title_post_js",
					"poster_acknowledged",
					"admin_acknowledged",
					"is_sent",
					"is_sent_pre_js",
					"is_sent_post_js",
					"tech_mtstamp",
					"admin",
					"admin_pre_js",
					"admin_post_js" );
				foreach ($this->aData as $row) {
					if (isset( $row["send_task_id"] ) && $row["is_sent"]=="f" ) $furgezzunk = true;
					if (isset( $row["activate_task_id"] ) && !isset( $row["send_task_id"] )) $furgezzunk = true;
					$job_id = $row["job_id"];
					$item = array ();
					foreach ($fields as $f) $item[$f]=$this->renderField( $f , $row );
					$retval["datas"][$job_id]=$item;
				}
			}

			if ($furgezzunk) $this->iAdvisedNextPoll = 1000;

			$retval["next_poll"]=$this->iAdvisedNextPoll;
			fo3_set_session_readonly();
			FNTH_echo_json_response( $retval , 0 , "fo3_exit" );
		}

		public function handleEvents() {
			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":
					if ($this->aP["tbl"]!=$this->getId()) return parent::handleEvents();
					switch ($this->aP["action"]) {
					case "delete":
						$job_ids = $this->aP["ids"];
						if (!empty( $job_ids )) {
							$jm = new JobModel();
							foreach ($job_ids as $job_id) $jm->deleteJob( $job_id );
						}
						$this->refreshGrid();
						break;
					case "all_admin_ack":
					case "admin_ack":
						if (isset( $this->aP["job_id"] )) {
							$job_ids = array( $this->aP["job_id"] );
						} else {
							$job_ids = $this->aP["ids"];
						}
						if (!empty( $job_ids )) {
							$jm = new JobModel();
							foreach ($job_ids as $job_id) {
								$job = $jm->getJobFromId( $job_id, true );
								if (!$this->isJobAbleToAdminAck( $job )) continue;
								$jm->adminAcknowledgeJob( $job_id );
							}
						}
						$this->refreshGrid();
						break;
					case "all_admin_resend":
						$job_ids = $this->aP["ids"];
						if (!empty( $job_ids )) {
							$jm = new JobModel();
							foreach ($job_ids as $job_id) {
								$jm->clearJobSent( $job_id );
							}
						}
						$this->refreshGrid();
						break;
					case "all_send":
					case "send":
						if (isset( $this->aP["job_id"] )) {
							$job_ids = array( $this->aP["job_id"] );
						} else {
							$job_ids = $this->aP["ids"];
						}
						if (!empty( $job_ids )) {
							$jm = new JobModel();
							foreach ($job_ids as $job_id) {
								$job = $jm->getJobFromId( $job_id, true );
								if (!$this->isJobAbleToSend( $job )) continue;
								$jm->activateJob( $job_id );
							}
						}
						$this->refreshGrid();
						break;
					}
					return parent::handleEvents();
				}
				return parent::handleEvents();
			}
			$this->handleStandardFilterEvent();
			return parent::handleEvents();
		}

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

		protected function generateLangdefs( ) {
			fo3_add_js_langdef( "jobspage_confirm_Ack_jobs" );
			fo3_add_js_langdef( "jobspage_confirm_Send_jobs" );
			fo3_add_js_langdef( "jobspage_confirm_Ack_job" );
			fo3_add_js_langdef( "jobspage_confirm_Send_job" );
			fo3_add_js_langdef( "jobspage_confirm_Delete_jobs" );
			fo3_add_js_langdef( "jobspage_confirm_Resend_jobs" );
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$this->generateLangdefs();

			FNTHPage::setPageHead( "force_job_details_css", FNTH_embed_css_file( $GLOBALS["site_www"]."/design/rp/css/widgets/JobDetails.css" ) );
			FNTHPage::setPageHead( "force_admin_jobs_grid_css", FNTH_embed_css_file( $GLOBALS["site_www"]."/design/rp/css/widgets/AdminJobPreview.css" ) );

			$retval = parent::render();
			$datas = $this->prepareInitialDatas();
			FNTHPage::addUniquePageFullInit( sprintf( "InitAdminJobsGrid( '%s',%s );", $this->getId(),json_encode( $datas ) ) );
			return parent::render();
		}

	}


?>
