<?php
ob_start();
require_once '../config.php';
ob_clean();
header('Content-Type: application/json; charset=utf-8');

try {
    $input = json_decode(file_get_contents('php://input'), true);
    $user = trim($input['user'] ?? '');
    $pass = trim($input['pass'] ?? '');

    if (empty($user) || empty($pass)) {
        throw new Exception("Datos incompletos");
    }

    $pdo = getDBConnection();
    if (!$pdo)
        throw new Exception("Error DB");

    // Check existing
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = :user");
    $stmt->execute([':user' => $user]);
    if ($stmt->fetchColumn() > 0) {
        throw new Exception("El usuario ya existe");
    }

    // Insert pending
    $passHash = password_hash($pass, PASSWORD_DEFAULT);
    $stmt = $pdo->prepare("INSERT INTO users (username, password, role, status) VALUES (:user, :pass, 'user', 'pending')");
    $stmt->execute([':user' => $user, ':pass' => $passHash]);

    echo json_encode(['success' => true]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
exit;
?>