<?php
session_start();
if(!isset($_SESSION['id'])){
    header("Location: ../index.php");
    exit();
}

include("../conexion.php");

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nombre = isset($_POST['nombre']) ? mysqli_real_escape_string($conexion, $_POST['nombre']) : '';
    $email = isset($_POST['email']) ? mysqli_real_escape_string($conexion, $_POST['email']) : '';
    $edad = isset($_POST['edad']) ? intval($_POST['edad']) : 0;
    $password = isset($_POST['password']) ? $_POST['password'] : '';

    if(empty($nombre) || empty($email) || empty($password) || $edad <= 0) {
        header("Location: ../menu.php?page=usuarios&error=campos_vacios");
        exit();
    }

    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header("Location: ../menu.php?page=usuarios&error=email_invalido");
        exit();
    }

    $password_hash = password_hash($password, PASSWORD_DEFAULT);

    $check_sql = "SELECT id FROM usuarios WHERE email = '$email'";
    $check_result = mysqli_query($conexion, $check_sql);
    
    if(mysqli_num_rows($check_result) > 0){
        header("Location: ../menu.php?page=usuarios&error=email_existente");
        exit();
    }

    $sql = "INSERT INTO usuarios (nombre, email, edad, password) 
            VALUES ('$nombre', '$email', '$edad', '$password_hash')";
    
    if(mysqli_query($conexion, $sql)){
        header("Location: ../menu.php?page=usuarios&success=creado");
    } else {
        echo "Error SQL: " . mysqli_error($conexion);
    }
} else {
    header("Location: ../menu.php?page=usuarios");
}

mysqli_close($conexion);
exit();
?>