<?php 
/** Script para la creación de un perfil nuevo
 *  Los perfiles vienen reflejados con la tabla USUARIOS_GRUPOS
 *  No se devuelve nada. Si la consulta falla se controla con excepciones. 
 */
session_start();
$usuarioSession = $_SESSION['USUARIO'];
$grupo = $_SESSION['GRUPO'];
$contacto = $_SESSION['CONTACTO'];
$awa_session_id = $_SESSION['AWA_SESION_ID'];

include('../lg/config_vo.php');
include('../includes/conex.php');
include('../includes/eat.php');
include('../class/Schema.php');

$cookieUser = filter_input(INPUT_COOKIE, 'usuario') ?? null; 
$cookieIdioma = filter_input(INPUT_COOKIE, 'idioma') ?? null; 
if((!isset($usuarioSession) or $awa_session_id != $awa_id) or (isset($cookieUser) AND $cookieUser != $staticUsu )){
    eatCookies();
    header('Location:../index.php');}
empty($cookieIdioma)?
    include('../lg/LG_' . $cookieIdioma . '.php'):
    include('../lg/LG_SP.php');

$nuevoperfil    = filter_input(INPUT_POST, 'nuevoperfil') ?? null;
try{
    if ($nuevoperfil === null ) { throw new Exception("Es necesario aportar un nombre");}
    
    $query = "SELECT MAX(CODIGO) as MAXCOD FROM USUARIOS_GRUPOS";
    $rescodigo = $con->query($query)->fetch_assoc();
    $codigoperfil = (int)$rescodigo["MAXCOD"] + 1 ;
    
    $query2 = "SELECT count(*) as REPETIDOS FROM USUARIOS_GRUPOS WHERE DESCRIPCION LIKE '".$nuevoperfil."'";
    $resrepetidos = $con->query($query2)->fetch_assoc();
    if ((int)$resrepetidos["REPETIDOS"] >= 1 ) { throw new Exception("Ese nombre ya está asignado a un perfil, has de emplear otro nombre");}
    
    $currdate =  date("Y-m-d H:i:s");
    
    $query3 = "INSERT INTO USUARIOS_GRUPOS (CODIGO, DESCRIPCION, ACTIVO, ALTA) VALUES ( ? , ? , 1, ? )";
    $stmt = $con->prepare($query3);
    $stmt->bind_param('iss', $codigoperfil, $nuevoperfil, $currdate );
    $stmt->execute();
    
} catch (Exception $ex) {
    echo "twb_".$ex->getMessage(). "En la linea : ". $ex->getLine();return;
} catch (Throwable $twb) {
    echo "twb_".$twb->getMessage(). "En la linea : ". $twb->getLine();return;
} finally {
    $con->close();
}
