<?php
include(dirname(__FILE__) . "/lib/common_include.php");
//パラメータの整形
//パラメータは
//db_id
//id[]
//table_name[]
//として入ってくるので、これを変形する。
//[
//	"id"=>id[i],
//	"name"=>table_name[i],
//	"order"=>i,
//]
//の形にする。

$id = null;
$names = [];
$errReq = null;
if( array_key_exists('db_id' , $_POST ) ){
	$id = $_POST['db_id'];
	if( !is_string($id) ){
		errLog('Post["db_id"] is not string');
		$errReq = CC\RES::RES_SYSERRORS['ILLEGAL_PARAM'];
	}
}else{
	$errReq = CC\RES::RES_SYSERRORS['ILLEGAL_PARAM'];
	errLog('Post["db_id"] is not Found');
}


$aryNames =[];
$aryIds =[];
$params = [ ];

if( array_key_exists('id' , $_POST ) ){
	$aryIds = $_POST[ 'id' ];
	if( !is_array($aryIds) ){
		errLog('Post["id"] is not array');
		$errReq = CC\RES::RES_SYSERRORS['ILLEGAL_PARAM'];
	}
}
if( array_key_exists( 'table_name' , $_POST ) ){
	$aryNames = $_POST[ 'table_name' ];
	if( !is_array($aryNames) ){
		errLog('Post["table_name"] is not array');
		$errReq = CC\RES::RES_SYSERRORS['ILLEGAL_PARAM'];
	}
}
if( $errReq == null){
	foreach( $aryIds as $idx => $tid ){
		if( !is_string($tid) && $tid !== null ){
			errLog('Post["id"]['.$idx.'] is not string');
			$errReq = CC\RES::RES_SYSERRORS['ILLEGAL_PARAM'];
			break;
		};
		if( $tid == '' ){
			$tid = null;
		}
		$params[ $idx ] = [ 'id' => $tid , 'name' => '' , 'order'=>$idx ];
	}
}
if( $errReq == null){
	foreach( $aryNames as $idx => $name ){
		if( !is_string($name) && $id !== null ){
			$errReq = CC\RES::RES_SYSERRORS['ILLEGAL_PARAM'];
			errLog('Post["table_name"]['.$idx.'] is not string');
			break;
		};
		if( mb_ereg("[\[\]\'\"]", $name) ){ 
			errLog('Post["table_name"]['.$idx.'] is ILLEGAL'."\t".'tableName:'.$name);
			return CC\RES::RES_SYSERRORS['ILLEGAL_PARAM'];
		};

		if( $name === null ){
			$name = '' ;
		}
		if( ! array_key_exists( $idx , $params) ){
			$params[ $idx ] = [ 'id' => null , 'name' => $name , 'order'=>$idx ];
		}
		$params[ $idx ][ 'name' ] = $name;
	};
}


if( $errReq == null){

	$db = new usrDb($id);
	if( ! $db->isEnable() ){
		$res = $db->error;
		errLog(
			'DB INITIALIZE ERROR'
		);
	}else{
		$res = $db->chgSysTbl( $params );
	};
	C\res($res);
}else{
	C\res($errReq);
}

