<?php

error_reporting(E_ALL & ~E_NOTICE);

define('DS', DIRECTORY_SEPARATOR);
define('APP_PATH_ROOT', realpath(dirname(__FILE__) . DS . '..'));
define('APP_PATH_WWW', realpath(dirname(__FILE__) . DS . '..'));
define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');

//session_save_path("../session") ;
session_start();

date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions

header('Content-Type: text/html; charset=utf-8');

// SEF - SE file loader
function SEF($ARG1) {
	if (!function_exists($ARG1)) {
		if (file_exists(APP_PATH_ROOT . DS . "superedit-".$ARG1.".php")) include(APP_PATH_ROOT . DS . "superedit-".$ARG1.".php");
		else if (file_exists(APP_PATH_ROOT . DS . "billing-".$ARG1.".php")) include(APP_PATH_ROOT . DS . "billing-".$ARG1.".php");
		else if (file_exists(APP_PATH_ROOT . DS . $ARG1.".php")) include(APP_PATH_ROOT . DS . $ARG1.".php");
		else echo ("\n<br>Function SEF : can't find function ".$ARG1);
	}
}
SEF("DEBUG_S");

if (file_exists(APP_PATH_ROOT . DS . ".config.php")) include(APP_PATH_ROOT . DS . ".config.php");

require_once APP_PATH_ROOT . '/' . 'se-lib' . '/' . 'Lib.php';
Lib::loadClass('V');
Lib::loadClass('User');
Lib::loadClass('Config');
Lib::loadClass('App');
Lib::loadClass('DB');
Lib::loadClass('S');


if (!User::logged()) {
	die("Require login!");
}

//if (User::get('ADM_ADMIN_LEVEL') != 0) {
//	die("Access denied!");
//}

Lib::loadClass('ZasobFileOdt');

$druki_path = '/home/samba/DRUKI';
if ($_SERVER['SERVER_NAME'] == 'se.dev.webone.pl.devpl') {
	$druki_path = realpath(APP_PATH_ROOT . '/../../samba/DRUKI/');
} else if ($_SERVER['SERVER_NAME'] == 'biuro.biall-net.pl') {
	$druki_path = '/Library/Server/Web/Data/Sites/Default/PLIKI/DRUKI/';
}



$allowed_options = array('NET', 'TEL', 'TV', 'TVC');
$args = array();
$args['id_user'] = V::get('id_user', 0, $_GET, 'int');
$args['id_options'] = array();
foreach ($allowed_options as $v_option) {
	$args['id_options'][$v_option] = V::get('id_options_' . $v_option . '', 0, $_GET, 'array');
}

$user = null;
if ($args['id_user'] > 0) {
	/*
	 * <span id="cell-KLIENT_ID"></span>
	 * <span id="cell-KLIENT_P_NAME"></span>
	 * <span id="cell-KLIENT_P_NAME_SECOND"></span>
	 * <span id="cell-KLIENT_P_PHONE"></span>
	 * <span id="cell-KLIENT_user_mail_contact"></span>
	 */
	$db = DB::getDB();
	$sql = "select bua.`id_users`
			, bua.`id_users` as ID_BILLING_USERS
			, bua.`is_firma`
			, bua.`P_NAME`
			, bua.`P_NAME_SECOND`
			, bua.`P_NIP`
			, bua.`P_PESEL`
			, bua.`P_PHONE`
			, bua.`P_ADDRESS_REGION`
			, bua.`P_ADDRESS_CITY`
			, bua.`P_ADDRESS_POST_CODE`
			, bua.`P_ADDRESS_STREET`
			, bua.`P_ADDRESS_HOME`
			, bua.`P_ADDRESS_HOUSE`
			, bua.`user_mail_contact`
			, bu.`BILLING_OWNER`
		from `BILLING_USERS_ADD` as bua
			left join `BILLING_USERS` as bu on(bu.`ID`=bua.`id_users`)
		where bua.`id_users`='{$args['id_user']}'
	";
	$res = $db->query($sql);
	if ($r = $db->fetch($res)) {
		$user = $r;
	}
}

$umowaOdt = null;
if ($user) {
	if ($user->BILLING_OWNER == 1) {// BN
		$umowaOdt = new ZasobFileOdt(1657, $druki_path, dirname(__FILE__), 1657);
	} else if ($user->BILLING_OWNER == 2 || $user->BILLING_OWNER == 3) {// ND
		$umowaOdt = new ZasobFileOdt(1657, $druki_path, dirname(__FILE__), 4357);
	}
}
if (!$umowaOdt) {
	$umowaOdt = new ZasobFileOdt(1657, $druki_path, dirname(__FILE__));
}
if (false == $umowaOdt->find_odt_file()) {
	die("Error: cant find file! [" . $umowaOdt->zasob_id . "]");
}
if (false == $umowaOdt->find_xsl_file()) {
	die("Template file not exists! - [" . $umowaOdt->zasob_id . "]");
}

if (V::get('test', 0, $_GET, 'int') == 1) {
	$odt_file_arr = explode('/', $umowaOdt->odt_file);
	array_pop($odt_file_arr);
	$umowaOdt->odt_file = implode('/', $odt_file_arr) . '/STARE/test.odt';
}
if (123 == V::get('DBG', 0, $_GET, 'int')) {
	echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($umowaOdt);echo'</pre>';
}

Lib::loadClass('Odt2xhtml');

if (!class_exists('DOMDocument')) {
	die('require class DOMDocument');
}
if (!class_exists('XSLTProcessor')) {
	die('require class XSLTProcessor');
}
if (!function_exists('zip_open')) {
	die('NO ZIP FUNCTIONS DETECTED. Do you have the PECL ZIP extensions loaded?');
}

$conv = new Odt2xhtml;

if ($umowaOdt->fetch_content_from_odt_by_converter($conv)) {
	die("Conversion odt to html error! - [" . $umowaOdt->zasob_id . "]");
}

// fetch data from DB

if (!empty($args['id_options'])) {
/*
 * <span id="cell-OPCJA_NET_1_450"></span>
 * <span id="cell-OPCJA_NET_1_1385"></span>
 * <span id="cell-OPCJA_NET_1_459"></span>
 * <span id="cell-OPCJA_NET_1_1580"></span>
 * <span id="cell-OPCJA_NET_1_457"></span>
 * <span id="cell-OPCJA_NET_1_460"></span>
 * <span id="cell-OPCJA_NET_1_458"></span>
 * 
 * <span id="cell-OPCJA_TEL_1_450"></span>
 * 
 * <span id="cell-OPCJA_TV_1_450"></span>
 * 
 * , '' as OPCJA_NET_1_450 -- P_SERVICE_NAME - nazwa
 * , '' as OPCJA_NET_1_1385 -- ID
 * , '' as OPCJA_NET_1_459 -- P_CONTRACT_PRICE - abonament
 * -- , t4.P_NORMAL_PRICE * t0.P_DEALTERM_MONTHS - t4.P_DEAL_PROMO_MONTHS * t4.P_PROMO_MONTH_PRICE - (t0.P_DEALTERM_MONTHS - t4.P_DEAL_PROMO_MONTHS) * t4.P_CONTRACT_PRICE + (t4.P_INSTALL_QUOTE_NORMAL - t4.P_INSTALL_QUOTE) as `t4_1580`
 * , '' as OPCJA_NET_1_1580 -- upust od ceny nominalnej
 * , '' as OPCJA_NET_1_457 -- P_DEAL_PROMO_MONTHS - liczba miesiecy promocyjnych
 * , '' as OPCJA_NET_1_460 -- P_PROMO_MONTH_PRICE - cena abonamentu w promocyjnych miesiacach
 * , '' as OPCJA_NET_1_458 -- P_INSTALL_QUOTE - cena promocyjna
 */

	$options_to_load = array();
	foreach ($args['id_options'] as $k_service => $v_options) {
		if (empty($v_options)) continue;
		foreach ($v_options as $v_option_id) {
			if ($v_option_id > 0) {
				$options_to_load[$k_service] []= $v_option_id;
			}
		}
	}

	if (V::get('DBG', 0, $_GET, 'int')) {
		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">args: ';print_r($args);echo'</pre>';
		if (!empty($options_to_load)) {
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">options_to_load: ';print_r($options_to_load);echo'</pre>';
		}
	}

	$sql_ids = array();
	foreach ($options_to_load as $k_service => $v_options_arr) {
		foreach ($v_options_arr as $v_offerr_id) {
			$sql_ids []= "'" . $v_offerr_id . "'";
		}
	}

	if (!empty($sql_ids)) {
		$options_to_load_counter = array();
		foreach ($options_to_load as $k_service => $v_arr) {
			$options_to_load_counter[$k_service] = 0;
		}

		$to_convert_encoding = array();
		$to_convert_encoding []= 'z_450';

		$oferty_opcje = array();
		$sql = "select
				t.`ID` as z_1385
				, t.`P_SERVICE` as `z_449`
				, t.`P_SERVICE_PARENT` as `z_3280`
				, t.`P_SERVICE_NAME` as z_450
				, t.`P_CONTRACT_PRICE` as z_459
				, '' as z_1580
				, t.`P_DEALTERM_MONTHS` as z_456
				, t.`P_DEAL_PROMO_MONTHS` as z_457
				, t.`P_PROMO_MONTH_PRICE` as z_460
				, t.`P_INSTALL_QUOTE` as z_458
			FROM `USERS2_OFFERS` as t
			WHERE
				t.`ID` in(" . implode(",", $sql_ids) . ")
				and t.`P_SERVICE`='OPCJE'
				--	t.`P_SERVICE_COMPANY`='BN'
				--	AND ( t.`A_STATUS` = 'NORMAL'  OR t.`A_STATUS`='WAITING' )
		";
		$res = DB::query($sql);
		while ($h = DB::fetch_assoc($res)) {
			//foreach ($to_convert_encoding as $v_field) {
			//	if (array_key_exists($v_field, $h)) {
			//		$h[$v_field] = iconv('latin2', 'utf-8', $h[$v_field]);
			//	}
			//}
			$oferty_opcje[ $h['z_1385'] ] = $h;
		}
		if (V::get('DBG', 0, $_GET, 'int')) {echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">oferty_opcje: ';print_r($oferty_opcje);echo'</pre>';}

		$replace_fields = array();
		foreach ($oferty_opcje as $k_id => $h) {
			$cur_option_service = $h['z_3280'];
			if (!array_key_exists($cur_option_service, $options_to_load)) {
				// TODO: error
				continue;
			}

			$options_to_load_counter[$cur_option_service]++;

			$cur_option_index = $options_to_load_counter[$cur_option_service];

			$replace_key_prefix = 'OPCJA_' . $cur_option_service . '_' . $cur_option_index . '_';
			$replace_fields[$replace_key_prefix . '450'] = $h['z_450'];
			$replace_fields[$replace_key_prefix . '1385'] = $h['z_1385'];
			$replace_fields[$replace_key_prefix . '459'] = $h['z_459'];
			$replace_fields[$replace_key_prefix . '1580'] = $h['z_1580'];
			$replace_fields[$replace_key_prefix . '456'] = $h['z_456'];
			$replace_fields[$replace_key_prefix . '457'] = $h['z_457'];
			$replace_fields[$replace_key_prefix . '460'] = $h['z_460'];
			$replace_fields[$replace_key_prefix . '458'] = $h['z_458'];
		}
		if (V::get('DBG', 0, $_GET, 'int')) {echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">replace_fields: ';print_r($replace_fields);echo'</pre>';}

		if (!empty($replace_fields)) {
			$umowaOdt->add_data($replace_fields);
		}
	}
}

/*
 * <span id="cell-779"></span>  - data
 */
$replace_fields = array();
$replace_fields['779'] = date('Y-m-d');
$umowaOdt->add_data($replace_fields);

if ($args['id_user'] > 0) {
	/*
	 * <span id="cell-KLIENT_ID"></span>
	 * <span id="cell-KLIENT_P_NAME"></span>
	 * <span id="cell-KLIENT_P_NAME_SECOND"></span>
	 * <span id="cell-KLIENT_P_PHONE"></span>
	 * <span id="cell-KLIENT_user_mail_contact"></span>
	 */
	if ($user) {
		$replace_fields = array();
		$replace_fields['KLIENT_ID'] = $user->ID_BILLING_USERS;
		$replace_fields['KLIENT_P_NAME'] = $user->P_NAME;//iconv('latin2', 'utf-8', $user->P_NAME);
		$replace_fields['KLIENT_P_NAME_SECOND'] = $user->P_NAME_SECOND;//iconv('latin2', 'utf-8', $user->P_NAME_SECOND);
		$replace_fields['KLIENT_P_PHONE'] = $user->P_PHONE;
		$replace_fields['KLIENT_user_mail_contact'] = $user->user_mail_contact;
		$umowaOdt->add_data($replace_fields);
	}
}

echo $umowaOdt->get_content();

?>
