<?php


session_start();

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

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

SEF('DEBUG_S');
SEF("ZAP_SQL");
SEF("USERS_COLUMN_INIT");
SEF("AUTHORIZE_USER");
SEF("AUTHORIZE_USER_LOGIN");
//SEF("AUTHORIZE_USER_BY_AUTH_MODULE");
//SEF("AUTHORIZE_USER_LOGIN_BY_AUTH_MODULE");
SEF("GETFORMITEM");
SEF("T_WORKPOINTS_USER_SELECT");
require_once dirname(__FILE__) . '/' . 'se-lib' . '/' . 'Lib.php';
Lib::loadClass('V');
Lib::loadClass('User');
Lib::loadClass('App');
Lib::loadClass('DB');



$conn = DB::connect();


$task = V::get('task', '', $_REQUEST);

if ($task) {
	$con = new SyncDB();
	$task_fun = 'task_'.$task;
	if (method_exists($con, $task_fun)) {
		$con->$task_fun();
	} else {
		die('task not exists');
	}
} else {
	die('no task');
}



// ==================== Sync DB ===================


class SyncDB {


var $output;


function __construct() {
	$this->output = V::get('output', '', $_REQUEST);
}


function write( $str ) {
	if ($this->output) {
		error_log($str, 3, $this->output);
	} else {
		echo $str;
	}
}


function task_export_csv() {
	$tbl = V::get('tbl', '', $_REQUEST);
	if (!$tbl) return;
	$sql = new stdClass();
	$sql->fields = array();
	$sql->limit = V::get('limit', '', $_REQUEST);
	$sql->offset = V::get('offset', '', $_REQUEST);

	$sql->out_where = 'where 1=1';
	$sql->out_limit = '';
	//if (($sql->limit && $sql->offset)? ' limit '.$sql->limit : '');
/*
[FROM table_references
    [WHERE where_condition]
    [GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]]
    [HAVING where_condition]
    [ORDER BY {col_name | expr | position} [ASC | DESC], ...]
    [LIMIT {[offset,] row_count | row_count OFFSET offset}]
    [PROCEDURE procedure_name(argument_list)]
    [INTO OUTFILE 'file_name' export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]
    [FOR UPDATE | LOCK IN SHARE MODE]]
 * 
		INTO OUTFILE '".$sql->out_file."'
			FIELDS TERMINATED BY ',' ENCLOSED BY '\"'
			LINES TERMINATED BY '\\r\\n';
 */
	$this->output = dirname( __FILE__ ). '/db-sync-tmp/'.'sync_db_'.session_id().'-'.$tbl.'.csv';

	if (file_exists($this->output)) {
		unlink($this->output);
	}

	$query = "select t.*
		from `".$tbl."` as t
		".$sql->out_where."
		".$sql->out_limit."
	";
	$res = DB::query( $query, false );


	$csv_sep = ',';
	$row_cols = array();
	while ($r = DB::fetch( $res )) {
		if (empty($row_cols)) {
			$row_cols = array_keys(get_object_vars($r));
			$this->write();
			$first = true;
			foreach ($row_cols as $field) {
				if ($first) {
					$first = false;
				} else {
					$this->write($csv_sep);
				}
				$this->write('"'.str_replace('"', '""', $field).'"');
			}//end foreachs
			$this->write("\n");
		}
		$first = true;
		foreach ($row_cols as $field) {
			if ($first) {
				$first = false;
			} else {
				$this->write($csv_sep);
			}
			$this->write('"'.str_replace('"', '""', $r->$field).'"');
		}//end foreach
		$this->write("\n");
	}
}


function task_show_tables() {
	$field = 'Tables_in_'."SES_USERS2";
	$sql = "show tables; ";
	$res = DB::query( $sql );
	while ($r = DB::fetch( $res )) {
		if (isset($r->$field)) {
			echo'<br />'. $r->$field;
			echo' <a href="'."?task=export_csv&tbl=".$r->$field.'">'."export cvs".'</a>';
		} else {
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">Unknown row=';print_r($r);echo'</pre>';
		}
	}
}


}// class
