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

if (! $connection = connectDb()) {
    die("err db");
} else {
    $connection->query("SET NAMES 'utf8';");
}
;

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'];
$_SESSION['guardar'] = $_POST['guardar'];

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

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

$Sql = 'SELECT ' . $cCampo . '_long AS Value  FROM ' . $db . '.empresas LIMIT 1';
$data = getRow($connection, $Sql, $recount, false);
$iLon = $data['Value'];

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 (is_numeric($cValue) == true) {
    
    $cValue = corre_mante($connection, $cCampo, $db);
    
    $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=' . $cCampo . '_valor+1 WHERE emp_id=1 LIMIT 1';
        $resp = update_Sql($connection, $cmd);
        if ($resp == false) {
            $msg = array(
                "value" => $cValue
            );
            print_r(json_encode($msg));
            exit();
        }
    }
    
    if ($cCampo === 'cod_client') {
        
        $resval = 10000 + str_pad($cValue, $iLon, "0", STR_PAD_LEFT);
    } else {
        $resval = str_pad($cValue, $iLon, "0", STR_PAD_LEFT);
    }
    
    $msg = array(
        "value" => $resval
    );
}

print_r(json_encode($msg));

@mysqli_close($connection);
exit();

function corre_mante($pconn, $cCampo, $pdb)
{
    $cCampo = trim($cCampo);
    $Sql = 'SELECT ' . $cCampo . '_auto AS Value FROM ' . $pdb . '.empresas LIMIT 1';
    $data = getRow($pconn, $Sql, $recount, false);
    $autoinc = $data['Value'];
    if ($autoinc == '1') {
        $Sql = 'SELECT (' . $cCampo . '_valor + 1) AS Value FROM ' . $pdb . '.empresas LIMIT 1';
        $data = getRow($pconn, $Sql, $recount, false);
        $cCodigo = trim($data['Value']);
        
        $Sql = 'SELECT ' . $cCampo . '_long AS Value  FROM ' . $pdb . '.empresas LIMIT 1';
        $data = getRow($pconn, $Sql, $recount, false);
        $nLon = $data['Value'];
        if ($nLon == 0) {
            $result = trim($cCodigo);
        } else {
            $result = str_pad(trim($cCodigo), $nLon, "0", STR_PAD_LEFT);
        }
    } else {
        $result = '';
    }
    return $result;
}
;

function pad_value($pValue, $pLen, $pSuc = '')
{
    if ($pLen == 0)
        $Result = array(
            "value" => $pValue
        );
    else
        $Result = array(
            "value" => ($pSuc == '' ? 1 : 10000) + 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();
}
;

?>