<?php
/**
 * wykonywanie procesu zapisywane w tabeli `CRM_PROCES_LOG`
 *   `CRM_PROCES_LOG`.`TYPE`:
 *     'INIT' - rozpoczeto proces
 *     'STEP' - krok `ID_STEP`
 *     'END' - zakonczono proces
 * 
 * ID_PROCES_INIT (C)
 * ID_STEP (W) - aktualny krok
 * ID_STEP_WSKAZNIK (W) - aktualny wskaznik w kroku
 * 
 * stany:
 *   edycja rekordu - wedlug zawartosci pola ID_STEP_WSKAZNIK (tabela/zrodlo danych z drzewa zasobow)
 *     ID_STEP_WSKAZNIK jest ustawiony - jesli nie to pierwszy w kolejnosci
 *     ID_KEY - jeszcze nie ustawiony - jesli ustawiony to pokazac rekord/edycje, akcje - NEXT
 * 
 * akcje:
 *   'save_edit' - zapis formularza edycji rekordu
 *       @see fun_PROCES_STEP_SAVE @param _action
 *   next step - nastepny krok (jesli nie aktualny wskaznik jest ostatnim w kroku)
 *       ID_STEP_WSKAZNIK - jest ustalany po wybraniu/edycji/utworzeniu/akcji na rekordzie ID_KEY zasobu/tabeli A_UPDATE_ZASOB_ID
 *   next step wsk - nastepny wskaznik w kroku
 *       zmiana ID_STEP_WSKAZNIK na nastepny w kolejnosci bez ustalania ID_KEY
 * 
 * 
 * 
 * Obsługa plików:
 *   Zasoby:
 * serwer (host)
 *   ZASOB_PLIKOW (path eg. /home/samba)
 *     ZASOB_PLIKOW (PROJEKTY) -> /home/samba/PROJEKTY
 * [X]   SCHEMAT KATALOG (PR)
 *         DANE 1 (ID_PROJ)
 *         DANE 2 (DATE)
 *         DANE 3 (TYPE)
 *         DANE 4 (OPIS)
 *         SCHEMAT KATALOG ()
 *           DANE 1 (part 1)
 *           DANE 2 (part 2)
 *         PLIK
 *           DANE 1 (row ID)
 *           DANE 2 (rodzaj) z parent [X]
 *           DANE 3 (typ)
 *             DANE (PISMO)
 *             DANE (ZDJECIE)
 *             DANE (...)
 *           DANE 4 (opis) - reczny
 *           DANE 5 (data utworzenia)
 *           DANE 6 (data wersji)
 *           DANE 7 (ext)
 * 
 *  PLIK OLD 2011-10-28.PISMO.Podanie_o_przesuniecie_te.2011-10-28.16883.pdf)
 *  PLIK NEW row_ID.PISMO.zasob_ID.Podanie_o_przesuniecie_te.2011-10-28.2011-10-28.pdf)
 *  PLIK NEW row_ID.PR.PISMO.Podanie_o_przesuniecie_te.2011-10-28.2011-10-28.pdf)
 *  PLIK NEW row_ID . rodzaj . typ . opis . data crete . data update . ext)
 */


Lib::loadClass('BaseDao');
Lib::loadClass('ProcesLogModel');


class ProcesLogDao extends BaseDao {

	function __construct( $db ) {
		parent::__construct($db, 'CRM_PROCES_LOG');
	}

	function get_by_id( $id ) {
		$null = null;
		$id = (int)$id;
		if ($id <= 0) return $null;
		$sql = "select t.*
			from `" . $this->_table . "` as t
			where t.`ID`='" . $id . "'
		";
		$res = DB::query($sql);
		if ($h = DB::fetch_assoc($res)) {
			$model = new ProcesLogModel($this);
			$model->setDataFromDB($h);
			return $model;
		}
		return $null;
	}

	function get_hist( $id ) {
	}

	/**
	 * @returns int
	 */
	function get_user_log_list_count( $user_id, $user_groups ) {
		$ret = 0;
		$sql_where = $this->_get_user_log_list_query_where($user_id, $user_groups);
		$sql = "select count(1) as cnt
			from `" . $this->_table . "` as plog
			where " . $sql_where . "
		";
		$res = $this->_db->query($sql);
		if ($r = $this->_db->fetch($res)) {
			$ret = $r->cnt;
		}
		return $ret;
	}

	/**
	 * @returns array of ProcesLogModel objects.
	 */
	function get_user_log_list( $user_id, $user_groups, $limitstart = 0 ) {
		$ret = array();
		$sql_offset = intval($limitstart);
		$sql_where = $this->_get_user_log_list_query_where($user_id, $user_groups);
		$sql = "select plog.*
			from `" . $this->_table . "` as plog
			where " . $sql_where . "
			limit 20 offset " . $sql_offset . "
		";
		$res = $this->_db->query($sql);
		while ($r = $this->_db->fetch($res)) {
			$model = new ProcesLogModel($this);
			$model->setDataFromDB($r);
			$ret []= $model;
		}
		return $ret;
	}

	function _get_user_log_list_query_where( $user_id, $user_groups ) {
		$sql_where = '';
		$sql_where_groups_add = '';
		if (!empty($user_groups)) {
			$sql_where_groups_and = array();
			foreach ($user_groups as $v_group_id) {
				$sql_where_groups_and []= "FIND_IN_SET('$v_group_id', plog.`ID_STANOWISKA`)";
			}
			$sql_where_groups_add .= " or (plog.`ID_USER`=0 and (" . implode(" or ", $sql_where_groups_and) . "))";
		}
		$sql_where = "( (plog.`ID_USER`>0 and plog.`ID_USER`='" . $user_id . "')
				" . $sql_where_groups_add . " )
		";
		return $sql_where;
	}

	/**
	 * Create ProcesLogModel and save data into table `PROCES_LOG`.
	 * @returns boolean.
	 * @see save
	 */
	function proces_log_init($user_id, $user_login, $proces_id) {
		$log_model = new ProcesLogModel($this);
		$log_model->set('A_RECORD_CREATE_DATE', date("Y-m-d-H:i"));
		$log_model->set('A_RECORD_CREATE_AUTHOR', $user_login);
		$log_model->set('ID_USER', $user_id);
		$log_model->set('TYPE', 'INIT');
		$log_model->set('ID_PROCES_INIT', $proces_id);
		$log_model->set('ID_STEP', $proces_id);
		//$log_model->set('ID_STANOWISKA', '');// nieokreślony
		$log_model->set('ID_KEY', 0);
		return $this->save($log_model);
	}

	/**
	 * Get model actions by state.
	 * @returns array of actions.
	 */
	function get_model_actions($model) {
		$actions = array();
		if (!$model->get('ID')) {
			return $ret;
		}
		switch ($model->get('TYPE')) {
			case 'INIT':
				$actions ['step']= "kontynuuj";
				break;
			case 'STEP':
				$actions ['step']= "kontynuuj";
				$actions ['quit']= "zakończ";
				break;
			case 'END':
				$actions ['hist']= "hist";
				break;
		}

		return $actions;
	}

	/**
	 * Check if user or group ids has access to log model.
	 * @returns boolean.
	 */
	function check_access($modelLog, $user_id, $user_groups_ids) {
		if (!$modelLog->get('ID')) {
			return false;
		}
		if ($modelLog->get('ID_USER') == $user_id) {
			return true;
		} else if ($modelLog->get('ID_USER') == 0) {
			$log_groups = explode(',', $modelLog->get('ID_STANOWISKA'));
			if (!empty($log_groups)) {
				foreach ($user_groups_ids as $v_group_id) {
					if (in_array($v_group_id, $log_groups)) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 
	 * @returns ProcesLogEditModel or null
	 * TODO: RMME - not used
	 */
	function get_next_edit($modelLog, $wskazniki, $current_edit) {
		$ret = null;
		return $ret;
	}

	function get_proces_next_steps($cur_step_id) {
		$ret = array();
		if ($cur_step_id <= 0) {
			return $ret;
		}
		$cur_row = $this->_db->get_by_id('CRM_PROCES', $cur_step_id);
		if (!$cur_row) {
			return $ret;
		}
		$sql = "select p.`ID`, p.`DESC`
			from `CRM_PROCES` as p
			where p.`PARENT_ID`='" . $cur_step_id . "'
				and p.`A_STATUS` in ('WAITING', 'NORMAL')
			order by p.`SORT_PRIO` asc, p.`ID` asc
		";
		$res = $this->_db->query($sql);
		while ($r = $this->_db->fetch($res)) {
			$ret [$r->ID] = $r->DESC;
		}
		if ($cur_row->IF_TRUE_GOTO > 0) {
			$goto_row = $this->_db->get_by_id('CRM_PROCES', $cur_row->IF_TRUE_GOTO);
			if ($goto_row) {
				$ret [$goto_row->ID] = $goto_row->DESC;
			}
		}
		return $ret;
	}

	function get_wskazniki($proces_id) {
		$ret = array();
		$proces_id = (int)$proces_id;
		if ($proces_id <= 0) {
			return $ret;
		}
		$sql = "select
				clz.*
				, w.`ID` as CW_ID, w.`TYP` as CW_TYP, w.`OPIS_ZASOB` as OPIS_ZASOB, w.`SORT_PRIO` as CW_SORT_PRIO, w.`ID_PRZYPADEK` as CW_ID_PRZYPADEK
				, w.`A_HAS_IMAGE` as CW_A_HAS_IMAGE
				, cp.`PYTANIE` as CP_PYTANIE, cp.`OPIS` as CP_OPIS, cp.`FORM_TREAT` as CP_FORM_TREAT
			from `CRM_WSKAZNIK` as w
				left join `CRM_LISTA_ZASOBOW` as clz on (clz.`ID`=w.`ID_ZASOB`)
				left join `CRM_PRZYPADEK` as cp on (cp.`ID`=w.`ID_PRZYPADEK`)
			where
				w.`ID_PROCES`='".$proces_id."'
				and w.`A_STATUS` in('WAITING','NORMAL','MONITOR')
			order by w.`SORT_PRIO` asc, w.`ID` asc
		";
		$res = $this->_db->query( $sql );
		while ($r = $this->_db->fetch( $res )) {
			$ret[$r->CW_ID] = $r;
		}
		return $ret;
	}

	/**
	 * Fetch sql types.
	 * @returns array( Field => array(
	 *   [Type] => int(10)
	 *   [Null] => NO
	 *   [Key] => PRI
	 *   [Default] => 
	 *   [Extra] => auto_increment )
	 * TODO: use cache SES
	 */
	function get_sql_types($sql_table) {
		$db = DB::getDB();
		$types = array();
		$sql = "show fields from `" . $sql_table . "`;";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$field = $r->Field;
			unset($r->Field);
			$types [$field]= $r;
		}
		return $types;
	}

	/**
	 * @returns array of wsk id's tree flat - TODO:
	 */
	function get_wskazniki_parent_tables($wskazniki) {
		$ret = array();
		if (empty($wskazniki)) {
			return $ret;
		}
		$komorka_ids = array();
		foreach ($wskazniki as $k_id => $v_wsk) {
			if ($v_wsk->TYPE == 'KOMORKA') {// TODO: 'DANE' under 'KOMORKA'
				$komorka_ids []= $v_wsk->ID;
			}
		}
		if (empty($komorka_ids)) {
			return $ret;
		}

		$sql = "select z.`ID`, z.`TYPE`, z.`DESC`
				, pz.`ID` as p__ID, pz.`TYPE` as p__TYPE, pz.`DESC` as p__DESC
			from `CRM_LISTA_ZASOBOW` as z
				left join `CRM_LISTA_ZASOBOW` as pz on(pz.`ID`=z.`PARENT_ID` and pz.`A_STATUS` in ('WAITING','NORMAL'))
			where
				z.`ID` in(" . implode(",", $komorka_ids) . ")
				and z.`A_STATUS` in ('WAITING','NORMAL')
		";
		$res = $this->_db->query($sql);
		while ($r = $this->_db->fetch($res)) {
			// TODO: use TYPE = DANE
			if ($r->TYPE == 'TABELA') {
				$ret [$r->ID]= (object)array('ID'=>$r->ID, 'DESC'=>$r->DESC, 'TYPE'=>$r->TYPE);
			} else if ($r->p__TYPE == 'TABELA') {
				$ret [$r->p__ID]= (object)array('ID'=>$r->p__ID, 'DESC'=>$r->p__DESC, 'TYPE'=>$r->p__TYPE);
				$ret [$r->ID]= $r->p__ID;
			}
		}
		return $ret;
	}

}
