<?php
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/auth.php';
dm_require_login();

$user = dm_user();
$input = json_decode(file_get_contents('php://input'), true);

if (!$pdo) { echo json_encode(['ok'=>false,'error'=>'Sin BD']); exit; }

$name = trim($input['name'] ?? '');
$pass = trim($input['password'] ?? '');
$pass2 = trim($input['password2'] ?? '');

if (!$name) { echo json_encode(['ok'=>false,'error'=>'El nombre es obligatorio']); exit; }

if ($pass) {
    if (strlen($pass) < 6) { echo json_encode(['ok'=>false,'error'=>'Contraseña mínimo 6 caracteres']); exit; }
    if ($pass !== $pass2) { echo json_encode(['ok'=>false,'error'=>'Las contraseñas no coinciden']); exit; }
    $hash = password_hash($pass, PASSWORD_BCRYPT);
    $pdo->prepare('UPDATE dm_users SET name=?, password=? WHERE id=?')->execute([$name, $hash, $user['id']]);
} else {
    $pdo->prepare('UPDATE dm_users SET name=? WHERE id=?')->execute([$name, $user['id']]);
}

$_SESSION['dm_name'] = $name;
dm_log($user['id'], null, 'update_profile', 'Perfil actualizado');
echo json_encode(['ok'=>true]);
