<?php
include_once ("conn.php");

date_default_timezone_set("America/Panama");
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING );

$_SESSION['database'] = $_POST['database'];
$_SESSION['campo'] = $_POST['campo'];
$_SESSION['valor'] = $_POST['valor'];

$cCampo = $_SESSION['campo'];
$cValue = $_SESSION['valor'];
$cGuarda = $_SESSION['guardar'];

$db = $_SESSION['database'];

/*
$db       = 'facilmatriz';
$cCampo   = 'cod_fam';
$cValue   = '1';
*/

$cmd = 'SELECT '.$cCampo.'_long AS cFValue FROM '.$db.'.empresas LIMIT 1';
$qry = mysqli_query($connection,$cmd);
$row = mysqli_fetch_row($qry);
$iLon= $row[0];
mysqli_free_result($qry);

if($cCampo === 'cod_fam')
{
	$cTable = $db.'.familia';
	$cField = 'f_id';
}

if($cCampo === 'cod_marc')
{
	$cTable = $db.'.marcas';
	$cField = 'id_marca';
}

if($cCampo === 'cod_fab')
{
	$cTable = $db.'.fabricantes';
	$cField = 'fab_id';
}

if($cCampo === 'cod_pers')
{
	$cTable = $db.'.personal';
	$cField = 'pers_id';
}

if($cCampo === 'cod_prod')
{
	$cTable = $db.'.productos';
	$cField = 'pr_id';
}

if($cCampo === 'cod_client')
{
	$cTable = $db.'.clientes';
	$cField = 'c_id';
}

if($cCampo === 'cod_prov')
{
	$cTable = $db.'.proveedores';
	$cField = 'p_id';
}

if ($cValue=-1)
{
	$cmd = 'SELECT MAX('.$cField.') FROM '.$cTable.' WHERE 1=1';
	if ($qry = mysqli_query($connection, $cmd))
	{
		$row = mysqli_fetch_row($qry);
		$cValue= $row[0];
		$qry->close();
	}
	else
	{
		$msg = array("value" => "false");
		print_r(json_encode($msg));
		exit();
	}
}

$control = exists_value($cField, $cValue, $cTable);
do{
	if($control === false)
	{
		$cValue = $cValue + 1;
		$control = exists_value($cField, $cValue, $cTable);
	}
	else
		break;
} while(0);

if (cGuarda==='1')
{
	$cmd = 'UPDATE '.$db.'.empresas SET '.$cCampo.'_valor="'.$cValue.'" LIMIT 1';
	if ($qry = mysqli_query($connection, $cmd))
	{
	
	}
	else
	{
		$msg = array("value" => "false");
		print_r(json_encode($msg));
		exit();
	}
	
}
$msg = pad_value($cValue,$iLon);
print_r(json_encode($msg));
 
@mysqli_close($connection);

function pad_value($pValue, $pLen)
{
	if(pLen === 0)
		$Result = array("value" => $pValue);
	else
		$Result = array("value" =>str_pad($pValue, $pLen, '0', STR_PAD_LEFT));
	return 	$Result;
}

function exists_value($pField, $pValue, $pTable)
{
	$cmd = 'SELECT '.$pField.' FROM '.$pTable.' WHERE '.$pField.'='.$pValue;

	if ($result = mysqli_query($connection, $cmd)) {
		return true;
	}
	else{
		
		return false;
	}
	$result->close();
}

?>