<?php

namespace DataView;

class CampaignState {
  
  

  
  

    // --- Statische Methoden ---
  
  public static function renderScript() { 
    
    
    // --- BLOCK: main ---
    
								\FOP\I18n::ensureIsLoaded();
								?>
								<script type="text/javascript">
									
    function changefilter_campaignState_aftercontactListMultiFilter(val, cb) {
		  if (val) {
			  querySet('filter_campaignState_aftercontact', val, cb.checked);
		  } else {
			  delete query['filter_campaignState_aftercontact'];
		  }reloadcampaignState();
        
    }

		var i9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397timeout = null;
		function changefilter_campaignState_aftercontactSearchFilter(val, callback) {
			if(i9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397timeout) clearTimeout(i9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397timeout);

			i9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397timeout = setTimeout(function() {
				$.getJSON(reloadcampaignState({action: 'getfilter_campaignState_aftercontactItemsByString', 'fstr': val}, true), function(r) {
					callback(r);
					query['filter_campaignState_aftercontact_orig'] = val;
				});
			}, 300);
		}

	function getfilter_campaignState_aftercontactListMultiFilter() {
		var gui = $("<div class='fop-floatsorter'></div>");
		// TODO: usability #1866 auf ajax warten bevor ENTER behandelt wird
		var fstr = <?php echo(isset($_GET['filter_campaignState_aftercontact_orig']) ? json_encode($_GET['filter_campaignState_aftercontact_orig']) : '""') ?>;
		var search = $('<div class="mdl-textfield mdl-js-textfield">' + 
			'<input value="" class="mdl-textfield__input" id="9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397" type="text">' +
			'<label class="mdl-textfield__label" for="9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397">Filter...</label>' +
			'</div>');
		search.find('input').val(fstr).keyup(function (event) {
			var self = this;
			if ((event.keyCode || e.which) == 13) {
				var hasChecked = false;
				if (this.value) {
					// search value + tick all search results
					checkboxes.find('input').each(function (i, inp) {
						if (!inp.checked && $(inp).data('value')) {
							inp.checked = true;
							querySet('filter_campaignState_aftercontact', $(inp).data('value'), true);
							hasChecked = true;
						}
					});
				} else {
					// untick all
					search.find('input').val('');
					query['filter_campaignState_aftercontact_orig'] = '';
					delete query['filter_campaignState_aftercontact'];
					reload('', items);
					hasChecked = true;
				}
				if (hasChecked) {reloadcampaignState();
					
				} else {
					$('#table_campaignState').find('.fop-table-row:first').click();
				}
			} else {
				changefilter_campaignState_aftercontactSearchFilter(this.value, function (result) {
					reload(self.value, result);
				});
			}
		});
		gui.append(search);

		var checkboxes = $("<div></div>").css({maxHeight: '200px', overflow: 'auto'});
		var items = <?php
			// TODO: deps-Variable füllen mit DV-Parametern vom DataView id
			echo json_encode(\DataView\CampaignState::getfilter_campaignState_aftercontactItemsByStringAction(''));
		?>;

		function reload(fstr, items) {
			// rerender checkbox list
			checkboxes.empty();
			checkboxes.append($('<i style="cursor: pointer;"><?php echo _('show all'); ?></i>').click(function () {
				search.find('input').val('');
				query['filter_campaignState_aftercontact_orig'] = '';
				delete query['filter_campaignState_aftercontact'];
				reload('', items);reloadcampaignState();
				
			})).append('<br/>');
			// NULL-Wert auch suchbar #2057 (kommt als ID=0 an, muss für die idlist in _null geändert werden)
			for (var i = 0; i < items.length; i++) {
				let value = (items[i].ID === '0' ? '_null' : items[i].ID);
				let descr = items[i].description;
				let checked = querySet('filter_campaignState_aftercontact', value);
				if (!fstr || checked || descr.toLowerCase().includes(fstr.toLowerCase())) {
					checkboxes.append($('<input type=\'checkbox\'  onclick=\'changefilter_campaignState_aftercontactListMultiFilter("' + value + '", this)\' ' + (checked ? ' checked>': '> ')).data('value', value)).append($('<span></span>').text(descr).prepend('&nbsp;')).append('<br/>');
				}
			 }
		}
		reload(fstr, items);
		gui.append(checkboxes);

		return gui;
	}
									
    function changefilter_campaignState_aftercontactListMultiFilter(val, cb) {
		  if (val) {
			  querySet('filter_campaignState_aftercontact', val, cb.checked);
		  } else {
			  delete query['filter_campaignState_aftercontact'];
		  }reloadcampaignState();
        
    }

		var i9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397timeout = null;
		function changefilter_campaignState_aftercontactSearchFilter(val, callback) {
			if(i9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397timeout) clearTimeout(i9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397timeout);

			i9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397timeout = setTimeout(function() {
				$.getJSON(reloadcampaignState({action: 'getfilter_campaignState_aftercontactItemsByString', 'fstr': val}, true), function(r) {
					callback(r);
					query['filter_campaignState_aftercontact_orig'] = val;
				});
			}, 300);
		}

	function getfilter_campaignState_aftercontactListMultiFilter() {
		var gui = $("<div class='fop-floatsorter'></div>");
		// TODO: usability #1866 auf ajax warten bevor ENTER behandelt wird
		var fstr = <?php echo(isset($_GET['filter_campaignState_aftercontact_orig']) ? json_encode($_GET['filter_campaignState_aftercontact_orig']) : '""') ?>;
		var search = $('<div class="mdl-textfield mdl-js-textfield">' + 
			'<input value="" class="mdl-textfield__input" id="9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397" type="text">' +
			'<label class="mdl-textfield__label" for="9abb76f5265a163d7d85f7efbe1967de1f60f7c46d5a00cde1df959967ae9397">Filter...</label>' +
			'</div>');
		search.find('input').val(fstr).keyup(function (event) {
			var self = this;
			if ((event.keyCode || e.which) == 13) {
				var hasChecked = false;
				if (this.value) {
					// search value + tick all search results
					checkboxes.find('input').each(function (i, inp) {
						if (!inp.checked && $(inp).data('value')) {
							inp.checked = true;
							querySet('filter_campaignState_aftercontact', $(inp).data('value'), true);
							hasChecked = true;
						}
					});
				} else {
					// untick all
					search.find('input').val('');
					query['filter_campaignState_aftercontact_orig'] = '';
					delete query['filter_campaignState_aftercontact'];
					reload('', items);
					hasChecked = true;
				}
				if (hasChecked) {reloadcampaignState();
					
				} else {
					$('#table_campaignState').find('.fop-table-row:first').click();
				}
			} else {
				changefilter_campaignState_aftercontactSearchFilter(this.value, function (result) {
					reload(self.value, result);
				});
			}
		});
		gui.append(search);

		var checkboxes = $("<div></div>").css({maxHeight: '200px', overflow: 'auto'});
		var items = <?php
			// TODO: deps-Variable füllen mit DV-Parametern vom DataView id
			echo json_encode(\DataView\CampaignState::getfilter_campaignState_aftercontactItemsByStringAction(''));
		?>;

		function reload(fstr, items) {
			// rerender checkbox list
			checkboxes.empty();
			checkboxes.append($('<i style="cursor: pointer;"><?php echo _('show all'); ?></i>').click(function () {
				search.find('input').val('');
				query['filter_campaignState_aftercontact_orig'] = '';
				delete query['filter_campaignState_aftercontact'];
				reload('', items);reloadcampaignState();
				
			})).append('<br/>');
			// NULL-Wert auch suchbar #2057 (kommt als ID=0 an, muss für die idlist in _null geändert werden)
			for (var i = 0; i < items.length; i++) {
				let value = (items[i].ID === '0' ? '_null' : items[i].ID);
				let descr = items[i].description;
				let checked = querySet('filter_campaignState_aftercontact', value);
				if (!fstr || checked || descr.toLowerCase().includes(fstr.toLowerCase())) {
					checkboxes.append($('<input type=\'checkbox\'  onclick=\'changefilter_campaignState_aftercontactListMultiFilter("' + value + '", this)\' ' + (checked ? ' checked>': '> ')).data('value', value)).append($('<span></span>').text(descr).prepend('&nbsp;')).append('<br/>');
				}
			 }
		}
		reload(fstr, items);
		gui.append(checkboxes);

		return gui;
	}
									function updateNumbercampaignState(col) {
										//var checklist = window.DataViewChecked['campaignState'][col];
										//if (checklist.id) {
											// checklist is online
											// TODO: check if cache is alive, otherwise reload from ajax, delay execution and return now
											//checklist.ranges = [[1,10000000]]; // mostly we use indirect idlists to tick all marks; so this is an approximation
										//}
										// checkboxes aktualisieren
										if (window.DataViewChecked && window.DataViewChecked['campaignState'] && window.DataViewChecked['campaignState'][col].ranges.length > 0) {
											$('.campaignState__mass-action').css('visibility', 'visible');
											$('.campaignState__action').css('visibility', 'hidden');
										} else {
											$('.campaignState__mass-action').css('visibility', 'hidden');
											$('.campaignState__action').css('visibility', 'visible');
										}
										$('.campaignState__checkbox').each(function (idx, x) {
											for (var cssclass of x.classList) {
												if (cssclass.startsWith('campaignState__checkbox-'+col+'-')) {
													var my_id = cssclass.substr(('campaignState__checkbox-'+col+'-').length);
													if (window.DataViewChecked) {
														x.MaterialCheckbox[checklist.has(my_id) ? 'check' : 'uncheck']();
													}
												}
											}
										});
									}
									function reloadcampaignState (params, returnUrl, onlyScroll, addPadding = 0) {
										// copy query
										let nq = JSON.parse(JSON.stringify(query));
										nq['parent_request'] = <?php echo json_encode(strtok(\FOP\Util::getBackUrl(), '?')); ?>;
										<?php if (isset($_GET['select'])) { ?>nq['select'] = 'select';<?php } ?>
										
										if (params) {
											for (var i in params) nq[i] = params[i];
											var action = nq['action'];
											delete nq['action'];
											let querystr = "DataView/CampaignState/" + action + "?" + Object.keys(nq).map(function(k){ return k + "=" +  encodeURIComponent(nq[k]); }).join("&");
											// direkt aufrufen (ist wohl ein Download oder so)
											if (returnUrl) return querystr;
											window.location.href = querystr;
										} else {
											let querystr;
											
											
											<?php if (((\FOP\User::getCampaign())) && (!\FOP\User::getIsGuest())) { ?>
											delete nq['action'];
											querystr = "DataView/CampaignState/renderTabTable?" + Object.keys(nq).map(function(k){ return k + "=" +  encodeURIComponent(nq[k]); }).join("&");
											// per Ajax laden
											if(!$("#campaignState-table")?.parent()?.parent()?.hasClass('fop-form-feature-collapsed') || $("#campaignState-table")?.parent()?.parent()?.hasClass('fop-form-feature-mode-area')) {
											$.get(querystr, function(data){
												var tab = $("#campaignState-table");
												var top = tab.find('.fop-table-body-inner');
												var el;
												if (onlyScroll && (el = $('<div class="tabcontent">' + data + '</div>').find('.fop-table-body-inner'))) {
													// nur Scroll-Bereich ersetzen
													var paddingTop = parseInt(el.css('paddingTop') || '0px', 10);
													var minHeight = parseInt(el.css('minHeight'), 10)
													paddingTop += addPadding;
													minHeight += addPadding;
													top.css({paddingTop: paddingTop.toString()+'px', minHeight: minHeight.toString()+'px'}); // Offset
													el = el.children();
													top.empty();
													top.append(el);
													el = top; // top-upgrade doppelt machen, dadurch vermeiden wir das Array-upgrade => Performance
												} else {
													// gesamten Tab ersetzen
													tab.children().remove();
													el = tab.html('<div class="tabcontent">' + data + '</div>');
												}
												try {
													for (var i = 0; i < el.length; i++) upgradeDOM(el[i]);
												} catch (e) {
													console.log(e);
												}
												upgradeTable(el.find('.fop-table .fop-table-header')); // Falls es Tabellen-Layout ist: Spalten-Order anpassen
												flushURL(); // Neue URL in Titelleiste eintragen

												// Checkbox-Auswahl ankreuzen
												updateNumbercampaignState('ID');
											});
											} else {
												// gesamten Tab ersetzen
												var tab = $("#campaignState-table");
												tab.children().remove();
												el = tab.html('<div class="fop-lazy-reload" onclick="reloadcampaignState()"></div>');
											}
											<?php } ?>
											
										}
									}
									function checkcampaignState (id, col, checked) {
										// ID-Liste aufbauen
										if (!window.DataViewChecked) window.DataViewChecked = {};
										if (!window.DataViewChecked['campaignState']) window.DataViewChecked['campaignState'] = {};
										if (!window.DataViewChecked['campaignState'][col]) window.DataViewChecked['campaignState'][col] = new IDList();

										// Abfrage aller gecheckten IDs für eine Tabelle
										if (!id) {
											return window.DataViewChecked['campaignState'][col].toString();
										}

										// check all, check id
										if (id == 'all') {
											// TODO: umbauen #1289: 'all' auch nur auf ne idlist reduzieren
											if (checked) {
												$.get(reloadcampaignState({action: 'getids', col: col}, true), function (ids) {
													window.DataViewChecked['campaignState'][col] = new IDList(ids);
													updateNumbercampaignState(col);
												});
											} else {
												window.DataViewChecked['campaignState'][col] = new IDList();
												updateNumbercampaignState(col);
											}
										} else {
											var ids = new IDList(id);
											var allcb = $('#campaignState__all-checkbox');
											if (allcb[0]) {
												allcb[0].parentElement.MaterialCheckbox.uncheck(); // TODO: prüfen, ob Gruppen-CBs voll werden
											}
											if (checked == 'set') {
												window.DataViewChecked['campaignState'][col] = ids;
											} else for (id of ids.all()) {
												if (checked) {
													window.DataViewChecked['campaignState'][col].push(id);
												} else {
													window.DataViewChecked['campaignState'][col].remove(id);
												}
											}
											updateNumbercampaignState(col);
										}
									}
								</script><?php

    
  }

  public static function renderSpecialFilters() { 
    
    
    // --- BLOCK: main ---
    ?>
	
	<script type"text/javascript">
		function updateSpecialFilter(param, val) {
			query[param] = val.toString();reloadcampaignState();
			
		}

	</script>
	<?php
	
    
  }

  public static function renderTabTableAction() { 
    
    
    // --- BLOCK: access ---
    
    // --- BLOCK: main ---
     ?><div class='fop-dv-buttonbar'><?php if(((\FOP\User::getCampaign()))) { ?><a class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="
		var self = this;
		event.preventDefault();
		$.get(reloadcampaignState({action: 'open', fop_table: 'campaignState', fop_id: '_', fop_from: location.href}, true))
		.then(function () {
			window.open_url(self.href, false);
		});" href="<?php echo htmlentities(\TablesRouter\CampaignState::createURL2(['from' => $_GET['from'] ?? null, 'popup' => $_GET['popup'] ?? null])); ?>"><i class="material-icons">add</i> <?php echo(sprintf(_('create %s'), sprintf(_('%s-Status'), _('Aktion')))); ?></a><?php } ?></div><?php 
								\FOP\User::getIsGuest();
								$itemheight = 32;
								$itemsperpage = ceil(1080 / $itemheight * 0.8);
								$page = (isset($_GET['page_campaignState']) ? intval($_GET['page_campaignState']) : 0);
								$addlines = (isset($_GET['addlines_campaignState']) ? intval($_GET['addlines_campaignState']) : 0);
								$firstitem = $page * $itemsperpage;
								$sqladdon = ' LIMIT ' . ($itemsperpage * 2) . ' OFFSET ' . ($firstitem);
								$data = self::getData($sqladdon, $_GET);
								$arr = $data["items"];
								$itemcount = $data["itemcount"];
								$lastPage = ceil($itemcount/$itemsperpage-1);
								// calculate width of first column: 67px + 32px for each shortcut
								$firstColumnWidth = 66 + 34 + 34 + 34;
								$additionalLines = 0;

									// Spaltenliste zuerst aufbauen, damit sie noch umsortiert werden kann
									$order = 1000;
									$columns = [];
									
										if(true){
											$col = [
												'id' => 'desc',
												'desc' => _('Status'),
												'order' => ++$order,
												'width' => 180, // default value
												'collapsed' => 0

											];
											$columns['desc'] = $col;
										}
									
										if(true){
											$col = [
												'id' => 'aftercontact',
												'desc' => _('Status nach Kontaktierung'),
												'order' => ++$order,
												'width' => 180, // default value
												'collapsed' => 0

											];
											$columns['aftercontact'] = $col;
										}
									
										if(true){
											$col = [
												'id' => 'endstate',
												'desc' => _('Endzustand'),
												'order' => ++$order,
												'width' => 40, // default value
												'collapsed' => 0

											];
											$columns['endstate'] = $col;
										}
									
										if(true){
											$col = [
												'id' => 'color',
												'desc' => _('Farbe'),
												'order' => ++$order,
												'width' => 180, // default value
												'collapsed' => 0

											];
											$columns['color'] = $col;
										}
									

									// gespeicherte Spaltenanordnung
									foreach (\FOP\Database::query('SELECT * FROM fop_dataview WHERE '.qi('user').' = ' . \FOP\Database::quote(\FOP\User::getID()) . ' AND dataview = ' . \FOP\Database::quote('campaignState'))->fetchAll(\PDO::FETCH_ASSOC) AS $column => $c) {
										if (isset($columns[$c['column']])) {
											$columns[$c['column']]['order'] = $c['order']; // order, width, collapsed
											$columns[$c['column']]['width'] = $c['width']; // order, width, collapsed
											$columns[$c['column']]['collapsed'] = $c['collapsed']; // order, width, collapsed
										}
									}

									// DOM vor-rendern
									
										
										if(true){
											ob_start();
											?><div class="fop-table-column overlay"
												data-column='desc'
												data-order='<?php echo intval($columns['desc']['order']); ?>'
												data-width='<?php echo intval($columns['desc']['width']); ?>'
												data-collapsed='<?php echo intval($columns['desc']['collapsed']); ?>'
												style='width: <?php echo intval($columns['desc']['width']); ?>px; <?php if ($columns['desc']['collapsed'] == 1) { echo ' display: none;'; } ?>'>
												<span class='title' onclick="
		var changed = false, win = dropDownFixPosition($(this), null, function() { if (changed) {
			
			reloadcampaignState(); 
		}});
		
		var el = $('<div class=\'mdl-textfield mdl-js-textfield mdl-textfield--floating-label fop-floatsorter\' style=\'width: calc(100% - 42px);\'><input class=\'mdl-textfield__input\' style=\'display: inline-block;\' type=\'text\'><label class=\'mdl-textfield__input\'><?php echo(_('search')); ?></label></div>');
		win.append(el);
		var text = el.find('input');
		text.val(query['search_campaignState_desc'])
		text.on('change keyup paste', function () { if (text.val()) { query['search_campaignState_desc'] = text.val(); } else { delete query['search_campaignState_desc']; } changed = true; });
		text.focus();
		text.select();
		text.keydown(function (event) {if ((event.keyCode || event.which) == 13) {$('#table_campaignState').find('.fop-table-row:first').click();} if (event.key === 'Escape') { win.close(); }});

		var el2 = $('<div class=\'mdl-textfield mdl-js-textfield mdl-textfield--floating-label\'><input class=\'mdl-textfield__input\' style=\'display: inline-block;\' type=\'text\'><label class=\'mdl-textfield__input\'><?php echo(htmlentities(htmlentities(_('filter_contains_not')))); ?></label></div>');
		win.append(el2);
		var text2 = el2.find('input');
		text2.val(query['searchnot_campaignState_desc'])
		text2.on('change keyup paste', function () { if (text2.val()) { query['searchnot_campaignState_desc'] = text2.val(); } else { delete query['searchnot_campaignState_desc']; } changed = true; });
		text2.keydown(function (event) {if ((event.keyCode || event.which) == 13) {$('#table_campaignState').find('.fop-table-row:first').click();} if (event.key === 'Escape') { win.close(); }});
	
	var icon, sortbtn	= $('<a class=\'mdl-button mdl-js-button mdl-button--icon mdl-button--colored\' style=\'display: inline-block;\'></a>')
		.append(icon = $('<i class=\'material-icons\'></i>').text('unfold_more'))
		.click(function() {
		 if (query['sort_campaignState'] == 'desc ASC') {
			query['sort_campaignState'] = 'desc DESC';
		 } else if (query['sort_campaignState'] == 'desc DESC') {
		 	delete query['sort_campaignState'];
		 } else {
			query['sort_campaignState'] = 'desc ASC';
		 }
		 reloadcampaignState();
		 return false;
	});
	if (win.children().first().hasClass('fop-floatsorter')) {
		// floating layout
		win.prepend(sortbtn.css({float: 'right', margin: '0px'}));
	} else {
		// append to the end
		win.append(sortbtn);
	}
		return false;
	">
													<span class='title-title' title='<?php echo(_('Status')); ?>'><?php echo(_('Status')); ?></span>
													<?php // sort indicator
														if (isset($_GET['sort_campaignState']) && $_GET['sort_campaignState'] == 'desc ASC') {
															?><i class='material-icons fop-small'>keyboard_arrow_down</i><?php
														} else if (isset($_GET['sort_campaignState']) && $_GET['sort_campaignState'] == 'desc DESC') {
															?><i class='material-icons fop-small'>keyboard_arrow_up</i><?php
														}
														if (isset($_GET['range_min_campaignState_desc']) || isset($_GET['range_max_campaignState_desc']) || isset($_GET['deps_campaignState_desc']) || isset($_GET['fullsearch_campaignState_desc']) || isset($_GET['dynamic_campaignState_desc']) || isset($_GET['search_campaignState_desc']) || isset($_GET['searchnot_campaignState_desc']) || isset($_GET['filter_campaignState_desc'])) {
															// filter indicator
															?><i class='material-icons fop-small'>filter_list</i><?php
														}
														// search indicator
														?><i class='material-icons fop-small'>search</i>
													</span>
												<div class='fop-column-handle'></div>
											</div><?php
											$columns['desc']['header'] = ob_get_contents(); ob_end_clean();
											$columns['desc']['render'] = function ($item) use (&$columns, $itemheight) {
												// Render-Callback für eine Zelle
												?><div class='fop-table-column'
													style='width: <?php echo intval($columns['desc']['width']); ?>px; <?php if ($columns['desc']['collapsed'] == 1) { echo ' display: none;'; } ?> height: <?php echo $itemheight; ?>px; ' data-column='desc'><span class='overflow-text' title="<?php echo htmlentities($item['desc']); ?>"><?php echo htmlentities($item['desc']); ?></span></div><?php
											};
											$columns['desc']['renderSum'] = function ($item) use (&$columns) {
												// Render-Callback Summe
												?><div class='fop-table-column fop-table-column-aggregate'
													data-column='desc'
													data-order='<?php echo intval($columns['desc']['order']); ?>'
													data-width='<?php echo intval($columns['desc']['width']); ?>'
													data-collapsed='<?php echo intval($columns['desc']['collapsed']); ?>'
													style='width: <?php echo intval($columns['desc']['width']); ?>px; <?php if ($columns['desc']['collapsed'] == 1) { echo ' display: none;'; } ?>'>
													</div><?php
											};
										}
										
									
										
										if(true){
											ob_start();
											?><div class="fop-table-column overlay"
												data-column='aftercontact'
												data-order='<?php echo intval($columns['aftercontact']['order']); ?>'
												data-width='<?php echo intval($columns['aftercontact']['width']); ?>'
												data-collapsed='<?php echo intval($columns['aftercontact']['collapsed']); ?>'
												style='width: <?php echo intval($columns['aftercontact']['width']); ?>px; <?php if ($columns['aftercontact']['collapsed'] == 1) { echo ' display: none;'; } ?>'>
												<span class='title' onclick="
		var changed = false, win = dropDownFixPosition($(this), null, function() { if (changed) {
			
			reloadcampaignState(); 
		}});
		
		win.append(getfilter_campaignState_aftercontactListMultiFilter()); win.find('input').first().focus();
		return false;
	">
													<span class='title-title' title='<?php echo(_('Status nach Kontaktierung')); ?>'><?php echo(_('Status nach Kontaktierung')); ?></span>
													<?php // sort indicator
														if (isset($_GET['sort_campaignState']) && $_GET['sort_campaignState'] == 'aftercontact ASC') {
															?><i class='material-icons fop-small'>keyboard_arrow_down</i><?php
														} else if (isset($_GET['sort_campaignState']) && $_GET['sort_campaignState'] == 'aftercontact DESC') {
															?><i class='material-icons fop-small'>keyboard_arrow_up</i><?php
														}
														if (isset($_GET['range_min_campaignState_aftercontact']) || isset($_GET['range_max_campaignState_aftercontact']) || isset($_GET['deps_campaignState_aftercontact']) || isset($_GET['fullsearch_campaignState_aftercontact']) || isset($_GET['dynamic_campaignState_aftercontact']) || isset($_GET['search_campaignState_aftercontact']) || isset($_GET['searchnot_campaignState_aftercontact']) || isset($_GET['filter_campaignState_aftercontact'])) {
															// filter indicator
															?><i class='material-icons fop-small'>filter_list</i><?php
														}
														// search indicator
														?><i class='material-icons fop-small'>search</i>
													</span>
												<div class='fop-column-handle'></div>
											</div><?php
											$columns['aftercontact']['header'] = ob_get_contents(); ob_end_clean();
											$columns['aftercontact']['render'] = function ($item) use (&$columns, $itemheight) {
												// Render-Callback für eine Zelle
												?><div class='fop-table-column'
													style='width: <?php echo intval($columns['aftercontact']['width']); ?>px; <?php if ($columns['aftercontact']['collapsed'] == 1) { echo ' display: none;'; } ?> height: <?php echo $itemheight; ?>px; ' data-column='aftercontact'><?php
	
	call_user_func(function () use ($item) {
	$id = $item['aftercontact'];
	$val = $item['aftercontact::description'];
	$canView = $item['aftercontact::canView'];
	if ($val !== null) {
		echo htmlentities($val);
	} else {
		echo htmlentities(_('nichts versenden') ?: '-');
	}
	});
	
?>
</div><?php
											};
											$columns['aftercontact']['renderSum'] = function ($item) use (&$columns) {
												// Render-Callback Summe
												?><div class='fop-table-column fop-table-column-aggregate'
													data-column='aftercontact'
													data-order='<?php echo intval($columns['aftercontact']['order']); ?>'
													data-width='<?php echo intval($columns['aftercontact']['width']); ?>'
													data-collapsed='<?php echo intval($columns['aftercontact']['collapsed']); ?>'
													style='width: <?php echo intval($columns['aftercontact']['width']); ?>px; <?php if ($columns['aftercontact']['collapsed'] == 1) { echo ' display: none;'; } ?>'>
													</div><?php
											};
										}
										
									
										
										if(true){
											ob_start();
											?><div class="fop-table-column overlay"
												data-column='endstate'
												data-order='<?php echo intval($columns['endstate']['order']); ?>'
												data-width='<?php echo intval($columns['endstate']['width']); ?>'
												data-collapsed='<?php echo intval($columns['endstate']['collapsed']); ?>'
												style='width: <?php echo intval($columns['endstate']['width']); ?>px; <?php if ($columns['endstate']['collapsed'] == 1) { echo ' display: none;'; } ?>'>
												<span class='title' onclick="
		var changed = false, win = dropDownFixPosition($(this), null, function() { if (changed) {
			
			reloadcampaignState(); 
		}});
		win
	.append($('<input type=\'checkbox\'' + (querySet('filter_campaignState_endstate', '0') ? ' checked>': '>')).change(function (){querySet('filter_campaignState_endstate', '0', $(this).prop('checked')); delete query['page_campaignState']; changed=true;})).append(' <?php echo(_('off')); ?><br/>')
	.append($('<input type=\'checkbox\'' + (querySet('filter_campaignState_endstate', '1') ? ' checked>': '>')).change(function (){querySet('filter_campaignState_endstate', '1', $(this).prop('checked')); delete query['page_campaignState']; changed=true;})).append(' <?php echo(_('on')); ?><br/>')
;
		return false;
	">
													<span class='title-title' title='<?php echo(_('Endzustand')); ?>'><?php echo(_('Endzustand')); ?></span>
													<?php // sort indicator
														if (isset($_GET['sort_campaignState']) && $_GET['sort_campaignState'] == 'endstate ASC') {
															?><i class='material-icons fop-small'>keyboard_arrow_down</i><?php
														} else if (isset($_GET['sort_campaignState']) && $_GET['sort_campaignState'] == 'endstate DESC') {
															?><i class='material-icons fop-small'>keyboard_arrow_up</i><?php
														}
														if (isset($_GET['range_min_campaignState_endstate']) || isset($_GET['range_max_campaignState_endstate']) || isset($_GET['deps_campaignState_endstate']) || isset($_GET['fullsearch_campaignState_endstate']) || isset($_GET['dynamic_campaignState_endstate']) || isset($_GET['search_campaignState_endstate']) || isset($_GET['searchnot_campaignState_endstate']) || isset($_GET['filter_campaignState_endstate'])) {
															// filter indicator
															?><i class='material-icons fop-small'>filter_list</i><?php
														}
														// search indicator
														?><i class='material-icons fop-small'>search</i>
													</span>
												<div class='fop-column-handle'></div>
											</div><?php
											$columns['endstate']['header'] = ob_get_contents(); ob_end_clean();
											$columns['endstate']['render'] = function ($item) use (&$columns, $itemheight) {
												// Render-Callback für eine Zelle
												?><div class='fop-table-column'
													style='width: <?php echo intval($columns['endstate']['width']); ?>px; <?php if ($columns['endstate']['collapsed'] == 1) { echo ' display: none;'; } ?> height: <?php echo $itemheight; ?>px; ' data-column='endstate'><?php if($item['endstate'] == 1){ ?>✓<?php }else{ ?><?php }?></div><?php
											};
											$columns['endstate']['renderSum'] = function ($item) use (&$columns) {
												// Render-Callback Summe
												?><div class='fop-table-column fop-table-column-aggregate'
													data-column='endstate'
													data-order='<?php echo intval($columns['endstate']['order']); ?>'
													data-width='<?php echo intval($columns['endstate']['width']); ?>'
													data-collapsed='<?php echo intval($columns['endstate']['collapsed']); ?>'
													style='width: <?php echo intval($columns['endstate']['width']); ?>px; <?php if ($columns['endstate']['collapsed'] == 1) { echo ' display: none;'; } ?>'>
													</div><?php
											};
										}
										
									
										
										if(true){
											ob_start();
											?><div class="fop-table-column overlay"
												data-column='color'
												data-order='<?php echo intval($columns['color']['order']); ?>'
												data-width='<?php echo intval($columns['color']['width']); ?>'
												data-collapsed='<?php echo intval($columns['color']['collapsed']); ?>'
												style='width: <?php echo intval($columns['color']['width']); ?>px; <?php if ($columns['color']['collapsed'] == 1) { echo ' display: none;'; } ?>'>
												<span class='title' onclick="
		var changed = false, win = dropDownFixPosition($(this), null, function() { if (changed) {
			
			reloadcampaignState(); 
		}});
		
		var el = $('<div class=\'mdl-textfield mdl-js-textfield mdl-textfield--floating-label fop-floatsorter\' style=\'width: calc(100% - 42px);\'><input class=\'mdl-textfield__input\' style=\'display: inline-block;\' type=\'text\'><label class=\'mdl-textfield__input\'><?php echo(_('search')); ?></label></div>');
		win.append(el);
		var text = el.find('input');
		text.val(query['search_campaignState_color'])
		text.on('change keyup paste', function () { if (text.val()) { query['search_campaignState_color'] = text.val(); } else { delete query['search_campaignState_color']; } changed = true; });
		text.focus();
		text.select();
		text.keydown(function (event) {if ((event.keyCode || event.which) == 13) {$('#table_campaignState').find('.fop-table-row:first').click();} if (event.key === 'Escape') { win.close(); }});

		var el2 = $('<div class=\'mdl-textfield mdl-js-textfield mdl-textfield--floating-label\'><input class=\'mdl-textfield__input\' style=\'display: inline-block;\' type=\'text\'><label class=\'mdl-textfield__input\'><?php echo(htmlentities(htmlentities(_('filter_contains_not')))); ?></label></div>');
		win.append(el2);
		var text2 = el2.find('input');
		text2.val(query['searchnot_campaignState_color'])
		text2.on('change keyup paste', function () { if (text2.val()) { query['searchnot_campaignState_color'] = text2.val(); } else { delete query['searchnot_campaignState_color']; } changed = true; });
		text2.keydown(function (event) {if ((event.keyCode || event.which) == 13) {$('#table_campaignState').find('.fop-table-row:first').click();} if (event.key === 'Escape') { win.close(); }});
	
	var icon, sortbtn	= $('<a class=\'mdl-button mdl-js-button mdl-button--icon mdl-button--colored\' style=\'display: inline-block;\'></a>')
		.append(icon = $('<i class=\'material-icons\'></i>').text('unfold_more'))
		.click(function() {
		 if (query['sort_campaignState'] == 'color ASC') {
			query['sort_campaignState'] = 'color DESC';
		 } else if (query['sort_campaignState'] == 'color DESC') {
		 	delete query['sort_campaignState'];
		 } else {
			query['sort_campaignState'] = 'color ASC';
		 }
		 reloadcampaignState();
		 return false;
	});
	if (win.children().first().hasClass('fop-floatsorter')) {
		// floating layout
		win.prepend(sortbtn.css({float: 'right', margin: '0px'}));
	} else {
		// append to the end
		win.append(sortbtn);
	}
		return false;
	">
													<span class='title-title' title='<?php echo(_('Farbe')); ?>'><?php echo(_('Farbe')); ?></span>
													<?php // sort indicator
														if (isset($_GET['sort_campaignState']) && $_GET['sort_campaignState'] == 'color ASC') {
															?><i class='material-icons fop-small'>keyboard_arrow_down</i><?php
														} else if (isset($_GET['sort_campaignState']) && $_GET['sort_campaignState'] == 'color DESC') {
															?><i class='material-icons fop-small'>keyboard_arrow_up</i><?php
														}
														if (isset($_GET['range_min_campaignState_color']) || isset($_GET['range_max_campaignState_color']) || isset($_GET['deps_campaignState_color']) || isset($_GET['fullsearch_campaignState_color']) || isset($_GET['dynamic_campaignState_color']) || isset($_GET['search_campaignState_color']) || isset($_GET['searchnot_campaignState_color']) || isset($_GET['filter_campaignState_color'])) {
															// filter indicator
															?><i class='material-icons fop-small'>filter_list</i><?php
														}
														// search indicator
														?><i class='material-icons fop-small'>search</i>
													</span>
												<div class='fop-column-handle'></div>
											</div><?php
											$columns['color']['header'] = ob_get_contents(); ob_end_clean();
											$columns['color']['render'] = function ($item) use (&$columns, $itemheight) {
												// Render-Callback für eine Zelle
												?><div class='fop-table-column'
													style='width: <?php echo intval($columns['color']['width']); ?>px; <?php if ($columns['color']['collapsed'] == 1) { echo ' display: none;'; } ?> height: <?php echo $itemheight; ?>px; ' data-column='color'><div style='display: inline-block; width: 32px; height: 1em; background-color: <?php echo ($item['color']) ? htmlentities($item['color']) : 'none'; ?>;'></div>&nbsp; <?php echo(htmlentities($item['color'])) ?></span></div><?php
											};
											$columns['color']['renderSum'] = function ($item) use (&$columns) {
												// Render-Callback Summe
												?><div class='fop-table-column fop-table-column-aggregate'
													data-column='color'
													data-order='<?php echo intval($columns['color']['order']); ?>'
													data-width='<?php echo intval($columns['color']['width']); ?>'
													data-collapsed='<?php echo intval($columns['color']['collapsed']); ?>'
													style='width: <?php echo intval($columns['color']['width']); ?>px; <?php if ($columns['color']['collapsed'] == 1) { echo ' display: none;'; } ?>'>
													</div><?php
											};
										}
										
									

									// sort by order
									uasort($columns, function ($a, $b) {
										return $a['order'] - $b['order'];
									});
									?>
									<style type='text/css'>
										#campaignState-table .fop-table-header {
											height: <?php echo 32; ?>px;
										}
										#campaignState-table .fop-table-header .fop-table-column .title,
										#campaignState-table .fop-column-handle,
										#campaignState-table .fop-table-row,
										#campaignState-table .fop-table-row .fop-table-column,
										#campaignState-table .fop-table-column-multicontrol,
										#campaignState-table .fop-filter-button {
											height: 32px;
											line-height: 32px;
										}
										</style>
											<div class="fop-table" data-table-id="campaignState">
											<div class="fop-legend"></div>
											<div class="fop-filter-string-wrapper"><div class="fop-filter-string"><label>Filter:</label> <span><?php echo self::getFilterHTML($_GET); ?></span></div></div>
											
											<?php if (isset($_GET['select'])) { echo '<br>'; } ?>
											<div class="fop-table-header">
											<?php if (!isset($_GET['select'])) { ?>
												<div class="fop-table-column noprint" style="width: <?php echo json_encode($firstColumnWidth); ?>px;">
													
													<div class="fop-table-column-multicontrol">
													<label class="mdl-checkbox mdl-js-checkbox"  style='width: auto;' for="campaignState__all-checkbox">
														<input class="mdl-checkbox__input" id="campaignState__all-checkbox" type="checkbox" onchange="checkcampaignState('all', 'ID', this.checked);">
														</label>
														<button type="button" class="mdl-button mdl-js-button mdl-button--icon campaignState__mass-action" style='visibility: hidden;' onclick="$.get('DataView/CampaignState/permissions?id=' + checkcampaignState(null, 'ID'), function (data) { for (var method in data) if (method != '__cnt') { var btn = $('[data-interaction-name=&quot;' + method + '&quot;]'); if (data[method] >= 1) btn.show(); else btn.hide(); btn.find('.cnt').text(data[method]); }; }); dropDownFixPosition($(this), $(this).next())">
															<i class="material-icons">more_vert</i>
														</button>
														<ul class="mdl-list mdl-card mdl-shadow--4dp fop-scroll-menu">
															<?php
		if(true) { ?>
			<span class="mdl-list__item mdl-button">
				<span class="mdl-list__item mdl-button" data-interaction-name="filterall" style="margin-right:auto; text-align:left;"
					onclick="for (key in query) if (key.indexOf('range_min_campaignState_') == 0 || key.indexOf('range_max_campaignState_') == 0 || key.indexOf('deps_campaignState_') == 0 || key.indexOf('fullsearch_campaignState_') == 0 || key.indexOf('dynamic_campaignState_') == 0 || key.indexOf('search_campaignState_') == 0 || key.indexOf('searchnot_campaignState_') == 0 || key.indexOf('filter_campaignState_') == 0) delete query[key]; reloadcampaignState(); $(this).closest('.overlay').click(); return false;">
					<span style="float:left;"><i class="material-icons">list</i></span><span class="fop-menu-caption" title="<?php echo(_('view all elements')); ?>"><?php echo(_('view all elements')); ?> 
					</span>
				</span>
			</span>
		<?php } ?><?php
		if(true) { ?>
			<span class="mdl-list__item mdl-button">
				<span class="mdl-list__item mdl-button" data-interaction-name="filteronly" style="margin-right:auto; text-align:left;"
					onclick="query['filter_campaignState_ID'] = checkcampaignState(null, 'ID'); delete query['page_campaignState']; reloadcampaignState(); $(this).closest('.overlay').click(); return false;">
					<span style="float:left;"><i class="material-icons">arrow_forward</i></span><span class="fop-menu-caption" title="<?php echo(_('view only these elements')); ?>"><?php echo(_('view only these elements')); ?> (<span class='cnt'></span>)
					</span>
				</span>
			</span>
		<?php } ?><?php
		if(true) { ?>
			<span class="mdl-list__item mdl-button">
				<span class="mdl-list__item mdl-button" data-interaction-name="filterrange" style="margin-right:auto; text-align:left;"
					onclick="
		var ticks = new IDList(checkcampaignState(null, 'ID'));
		var range = prompt('Bitte geben Sie den Bereich ein', '1-' + ticks.count());
		var newticks = new IDList();
		if (range) {
			range = range.split('-');
			if (range.length == 1) {
				range.push(range[0]);
			}
			var skip = (range[0] || 1) - 1;
			var take = (range[1] || Infinity) - skip;
			for (var item of ticks.all()) {
				if (skip > 0) {
					skip--;
				} else if (take > 0) {
					newticks.push(item);
					take--;
				} else break;
			}
			checkcampaignState(newticks, 'ID', 'set');
		} $(this).closest('.overlay').click(); return false;">
					<span style="float:left;"><i class="material-icons">colorize</i></span><span class="fop-menu-caption" title="<?php echo(_('limit range')); ?>"><?php echo(_('limit range')); ?> (<span class='cnt'></span>)
					</span>
				</span>
			</span>
		<?php } ?><?php
		if(true && ((\FOP\User::getCampaign()))) { ?>
			<span class="mdl-list__item mdl-button">
				<span class="mdl-list__item mdl-button" data-interaction-name="delete" style="margin-right:auto; text-align:left;"
					onclick="if(!confirm(<?php echo htmlentities(json_encode(_('confirmdelete'))); ?>)) return;$.get('Tables/CampaignState/delete?ajax&from=<?php echo urlencode(\FOP\Util::getBackUrl()); ?>&id=' + escape(checkcampaignState(null, 'ID'))).then(function () { reloadcampaignState(); }, function (err) { if (err.responseText.startsWith('http')) { window.location.href = err.responseText; } else {alert(err.responseText); }}); $(this).closest('.overlay').click(); return false;">
					<span style="float:left;"><i class="material-icons">delete</i></span><span class="fop-menu-caption" title="<?php echo(_('delete')); ?>"><?php echo(_('delete')); ?> (<span class='cnt'></span>)
					</span>
				</span>
			</span>
		<?php } ?>
														</ul>
														<!-- column hide -->
														<button type="button" class="mdl-button mdl-js-button mdl-button--icon" onclick="dropDownFixPosition($(this), $(this).next())">
															<i class="material-icons">visibility</i>
														</button>
														<ul class="mdl-list mdl-card mdl-shadow--4dp fop-scroll-menu">
															<?php foreach ($columns AS $col) { ?>
																<li class="mdl-list__item mdl-button" onclick="
																	var isVisible = this.firstElementChild.innerText !== 'clear';
																	this.firstElementChild.innerText = isVisible ? 'clear' : 'visibility'; // switch icon
																	tableColumnVisibility('campaignState', <?php echo htmlentities(json_encode($col['id'])); ?>, !isVisible); // the rest is up to a helper function in layout/tables.fop
																	">
																	<i class="material-icons"><?php if ($col['collapsed']) { echo 'clear'; } else { echo 'visibility'; }?></i>
																	<?php echo htmlentities($col['desc']); ?>
																</li>
															<?php } ?>
															<li class="mdl-list__item mdl-button" onclick="
																$.get('FOP/Index/dataview?data='+encodeURIComponent(JSON.stringify({dataview: 'campaignState', reset: true}))).then(function () { location.reload(); });
																">
																<i class="material-icons">refresh</i>
																<?php echo _('reset all'); ?>
															</li>
														</ul>
													</div>
												</div><?php }
												
												foreach ($columns AS $col) {
													// Spalten-Überschrift rendern
													echo $col['header'];
												} ?>
											 </div>
											
											<div class="fop-table-body" id="table_campaignState" <?php \EasyEditor\Navigation::printScroll('dv.CampaignState', '/* scroll horiz */ this.previousElementSibling.firstElementChild.style.marginLeft = \'-\' + this.scrollLeft + \'px\';
												/* scroll verti */
												var self = this;
												if (window.DataViewScrollReloadTimeout) clearTimeout(window.DataViewScrollReloadTimeout);
												window.DataViewScrollReloadTimeout = setTimeout(function () {
													var currentPage = parseInt(query[\'page_campaignState\'] || 0);
													var paddingTop = parseInt( self.lastElementChild.style.paddingTop, 10);
													var wantedPage = Math.max(0, currentPage + Math.floor((self.scrollTop - paddingTop) / ' . ($itemheight * $itemsperpage) . '));
													if (wantedPage != currentPage) {
														query[\'page_campaignState\'] = wantedPage;
														reloadcampaignState(undefined, undefined, true);
													}
												}, 50);
											'); ?>>
												<div class="fop-table-body-inner" style="min-height: <?php echo 12 + $itemheight * ($itemcount + $additionalLines); ?>px; padding-top: <?php echo $itemheight * $itemsperpage * $page; ?>px;">
												<?php foreach($arr as $itempos => $item) {
													?>
													<div class="fop-table-row" style=""data-itempos="<?php echo htmlentities($item['order']); ?>" data-campaignState-id="<?php echo htmlentities($item['ID']); ?>">

													<?php if (!isset($_GET['select'])) { ?>
													<div class='fop-table-column noprint' style="width: <?php echo json_encode($firstColumnWidth); ?>px;" onclick="$(this).find('input[type=checkbox]').first().click(); event.stopPropagation();">
													<label onclick="event.stopPropagation();" class="mdl-checkbox mdl-js-checkbox campaignState__checkbox campaignState__checkbox campaignState__checkbox-ID-<?php echo htmlentities($item['ID']); ?>" style="width: auto;" for="campaignState__<?php echo htmlentities($itempos); ?>-checkbox">
													<input class="mdl-checkbox__input" id="campaignState__<?php echo htmlentities($itempos); ?>-checkbox" type="checkbox" onchange="<?php if (isset($item['ID'])) echo 'checkcampaignState(' . htmlentities(json_encode($item['ID'])) . ', \'ID\', this.checked); ' ?>">
													</label><?php if(!isset($item['canSort']) || $item['canSort']) {
														?><a title="<?php echo htmlentities(_('sort')); ?>" class="sorthandle mdl-button mdl-js-button mdl-button--icon" onclick="event.stopPropagation();"><i class="material-icons">swap_vert</i></a><?php
													} ?><button type="button" class="mdl-button mdl-js-button mdl-button--icon campaignState__action" onclick="
														event.stopPropagation();
														dropDownFixPosition($(this), $(this).next());
														">
														<i class="material-icons">more_vert</i>
													</button><ul class="mdl-list mdl-card mdl-shadow--4dp fop-scroll-menu" id="fop-scroll-menu-campaignState-action-<?php echo $item['ID'] ?? 0; ?>">
														<?php
		if(isset($item['ID']) && $item['operation::view'] && $item['operation::edit']) { ?>
			<a class="mdl-list__item mdl-button" data-interaction-name="edit" style="margin-right:auto; text-align:left;" href="<?php echo htmlentities(\TablesRouter\CampaignState::editURL($item['ID'], ['from' => \FOP\Util::getBackUrl()])); ?>"
				onclick="   
					open_url(this.href, false);
					$(this).closest('.overlay').click();
					return false;">
				<span><i class="material-icons">edit</i></span><span class="fop-menu-caption" title="<?php echo(_('edit')); ?>"><?php echo(_('edit')); ?></span>
			</a>
		<?php } ?><?php
		if(isset($item['ID']) && $item['operation::delete']) { ?>
			<a class="mdl-list__item mdl-button" data-interaction-name="delete" style="margin-right:auto; text-align:left;" href="#"
				onclick="if(!confirm(<?php echo htmlentities(json_encode(_('confirmdelete'))); ?>)) return false;   $.get('Tables/CampaignState/delete?ajax&id=<?php echo htmlentities($item['ID']);?>&from=<?php echo htmlentities(\FOP\Util::getBackUrl());?>').then(function () { reloadcampaignState(); }, function (err) { if (err.responseText.startsWith('http')) { window.location.href = err.responseText; } else {alert(err.responseText); }}); $(this).closest('.overlay').click(); return false;
					open_url(this.href, false);
					$(this).closest('.overlay').click();
					return false;">
				<span><i class="material-icons">delete</i></span><span class="fop-menu-caption" title="<?php echo(_('delete')); ?>"><?php echo(_('delete')); ?></span>
			</a>
		<?php } ?>
													</ul><?php
		if(isset($item['ID']) && $item['operation::view'] && $item['operation::edit']) {
			?><a class="mdl-button mdl-js-button mdl-button--icon tbl-link" data-tbl="campaignState" data-id="<?php echo htmlentities($item['ID']); ?>" data-interaction-name="edit" href="<?php echo htmlentities(\TablesRouter\CampaignState::editURL($item['ID'], ['from' => \FOP\Util::getBackUrl()])); ?>"
				onclick="event.stopPropagation();    reloadcampaignState();
					$(this).closest('.overlay').click();
					if (this.href != '#') {
						open_url(this.href, false);
					}
					event.preventDefault();"
				title="<?php echo(_('edit')); ?>">
				<i class="material-icons">edit</i>
			</a><?php } ?>
													</div><?php } ?><?php
													
													foreach ($columns AS $col) {
														$col['render']($item);
													}
													?></div>
												 <?php }?>

													</div>
												</div>

												
												
												<script src='js/jquery.ui.touch-punch.min.js'></script>
												<script type="text/javascript">
												$(function(){
													$("#table_campaignState .fop-table-body-inner").sortable({
														'cursor': 'move',
														'handle': '.sorthandle',
														'start': function (event, ui) {
														},
														'update': function (event, ui) {
															var newids = $("#table_campaignState .fop-table-body-inner").sortable("toArray", {"attribute": "data-campaignState-id"});
															var positions = $("#table_campaignState .fop-table-body-inner").sortable("toArray", {"attribute": "data-itempos"}).map(function (x) {
																if (!x || x == 0) {
																	// nullen sanitizen
																	x = Math.round(Math.random() * 2000000) + 100;
																}
																return x;
															});
															positions.sort(function (a, b) {
																return Number(a) - Number(b);
															}); // sortieren, damit die neue Reihenfolge funzt
															var changedpos = {};
															for(var i = 0; i < newids.length; i++){
																changedpos[newids[i]] = positions[i]; 
															}
															
															$.get(reloadcampaignState({action: "sort", data: JSON.stringify(changedpos)}, true), function(response){
																// OK
															});
														}
													});
												});
												</script>
												
												</div><?php
												
	
    
  }

  public static function getidsAction($col) { 
    
    
    // --- BLOCK: access ---
    
    // --- BLOCK: main ---
    
			$q = \FOP\Database::query('SELECT t.'.qi($col).' '.self::getSQL($_GET));
			$result = new \FOP\IDList();
			while ($item = $q->fetchColumn()) {
				$result->push($item);
			}
			die($result->toString());

    
  }

  public static function permissionsAction($id) { 
    
    
    // --- BLOCK: access ---
    
    // --- BLOCK: main ---
    
		$ids = new \FOP\IDList($id);
		header('Content-Type: application/json');
		
		$perms = \FOP\Database::query('SELECT COUNT(*) AS __cnt, SUM(CASE (TRUE) WHEN TRUE THEN 1 ELSE 0 END) AS '.qi('filteronly').', SUM(CASE (TRUE) WHEN TRUE THEN 1 ELSE 0 END) AS '.qi('filterrange').', SUM(CASE (TRUE) WHEN TRUE THEN 1 ELSE 0 END) AS '.qi('filterall').', SUM(CASE (('.\FOP\Database::quote(\FOP\User::getCampaign()).')) WHEN TRUE THEN 1 ELSE 0 END) AS '.qi('delete').' FROM '.qi('campaignState').' WHERE ' . $ids->toSQL(qi('ID')))->fetch(\PDO::FETCH_ASSOC);
		
		return $perms;
	
    
  }

  public static function sortAction($data) { 
    
    
    // --- BLOCK: access ---
    if(!(((\FOP\User::getCampaign())) && (!\FOP\User::getIsGuest()))) throw new \FOP\AccessDeniedException();
    // --- BLOCK: main ---
    
		if ($data == '*') {
			// Position aus sord_campaignState ziehen
			$q = self::getData(' LIMIT 1024', $_GET, true);
			$order = 1;
			$s = [];
			foreach ($q AS $item) {
				array_push($s, 'WHEN ' . intval($item['ID']) . ' THEN ' . intval($order++));
			}
		} else {
			// Position von Elementen als JSON aus $data ziehen
			$newpos = json_decode($data, true);

			$s = array_map(function($value, $key){
				return 'WHEN ' . intval($key) . ' THEN ' . intval($value);
			}, array_values($newpos), array_keys($newpos));
		}

		// Zugriffsregel: sort
		$sql = 'UPDATE '.qi('campaignState').' SET '.qi('order').' = (CASE '.qi('ID').' ' . implode(' ', $s) . ' ELSE '.qi('order').' END) WHERE ('.(\FOP\User::getIsGuest() ? 'false' : 'true').')';

		\FOP\Database::query($sql);

		
	
    
  }

  public static function getSQL($params) { 
    
    
    // --- BLOCK: dependency-campaignState ---
    
		if (isset($params['select']) && $params['select'] == 'campaignState') {
			$deps = [];
		}
	
    // --- BLOCK: dependency-campaignStateNull ---
    
		if (isset($params['select']) && $params['select'] == 'campaignStateNull') {
			$deps = [];
		}
	
    // --- BLOCK: main ---
    
								// returns a sql snippet 'FROM (...) AS t WHERE' where you can prepend your select clauses and append your ORDER LIMIT
								$sql = 'FROM (SELECT /* ID */ '.qi('ID').' AS '.qi('ID').',
									/* aftercontact */ '.qi('aftercontact').' AS '.qi('aftercontact').',
									/* aftercontact::canView */ '.qi('ref:aftercontact').'.'.qi('aftercontact:canView').' AS '.qi('aftercontact::canView').',
									/* aftercontact::description */ '.qi('ref:aftercontact').'.'.qi('aftercontact:description').' AS '.qi('aftercontact::description').',
									/* canSort */ '.(\FOP\User::getIsGuest() ? 'false' : 'true').' AS '.qi('canSort').',
									/* color */ '.qi('color').' AS '.qi('color').',
									/* desc */ '.qi('desc').' AS '.qi('desc').',
									/* endstate */ '.qi('endstate').' AS '.qi('endstate').',
									/* operation::create */ ('.\FOP\Database::quote(\FOP\User::getCampaign()).') AS '.qi('operation::create').',
									/* operation::delete */ ('.\FOP\Database::quote(\FOP\User::getCampaign()).') AS '.qi('operation::delete').',
									/* operation::edit */ ('.\FOP\Database::quote(\FOP\User::getCampaign()).') AS '.qi('operation::edit').',
									/* operation::index */ ' . (!\FOP\User::getIsGuest() ? 1 : 0) . ' AS '.qi('operation::index').',
									/* operation::view */ ('.\FOP\Database::quote(\FOP\User::getCampaign()).') AS '.qi('operation::view').',
									/* order */ '.qi('order').' AS '.qi('order').',
									1
								FROM '.qi('campaignState').' '.qi('campaignState').'
								LEFT JOIN (SELECT '.qi('ID').' AS '.qi('aftercontact:ID').', '.qi('campaignState').'.'.qi('desc').' AS '.qi('aftercontact:description').', (('.\FOP\Database::quote(\FOP\User::getCampaign()).')) AS '.qi('aftercontact:canView').' FROM '.qi('campaignState').') '.qi('ref:aftercontact').' ON '.qi('ref:aftercontact').'.'.qi('aftercontact:ID').' = '.qi('aftercontact').'
								WHERE ((('.\FOP\Database::quote(\FOP\User::getCampaign()).')))
									AND (' . (isset($_GET['select']) && $_GET['select'] == 'campaignState' ? 'TRUE' : 'TRUE') . ')
									AND (' . (isset($_GET['select']) && $_GET['select'] == 'campaignStateNull' ? 'TRUE' : 'TRUE') . ')) AS t
								WHERE ' . (isset($params['filter_campaignState_desc']) ? ($params['filter_campaignState_desc'] !== '' ? ('(' . (new \FOP\IDList($params['filter_campaignState_desc']))->toSQL('t.'.qi('desc').'') . ') AND ') : '') : '') . 
								(isset($params['filter_campaignState_aftercontact']) ? ($params['filter_campaignState_aftercontact'] !== '' ? ('(' . (new \FOP\IDList($params['filter_campaignState_aftercontact']))->toSQL('t.'.qi('aftercontact').'') . ') AND ') : '') : '') . 
								(isset($params['filter_campaignState_endstate']) ? ($params['filter_campaignState_endstate'] !== '' ? ('(' . (new \FOP\IDList($params['filter_campaignState_endstate']))->toSQL('t.'.qi('endstate').'') . ') AND ') : '') : '') . 
								(isset($params['filter_campaignState_color']) ? ($params['filter_campaignState_color'] !== '' ? ('(' . (new \FOP\IDList($params['filter_campaignState_color']))->toSQL('t.'.qi('color').'') . ') AND ') : '') : '') . 
								(isset($params['filter_campaignState_ID']) ? ($params['filter_campaignState_ID'] !== '' ? ('(' . (new \FOP\IDList($params['filter_campaignState_ID']))->toSQL('t.'.qi('ID').'') . ') AND ') : '') : '') . 
								(isset($params['search_campaignState_desc']) ? 't.'.qi('desc').' '.(\FOP\Database::getDriver() == 'pgsql' ? 'ILIKE' : 'LIKE').' ' . \FOP\Database::quote('%' . $params['search_campaignState_desc'] . '%') . ' AND ' : '') . 
								(isset($params['search_campaignState_color']) ? 't.'.qi('color').' '.(\FOP\Database::getDriver() == 'pgsql' ? 'ILIKE' : 'LIKE').' ' . \FOP\Database::quote('%' . $params['search_campaignState_color'] . '%') . ' AND ' : '') . 
								(isset($params['searchnot_campaignState_desc']) ? 'NOT t.'.qi('desc').' '.(\FOP\Database::getDriver() == 'pgsql' ? 'ILIKE' : 'LIKE').' ' . \FOP\Database::quote('%' . $params['searchnot_campaignState_desc'] . '%') . ' AND ' : '') . 
								(isset($params['searchnot_campaignState_color']) ? 'NOT t.'.qi('color').' '.(\FOP\Database::getDriver() == 'pgsql' ? 'ILIKE' : 'LIKE').' ' . \FOP\Database::quote('%' . $params['searchnot_campaignState_color'] . '%') . ' AND ' : '') . 
								(isset($params['search_campaignState']) ? '(' . 't.'.qi('desc').' '.(\FOP\Database::getDriver() == 'pgsql' ? 'ILIKE' : 'LIKE').' ' . \FOP\Database::quote('%' . $params['search_campaignState'] . '%') . ' OR ' . 't.'.qi('color').' '.(\FOP\Database::getDriver() == 'pgsql' ? 'ILIKE' : 'LIKE').' ' . \FOP\Database::quote('%' . $params['search_campaignState'] . '%') . ') AND ' : '') . 
								'
								 TRUE ';
								return $sql;
	
    
  }

  public static function getfilter_campaignState_aftercontactItemsByStringAction($fstr) { 
    
    
    // --- BLOCK: access ---
    
    // --- BLOCK: main ---
    
		// Auf aktive DataView-Items einschränken
		$params = $_GET;
		unset($params['filter_campaignState_aftercontact']);
		return \Types\CampaignStateNull::getItems(null, -1, $fstr, ''.qi('ID').' IN (SELECT DISTINCT t.'.qi('aftercontact').''.self::getSQL($params).')');
	

    
  }

  public static function getData($sqladdon, $params, $stream = false ) { 
    
    
    // --- BLOCK: main ---
    
								$sql = self::getSQL($params);

								$order = (\FOP\Util::array_value(array(
									'color ASC' => 'ORDER BY t.'.qi('color').' ASC',
									'desc ASC' => 'ORDER BY t.'.qi('desc').' ASC',
									'color DESC' => 'ORDER BY t.'.qi('color').' DESC',
									'desc DESC' => 'ORDER BY t.'.qi('desc').' DESC',
									'' => ''), isset($params['sort_campaignState']) ? $params['sort_campaignState'] : '') ?: 'ORDER BY '.qi('t').'.'.qi('order').' ');
								// wenn sqladdon bereits ein ORDER enthält, kein order aufbauen
								if (strpos($sqladdon, 'ORDER') !== false) {
									$order = '';
								}
								if ($stream) {
									// als Stream (währenddessen darf keine weitere SQL-Query laufen) für große Datenmengen und Statistiken
									$result = (function () use ($sql, $order, $sqladdon) {
										$stream = \FOP\Database::query('SELECT t.* ' . $sql . $order . $sqladdon);
										while ($item = $stream->fetch(\PDO::FETCH_ASSOC)) {
											$item['aftercontact'] = \FOP\Sanitizers::null_converter($item['aftercontact']);
											$item['endstate'] = \FOP\Util::BoolSanitizer($item['endstate']);
											
											yield $item;
										}
									})();
								} else {
									// als RAM-Array
									$result = \FOP\Database::query('SELECT t.* ' . $sql . $order . $sqladdon);
									$arr = $result->fetchAll(\PDO::FETCH_ASSOC);
									$itemcount = count($arr);

									foreach($arr as $i => &$item){
										$item['aftercontact'] = \FOP\Sanitizers::null_converter($item['aftercontact']);
										$item['endstate'] = \FOP\Util::BoolSanitizer($item['endstate']);
										
									}
									unset($item);

									$result = ["items" => $arr, "itemcount" => $itemcount];

									
								}

								return $result;
	
    
  }

  public static function getFilterHTML($params, $delimiter = ', ' , $showButton = true ) { 
    
    
    // --- BLOCK: main ---
    
		// Contract: ist showButton == false, sollten keine HTML-Tags im Output enthalten sein (Verwendung in Dateinamen!!)
		$filters = [];
		if (isset($params['filter_campaignState_desc'])) {
		if ($params['filter_campaignState_desc'] == '_null') {
			array_push($filters, _('Status') . ': ' . 'NULL');
		} else {
			$values = [];
			foreach ((new \FOP\IDList($params['filter_campaignState_desc']))->all() AS $val) {
				$value = $val;
				if ($value) array_push($values, $value);
			}
			array_push($filters, _('Status') . ': ' . implode(', ', $values));
		}
	}if (isset($params['filter_campaignState_endstate'])) {
		if ($params['filter_campaignState_endstate'] == '_null') {
			array_push($filters, _('Endzustand') . ': ' . 'NULL');
		} else {
			$values = [];
			foreach ((new \FOP\IDList($params['filter_campaignState_endstate']))->all() AS $val) {
				$value = $val;
				if ($value) array_push($values, $value);
			}
			array_push($filters, _('Endzustand') . ': ' . implode(', ', $values));
		}
	}if (isset($params['filter_campaignState_color'])) {
		if ($params['filter_campaignState_color'] == '_null') {
			array_push($filters, _('Farbe') . ': ' . 'NULL');
		} else {
			$values = [];
			foreach ((new \FOP\IDList($params['filter_campaignState_color']))->all() AS $val) {
				$value = $val;
				if ($value) array_push($values, $value);
			}
			array_push($filters, _('Farbe') . ': ' . implode(', ', $values));
		}
	}if (isset($params['filter_campaignState_aftercontact'])) {
		if ($params['filter_campaignState_aftercontact'] == '_null') {
			array_push($filters, _('Status nach Kontaktierung') . ': ' . _('nichts versenden'));
		} else {
			$values = [];
			foreach ((new \FOP\IDList($params['filter_campaignState_aftercontact']))->all() AS $val) {
				$value = 
  \FOP\Database::query('SELECT '.qi('campaignState').'.'.qi('desc').' AS description FROM '.qi('campaignState').' WHERE '.qi('ID').' = ' . \FOP\Database::quote($val))->fetchColumn() ?: _('nichts versenden')
;
				if ($value) array_push($values, $value);
			}
			array_push($filters, _('Status nach Kontaktierung') . ': ' . implode(', ', $values));
		}
	}if (isset($params['search_campaignState_desc'])) {
		array_push($filters, _('desc') . ' ' . _('filter_contains') . ' ' . $params['search_campaignState_desc']);
	}if (isset($params['search_campaignState_color'])) {
		array_push($filters, _('color') . ' ' . _('filter_contains') . ' ' . $params['search_campaignState_color']);
	}if (isset($params['searchnot_campaignState_desc'])) {
		array_push($filters, _('desc') . ' ' . _('filter_contains_not') . ' ' . $params['searchnot_campaignState_desc']);
	}if (isset($params['searchnot_campaignState_color'])) {
		array_push($filters, _('color') . ' ' . _('filter_contains_not') . ' ' . $params['searchnot_campaignState_color']);
	}
		if (isset($params['sort_campaignState']) && $showButton) {
			array_push($filters, [htmlentities(_('sort order')), ' <i class="material-icons fop-small" style="cursor: pointer;" onclick="$.get(reloadcampaignState({action: &apos;sort&apos;, data: &apos;*&apos;}, true)).then(function () { delete query[&apos;sort_campaignState&apos;]; reloadcampaignState();  });">💾</i>']);
		}
	
		if (count($filters)) {
			$result = implode($delimiter, array_map(function ($filter) {
				if (is_array($filter)) {
					return implode('', $filter);
				}
				return htmlentities($filter);
			}, $filters))
			// Button, um Filter zu entfernen
			. ($showButton ? '<i class="material-icons fop-small" style="cursor: pointer;" onclick="for (var q in query) {if (q.includes(\'_campaignState_\')) delete query[q];} reloadcampaignState(); ">clear</i>' : '');
		} else {
			$result = _('no_filter');
		}
		return $result;
	
    
  }

  public static function openAction($fop_table, $fop_id, $fop_from) { 
    
    
    // --- BLOCK: access ---
    
    // --- BLOCK: main ---
    

if ($fop_table == 'campaignState') {
	\FOP\Session::setPayload('dv-campaignState', [
		'id' => 'campaignState',
		'tbl' => 'campaignState',
		'idcol' => 'ID',
		'prev' => \DataViewRouter\CampaignState::stepURL('campaignState', 'XXX', -1),
		'next' => \DataViewRouter\CampaignState::stepURL('campaignState', 'XXX',  1),
		'from' => $fop_from
	]);
	
	if ($fop_id == '_') return; // nur Rückreferenz setzen, nicht öffnen
	$params = [];
	if (isset($_GET['popup'])) $params['popup'] = true;
	if (isset($_GET['from'])) $params['from'] = $_GET['from'];
	$params['id'] = $fop_id;
	
	$url = \TablesRouter\CampaignState::viewURL2($params);
	header('Location: ' . $url);
}

die();
    
  }

  public static function stepAction($tbl, $id, $step) { 
    
    
    // --- BLOCK: access ---
    
    // --- BLOCK: main ---
    
	$dv = \FOP\Session::getPayload('dv-'.$tbl);
	$url = $dv['from'];
	$parts = parse_url($url);
	parse_str($parts['query'], $query);
	$data = self::getData('', $query);
	$col = $dv['idcol'];
	$ids = array_map(function ($x) use ($col) {return $x[$col];}, $data['items']);
	if (!count($ids)) {
		header('Location: ' . \FOP\Util::getCurrentBaseurl() . 'Tables/' . preg_replace('/[^a-zA-Z0-9_]/', '_', ucfirst($dv['tbl'])));
		die();
	}
	$idx = array_search($id, $ids);
	$idx += count($ids) + $step;
	$idx = $idx % count($ids);
	header('Location: ' . \FOP\Util::getCurrentBaseurl() . 'Tables/' . preg_replace('/[^a-zA-Z0-9_]/', '_', ucfirst($dv['tbl'])) . '/view?id=' . urlencode($ids[$idx]));
	die();

    
  }


  
  

  
  
}



