<?php
include('is_logged.php');

// Recibimos el ID y lo limpiamos
$user_id = (isset($_POST['mod_id'])) ? intval($_POST['mod_id']) : 0;

if ($user_id == 0) {
    $errors[] = "Error Crítico: El servidor no recibió el ID del usuario.";
else if (
    !empty($_POST['firstname2']) &&
    !empty($_POST['lastname2']) &&
    !empty($_POST['user_name2'])
){
    require_once ("../config/db.php");
    require_once ("../config/conexion.php");

    $firstname = mysqli_real_escape_string($con,(strip_tags($_POST["firstname2"],ENT_QUOTES)));
    $lastname = mysqli_real_escape_string($con,(strip_tags($_POST["lastname2"],ENT_QUOTES)));
    $user_name = mysqli_real_escape_string($con,(strip_tags($_POST["user_name2"],ENT_QUOTES)));
    $user_email = mysqli_real_escape_string($con,(strip_tags($_POST["user_email2"],ENT_QUOTES)));
    $rol = mysqli_real_escape_string($con,(strip_tags($_POST["rol2"],ENT_QUOTES)));
    $estado = mysqli_real_escape_string($con,(strip_tags($_POST["estado2"],ENT_QUOTES)));

    $sql = "UPDATE users SET firstname='".$firstname."', lastname='".$lastname."', user_name='".$user_name."', user_email='".$user_email."', ROL='".$rol."', estado='".$estado."' WHERE user_id='".$user_id."'";
    
    $query_update = mysqli_query($con,$sql);

    if ($query_update){
        $messages[] = "Usuario actualizado correctamente.";
    } else {
        $errors[] = "Error en base de datos: ".mysqli_error($con);
    }
} else {
    $errors[] = "Faltan campos obligatorios (Nombres, Apellidos o Usuario).";
}

// Imprimir Errores
if (isset($errors)){
    ?>
    <div class="alert alert-danger" role="alert">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <strong>Error!</strong> <?php foreach ($errors as $error) { echo $error; } ?>
    </div>
    <?php
}
// Imprimir Mensajes
if (isset($messages)){
    ?>
    <div class="alert alert-success" role="alert">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <strong>¡Listo!</strong> <?php foreach ($messages as $message) { echo $message; } ?>
    </div>
    <?php
}
?>