<?php
require_once __DIR__ . '/../auth/verifica.php';
require_once __DIR__ . '/../config/conexao.php';
$id = intval($_POST['id'] ?? 0);
$nome = trim($_POST['nome'] ?? '');
$email = trim($_POST['email'] ?? '');
$senha = $_POST['senha'] ?? '';
$nivel = trim($_POST['nivel'] ?? '');

if ($id > 0) {
    if ($senha !== '') {
        $hash = password_hash($senha, PASSWORD_DEFAULT);
        $pdo->prepare("UPDATE usuarios SET nome=:n, email=:e, senha=:s, nivel=:nv WHERE id=:id")->execute(['n'=>$nome,'e'=>$email,'s'=>$hash,'nv'=>$nivel,'id'=>$id]);
    } else {
        $pdo->prepare("UPDATE usuarios SET nome=:n, email=:e, nivel=:nv WHERE id=:id")->execute(['n'=>$nome,'e'=>$email,'nv'=>$nivel,'id'=>$id]);
    }
} else {
    $hash = password_hash($senha, PASSWORD_DEFAULT);
    $pdo->prepare("INSERT INTO usuarios (nome,email,senha,nivel) VALUES (:n,:e,:s,:nv)")->execute(['n'=>$nome,'e'=>$email,'s'=>$hash,'nv'=>$nivel]);
}
header("Location: usuarios.php"); exit;
