<?php

if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
if (!defined('APP_PATH_ROOT')) define('APP_PATH_ROOT', dirname(__FILE__));
if (!defined('APP_PATH_WWW')) define('APP_PATH_WWW', dirname(__FILE__));
if (!defined('APP_PATH_CONFIG')) define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');

function TV_OFERTA_PROGRAMOWA() {

	require_once dirname(__FILE__) . '/' . 'se-lib' . '/' . 'Lib.php';
	Lib::loadClass('V');
	Lib::loadClass('User');
	Lib::loadClass('Config');
	Lib::loadClass('DB');

	$TvOfertaView = new TvOfertaView();

	$_print = V::get('_print', '', $_GET);
	if (!$_print) {
		$TvOfertaView->menu();
	}

	$task = V::get('task', 'cyfrowe', $_GET);
	if ($task == 'analog') {
		$programy = TvOfertaHelper::getProgramyAnalogowe();

		$groups = array();
		foreach ($programy as $r) {
			$groups[$r->TV_PROGRAM_PROFILE] = true;
		}

		$orderby = V::get('orderby', '', $_GET);
		$TvOfertaView->analogowe($programy, $groups, $orderby);
	}
	else {
		$pakiety_cyfrowe = TvOfertaHelper::getPakietyCyfrowe();

		$programy = TvOfertaHelper::getProgramyCyfrowe();
		$groups = array();
		foreach ($programy as $r) {
			$groups[$r->TV_PROGRAM_PROFILE] = true;
		}

		$orderby = V::get('orderby', '', $_GET);
		$view_type = V::get('view_type', '', $_GET);
		$TvOfertaView->cyfrowe($programy, $pakiety_cyfrowe, $groups, $orderby, $view_type);
	}

}

class TvOfertaView {

	// TODO: function link()

	function menu() {
		// TODO: MENU_INIT na FUNCTION_INIT i HEADER NOT INIT
		?>
		<div>
			<a href="?MENU_INIT=TV_OFERTA_PROGRAMOWA">Cyfrowe</a>
			|
			<a href="?MENU_INIT=TV_OFERTA_PROGRAMOWA&task=analog">Analogowe</a>
			<?php if ('analog' == V::get('task', '', $_GET)) : ?>
				<br />Analogowe posortowane po: 
				<a href="?MENU_INIT=TV_OFERTA_PROGRAMOWA&task=analog&orderby=group">grupach tematycznych</a>
				|
				<a href="?MENU_INIT=TV_OFERTA_PROGRAMOWA&task=analog&orderby=name">nazwie</a>
			<?php else : ?>
				<br />Cyfrowe posortowane po: 
				<a href="?MENU_INIT=TV_OFERTA_PROGRAMOWA&orderby=group">grupach tematycznych</a>
				|
				<a href="?MENU_INIT=TV_OFERTA_PROGRAMOWA&orderby=pakiety">pakietach</a>
				|
				<a href="?MENU_INIT=TV_OFERTA_PROGRAMOWA&orderby=name">nazwie</a>
			<?php endif; ?>
		</div>
		<?php
	}

	function css() {
		?>
	<style type="text/css">
/* Styles for rotateTableCellContent plugin */
#oferta-programowa-cyfrowe div.rotated {
  -webkit-transform:rotate(-90deg);
  -moz-transform:rotate(-90deg);
	-o-transform:rotate(-90deg);
  writing-mode:tb-rl;
  white-space:nowrap;
}

body{font-family:arial}

.oferta-programowa { border-collapse:collapse; border:1px solid #7EC5FF; }
.oferta-programowa td { border:1px solid #7EC5FF; }
.oferta-programowa .prog-group { color:#7A7A7A; }
.oferta-programowa .cyfrowe-prog-count {}
.oferta-programowa .p2 { padding:0 2px; }
.oferta-programowa .c { text-align:center; }
.oferta-programowa .r { text-align:right; }
.oferta-programowa .cyfrowe-prog-count td { background-color:#fff; }
.oferta-programowa .hd { background-color:#FF5F5F; color:#fff; font-weight:bold; }
.oferta-programowa .nr { color:#7A7A7A; }
.oferta-programowa thead th { border:1px solid #7EC5FF; }

#oferta-programowa-cyfrowe thead { background:none; }
#oferta-programowa-cyfrowe thead th { vertical-align:bottom; border:none; }
#oferta-programowa-cyfrowe .logo { text-align:center; background-color:#fff; border:none; }
#oferta-programowa-cyfrowe .vertical { height:30px; white-space:nowrap; line-height:30px; padding:2px 0; }

#oferta-programowa-cyfrowe .prog-pakiet-24 {background-color:#EBEBEB;} /* Biały */
#oferta-programowa-cyfrowe .prog-pakiet-25 {background-color:#B88019;} /* Brązowy */
#oferta-programowa-cyfrowe .prog-pakiet-26 {background-color:#CACACA;} /* Srebrny */
#oferta-programowa-cyfrowe .prog-pakiet-27 {background-color:#FFE554;} /* Złoty */
#oferta-programowa-cyfrowe .prog-pakiet-28 {background-color:#E7E4E4;} /* Platynowy */
#oferta-programowa-cyfrowe .prog-pakiet-8 {background-color:#94CFFF;} /* CANAL+ */
#oferta-programowa-cyfrowe .prog-pakiet-10 {background-color:#77A3FF;} /* CANAL+ HD */

#oferta-programowa-analogowe {  }

/* print table background colors */
table td, table th { -webkit-print-color-adjust:exact; }
table { page-break-after:auto }
tr    { page-break-inside:avoid; page-break-after:auto; position:relative; }
td    { page-break-inside:avoid; page-break-after:auto; position:relative; }
thead { display:table-header-group }
tfoot { display:table-footer-group }
	</style>
		<?php
	}

	function cyfrowe($programy, $pakiety_cyfrowe, $groups, $orderby = '', $view_type = '') {
		$colors = array();
		$colors []= '#FFB3B3';
		$colors []= '#FFD9B3';
		$colors []= '#FFFFB3';
		$colors []= '#D9FFB3';
		$colors []= '#B3FFB3';
		$colors []= '#B3FFD9';
		$colors []= '#B3FFFF';
		$colors []= '#B3D9FF';
		$colors []= '#B3B3FF';
		$colors []= '#D9B3FF';
		$colors []= '#FFB3FF';
		$colors []= '#FFB3D9';
		$colors []= '#FFC6B3';
		$colors []= '#FFECB3';
		$colors []= '#ECFFB3';
		$colors []= '#C6FFB3';
		$colors []= '#B3FFC6';
		$colors []= '#B3FFEC';

		reset($colors);
		foreach ($groups as $name => $group) {
			$groups[$name] = next($colors);
		}

		if ($orderby == 'pakiety') {
			$group_sorter = new GroupSorterCallback();
			$group_sorter->setType('pakiety');
			$group_sorter->_pakiety_cyfrowe = $pakiety_cyfrowe;
			$group_sorter->addGroup('Biały');
			$group_sorter->addGroup('Brązowy');
			$group_sorter->addGroup('Srebrny');
			$group_sorter->addGroup('Złoty');
			$group_sorter->addGroup('Platynowy');
			$group_sorter->addGroup('Pakiet Premium: CANAL+');
			$group_sorter->addGroup('Pakiet Premium: CANAL+ HD');
			$pakiety_cyfrowe_names = array();
			foreach ($pakiety_cyfrowe as $pakiet) {
				$pakiety_cyfrowe_names[] = $pakiet->WWW_NAZWA;
			}
			$group_sorter->addGroups($pakiety_cyfrowe_names);
			uasort($programy, array($group_sorter, 'sort'));
		}
		else if ($orderby == 'name') {
			$group_sorter = new GroupSorterCallback();
			$group_sorter->setType('name');
			uasort($programy, array($group_sorter, 'sort'));
		}
		else {
			$group_sorter = new GroupSorterCallback();
			$group_sorter->setType('group');
			$group_sorter->addGroup('ogólnotematyczny');
			$group_sorter->addGroup('sport');
			$group_sorter->addGroup('filmowy');
			$group_sorter->addGroup('kobiecy');
			$group_sorter->addGroup('dla dzieci');
			$group_sorter->addGroup('informacyjny');
			$group_sorter->addGroups(array_keys($groups));
			uasort($programy, array($group_sorter, 'sort'));
		}

		$pakiety_cyfrowe_count = array();
		foreach ($pakiety_cyfrowe as $pakiet) {
			$pakiety_cyfrowe_count[$pakiet->ID] = 0;
		}
		$pakiety_cyfrowe_count['HD'] = 0;
		foreach ($programy as $program) {
			foreach ($pakiety_cyfrowe as $pakiet) {
				if (in_array($pakiet->ID, $program->pakiety)) {
					$pakiety_cyfrowe_count[$pakiet->ID] += 1;
				}
			}

			if ($program->TV_SIGAL_DELIVERY == 'DVB-HD') {
				$pakiety_cyfrowe_count['HD'] += 1;
			}
		}

		if ($view_type == 'csv') {
			$this->csv_cyfrowe($programy, $pakiety_cyfrowe, $groups, $orderby = '');
			return;
		}

		$this->css();
?>
	<script type="text/javascript">
(function($){
  $.fn.rotateTableCellContent = function(options){
		/*
			Version 1.0
			7/2011
			Written by David Votrubec (davidjs.com) and
			Michal Tehnik (@Mictech) for ST-Software.com

			@from https://github.com/ST-Software/Scripts/tree/master/jquery.rotateTableCellContent
			modified by Piotr Labudda: set -90deg from 90deg
		*/
		var cssClass = ((options) ? options.className : false) || "vertical";
		var cellsToRotate = $('.' + cssClass, this);
		var betterCells = [];
		cellsToRotate.each(function(){
			var cell = $(this)
				, newText = cell.text()
				, height = cell.height()
				, width = cell.width()
				, newDiv = $('<div>', { height: width, width: height })
				, newInnerDiv = $('<div>', { text: newText, 'class': 'rotated' });
			newInnerDiv.css('-webkit-transform-origin', (width / 2) + 'px ' + (width / 2) + 'px');
			newInnerDiv.css('-moz-transform-origin', (width / 2) + 'px ' + (width / 2) + 'px');
			newDiv.append(newInnerDiv);
			betterCells.push(newDiv);
		});

		cellsToRotate.each(function(i){
			$(this).html(betterCells[i]);
		});
	};
})(jQuery);

jQuery(document).ready(function(){
	var n=jQuery('#oferta-programowa-cyfrowe')
	n.rotateTableCellContent();
	n.find('.logo').append(jQuery('<img src="icon/logo.biall-net.jpg">'));
});
	</script>
	<div style="float:right;color:#aaa;"><?php echo date("Y-m-d"); ?></div>
	<h1>Oferta programowa
		<?php if (!V::get('_print', '', $_GET)) : ?>
			- <a href="?MENU_INIT=TV_OFERTA_PROGRAMOWA&orderby=<?php echo $orderby; ?>&_print=1" target="_blank">Drukuj</a>
		<?php endif; ?>
	</h1>
	<p>porównanie pakietów telewizji cyfrowej</p>
	<table cellspacing="0" cellpadding="0" border="0" id="oferta-programowa-cyfrowe" class="oferta-programowa">
	<thead>
		<tr>
			<td colspan="3" class="logo">
			</td>
			<th class="vertical">HD&nbsp;&nbsp;</th>
			<?php foreach ($pakiety_cyfrowe as $pakiet) { ?>
				<th class="vertical prog-pakiet-<?php echo $pakiet->ID; ?>"><?php echo $pakiet->WWW_NAZWA; ?></th>
			<?php } ?>
		</tr>
	</thead>
	<tbody class="cyfrowe-prog-count">
		<tr>
			<td colspan="3" class="p2 r">Liczba programów</td>
			<td class="c"><?php echo $pakiety_cyfrowe_count['HD']; ?></td>
			<?php foreach ($pakiety_cyfrowe as $pakiet) { ?>
				<td class="c"><?php echo $pakiety_cyfrowe_count[$pakiet->ID]; ?></td>
			<?php } ?>
		</tr>
	</tbody>
	<tbody>
	<?php $t = 1; foreach ($programy as $program) { ?>
		<tr class="row-<?php echo ($t = 1 - $t); ?>">
			<td class="p2 r nr"><?php echo $program->TV_DVBC_EPG_CHANNEL_NUMBER; ?></td>
			<td class="p2"><?php echo $program->TV_NAZWA_PROGRAMU; ?></td>
			<td class="p2 c prog-group prog-group-<?php echo substr($groups[$program->TV_PROGRAM_PROFILE], 1); ?>"><?php echo $program->TV_PROGRAM_PROFILE; ?></td>
			<?php if ($program->TV_SIGAL_DELIVERY == 'DVB-HD') : ?>
				<td class="hd c">HD</td>
			<?php else: ?>
				<td></td>
			<?php endif; ?>
			<?php foreach ($pakiety_cyfrowe as $pakiet) { ?>
				<?php if (in_array($pakiet->ID, $program->pakiety)) : ?>
					<td class="c prog-pakiet-<?php echo $pakiet->ID; ?>">&diams;</td>
				<?php else : ?>
					<td></td>
				<?php endif; ?>
			<?php } ?>
		</tr>
	<?php } ?>
	</tbody>
	</table>
<?php
	}

	function csv_cyfrowe($programy, $pakiety_cyfrowe, $groups, $orderby = '') {
		echo'<pre style="overflow:auto;border:1px solid red;text-align:left;">';
		foreach ($programy as $program) {
			$csv_line = array();
			$csv_line []= '"' . $program->TV_DVBC_EPG_CHANNEL_NUMBER . '"';
			$csv_line []= '"' . $program->TV_NAZWA_PROGRAMU . '"';
			$csv_line []= '"' . $program->TV_PROGRAM_PROFILE . '"';
			$csv_line []= '"' . (($program->TV_SIGAL_DELIVERY == 'DVB-HD')? 'HD' : '') . '"';
			foreach ($pakiety_cyfrowe as $pakiet) {
				if (in_array($pakiet->ID, $program->pakiety)) {
					$csv_line []= '"1"';
				} else {
					$csv_line []= '"0"';
				}
			}
			echo implode(';', $csv_line) . "\n";
		}
		echo'</pre>';
	}

	function analogowe($programy, $groups, $orderby = '') {
		$colors = array();
		$colors []= '#FFB3B3';
		$colors []= '#FFD9B3';
		$colors []= '#FFFFB3';
		$colors []= '#D9FFB3';
		$colors []= '#B3FFB3';
		$colors []= '#B3FFD9';
		$colors []= '#B3FFFF';
		$colors []= '#B3D9FF';
		$colors []= '#B3B3FF';
		$colors []= '#D9B3FF';
		$colors []= '#FFB3FF';
		$colors []= '#FFB3D9';
		$colors []= '#FFC6B3';
		$colors []= '#FFECB3';
		$colors []= '#ECFFB3';
		$colors []= '#C6FFB3';
		$colors []= '#B3FFC6';
		$colors []= '#B3FFEC';

		reset($colors);
		foreach ($groups as $name => $group) {
			$groups[$name] = next($colors);
		}

		if ($orderby == 'name') {
			$group_sorter = new GroupSorterCallback();
			$group_sorter->setType('name');
			uasort($programy, array($group_sorter, 'sort'));
		}
		else {
			$group_sorter = new GroupSorterCallback();
			$group_sorter->setType('group');
			$group_sorter->addGroup('ogólnotematyczny');
			$group_sorter->addGroup('sport');
			$group_sorter->addGroup('filmowy');
			$group_sorter->addGroup('kobiecy');
			$group_sorter->addGroup('dla dzieci');
			$group_sorter->addGroup('informacyjny');
			$group_sorter->addGroups(array_keys($groups));
			uasort($programy, array($group_sorter, 'sort'));
		}

		$this->css();
?>
	<h1>Oferta programowa - telewizja analogowa
		<?php if (!V::get('_print', '', $_GET)) : ?>
			- <a href="?MENU_INIT=TV_OFERTA_PROGRAMOWA&task=analog&orderby=<?php echo $orderby; ?>&_print=1" target="_blank">Drukuj</a>
		<?php endif; ?>
	</h1>
	<table cellspacing="0" cellpadding="0" border="0" id="oferta-programowa-analogowe" class="oferta-programowa">
	<thead>
		<tr>
			<th class="p2">Lp.</th>
			<th class="p2">Nazwa</th>
			<th class="p2">Grupa</th>
			<th class="p2">Czętotliwość</th>
		</tr>
	</thead>
	<tbody>
	<?php $lp = 0; $t = 1; foreach ($programy as $program) { $lp++; ?>
		<tr class="row-<?php echo ($t = 1 - $t); ?>">
			<td class="p2 prog-group"><?php echo $lp; ?></td>
			<td class="p2"><?php echo $program->TV_NAZWA_PROGRAMU; ?></td>
			<td class="p2 c prog-group prog-group-<?php echo substr($groups[$program->TV_PROGRAM_PROFILE], 1); ?>"><?php echo $program->TV_PROGRAM_PROFILE; ?></td>
			<td class="p2 r"><?php echo $program->TV_ANALOG_FREQUENCY; ?></td>
		</tr>
	<?php } ?>
	</tbody>
	</table>
<?php
	}

}

class TvOfertaHelper {

	function getPakietyCyfrowe() {
		$pakiety_cyfrowe = array();
		$db = DB::getDB();
		$sql = "select gc.`ID`, gc.`POKAZ_NA_WWW`, gc.`WWW_NAZWA`, gc.`WWW_P_SERVICE`
				, if(gc.`WWW_P_SERVICE`='TVC', 1, 2) as order_by_lp
			from `USERS2_OFFERS_COSTS_GROUPS` as gc
			where
				gc.`A_STATUS` in('NORMAL', 'WAITING')
				and gc.`POKAZ_NA_WWW`='TAK'
			order by order_by_lp
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$pakiety_cyfrowe[$r->ID] = $r;
		}
		return $pakiety_cyfrowe;
	}

	function getProgramyCyfrowe() {
		$db = DB::getDB();
		$programy = array();
		$sql = "select c.ID as c_ID
				, c.ID_PROJECT as c_ID_PROJECT
				, p.ID, p.TV_NAZWA_PROGRAMU, p.TV_LANGUAGE, p.TV_SIGAL_DELIVERY, p.TV_PROGRAM_PROFILE, p.TV_DVBC_EPG_CHANNEL_NUMBER, p.M_DIST_INVENTOR
				, CAST(p.`TV_DVBC_EPG_CHANNEL_NUMBER` AS SIGNED) as order_by_lp
				, GROUP_CONCAT(cg.ID) as cost_group_ids
			from `USERS2_OFFERS_COSTS_GROUPS` as cg
				left join `USERS2_OFFERS_COSTS` as c on(c.`ID_COSTS_GROUPS`=cg.`ID`)
				left join `IN7_MK_BAZA_DYSTRYBUCJI` as p on(p.`ID`=c.`ID_PROJECT` and p.`M_DIST_TYPE`='TV__UMOWA ZAKUPU KANALU')
			where
				p.`M_DIST_TYPE`='TV__UMOWA ZAKUPU KANALU' 
				and c.`S_OFFER_STATUS`='IN_OFFER' 
				and cg.`ID_MAIN_COSTS_GROUP`=47 
				and p.`ID` is not NULL 
				and cg.`A_STATUS` in('WAITING', 'NORMAL') 
				and c.`A_STATUS` in('WAITING', 'NORMAL') 
				and p.`A_STATUS` in('WAITING', 'NORMAL') 
				and p.`TV_SIGAL_DELIVERY` in ('DVB-SD', 'DVB-HD')
				and cg.`POKAZ_NA_WWW`='TAK'
			group by p.ID
			order by order_by_lp ASC
			limit 1000;
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$r->pakiety = explode(',', $r->cost_group_ids);
			$programy []= $r;
		}
		return $programy;
	}

	function getProgramyAnalogowe() {
		$db = DB::getDB();
		$programy = array();
		$sql = "select c.ID as c_ID
				, c.ID_PROJECT as c_ID_PROJECT
				, p.ID, p.TV_NAZWA_PROGRAMU, p.TV_LANGUAGE, p.TV_SIGAL_DELIVERY
				, p.TV_PROGRAM_PROFILE
			--	, p.TV_DVBC_EPG_CHANNEL_NUMBER
				, p.M_DIST_INVENTOR
				, p.TV_ANALOG_FREQUENCY
				, CAST(p.`TV_DVBC_EPG_CHANNEL_NUMBER` AS SIGNED) as order_by_lp
				, GROUP_CONCAT(cg.ID) as cost_group_ids
			from `USERS2_OFFERS_COSTS_GROUPS` as cg
				left join `USERS2_OFFERS_COSTS` as c on(c.`ID_COSTS_GROUPS`=cg.`ID`)
				left join `IN7_MK_BAZA_DYSTRYBUCJI` as p on(p.`ID`=c.`ID_PROJECT` and p.`M_DIST_TYPE`='TV__UMOWA ZAKUPU KANALU')
			where
				p.`M_DIST_TYPE`='TV__UMOWA ZAKUPU KANALU' 
				and c.`S_OFFER_STATUS`='IN_OFFER' 
				and cg.`ID`=2 
				and p.`ID` is not NULL 
				and cg.`A_STATUS` in('WAITING', 'NORMAL') 
				and c.`A_STATUS` in('WAITING', 'NORMAL') 
				and p.`A_STATUS` in('WAITING', 'NORMAL') 
				and p.`TV_SIGAL_DELIVERY` in ('ANALOG')
				-- and cg.`POKAZ_NA_WWW`='TAK'
			group by p.ID
			order by order_by_lp ASC
			limit 1000;
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$r->pakiety = explode(',', $r->cost_group_ids);
			$programy []= $r;
		}
		return $programy;
	}

}

class GroupSorterCallback {

	var $groups_order;
	var $_type = '';// group, pakiety
	var $_pakiety_cyfrowe = '';

	function setType($type) {
		$this->_type = $type;
	}

	function setOrder($group_name, $order) {
		$this->groups_order[$group_name] = $order;
	}

	function getOrder($item) {
		if ($this->_type == 'name') {
			return 0;
		} else if ($this->_type == 'pakiety') {
			$min_order = 999;
			foreach ($this->_pakiety_cyfrowe as $pakiet) {
				if (in_array($pakiet->ID, $item->pakiety)) {
					$cur_order = 999;
					if (array_key_exists($pakiet->WWW_NAZWA, $this->groups_order)) {
						$cur_order = $this->groups_order[$pakiet->WWW_NAZWA];
					}
					$min_order = min($min_order, $cur_order);
				}
			}
			return $min_order;
		} else {
			$group_name = $item->TV_PROGRAM_PROFILE;
			if (array_key_exists($group_name, $this->groups_order)) {
				return $this->groups_order[$group_name];
			}
		}
		return count($this->groups_order) + 1;
	}

	function addGroup($group_name) {
		$this->groups_order[$group_name] = count($this->groups_order) + 1;
	}

	function addGroups($groups) {
		foreach ($groups as $group_name) {
			if (!array_key_exists($group_name, $this->groups_order)) {
				$this->addGroup($group_name);
			}
		}
	}

	function sort($a, $b) {
		$oa = $this->getOrder($a);
		$ob = $this->getOrder($b);
		// sortuj w kolejności malejącej
		if ($oa < $ob) {
			return -1;
		} else if ($oa > $ob) {
			return 1;
		} else {
			// sortuj rosnąco alfabetycznie
			if ($a->TV_NAZWA_PROGRAMU < $b->TV_NAZWA_PROGRAMU) {
				return -1;
			} else if ($a->TV_NAZWA_PROGRAMU > $b->TV_NAZWA_PROGRAMU) {
				return 1;
			} else {
				return 0;
			}
		}
	}

}
