<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php'; // Para generar token al registrarse

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Obtener datos del body (JSON)
$data = json_decode(file_get_contents("php://input"));

if (!isset($data->username) || !isset($data->email) || !isset($data->password)) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing fields']);
    exit;
}

$username = trim($data->username);
$email = trim($data->email);
$password = $data->password;

// Validaciones básicas
if (strlen($username) < 3) {
    echo json_encode(['error' => 'Username must be at least 3 chars']);
    exit;
}

try {
    // 1. Verificar si existe en i_users
    $stmt = $pdo->prepare("SELECT iuid FROM i_users WHERE i_user_email = ? OR i_username = ?");
    $stmt->execute([$email, $username]);
    if ($stmt->fetch()) {
        http_response_code(409);
        echo json_encode(['error' => 'user_already_exists']);
        exit;
    }

    // 2. Crear usuario en i_users (Base de datos independiente klkapp_db)
    $password_hash = password_hash($password, PASSWORD_BCRYPT);
    $stmt = $pdo->prepare("INSERT INTO i_users (i_username, i_user_email, i_password, registered, uStatus) VALUES (?, ?, ?, ?, '1')");
    $registered_time = date('Y-m-d H:i:s');
    $stmt->execute([$username, $email, $password_hash, $registered_time]);

    $user_id = $pdo->lastInsertId();
    $token = Auth::generateToken($user_id);

    echo json_encode([
        'message' => 'User created successfully',
        'token' => $token,
        'user' => [
            'id' => $user_id,
            'username' => $username,
            'email' => $email,
            'avatar' => 'default.png',
            'diamonds' => 0
        ]
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'DB Error: ' . $e->getMessage()]);
}
?>
