<?php
require_once __DIR__ . '/config.php';
ensure_app_schema();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') fail('POST required', 405);

// Parse body
$body = json_decode(file_get_contents('php://input'), true);
if (!is_array($body)) fail('Invalid JSON body');

$u  = isset($body['username'])     ? trim($body['username'])     : '';
$dn = isset($body['displayName'])  ? trim($body['displayName'])  : '';
$pw = isset($body['password'])     ? $body['password']           : '';
$pk = isset($body['publicKey'])    ? trim($body['publicKey'])    : '';
$kb = isset($body['keyBackup'])    ? trim($body['keyBackup'])    : '';
$ki = isset($body['keyBackupIv'])  ? trim($body['keyBackupIv'])  : '';
$tz = isset($body['timezone'])     ? trim($body['timezone'])     : '';
$ct = isset($body['country'])      ? trim($body['country'])      : '';

// Validate
if ($u === '')  fail('Username is required');
if ($pw === '') fail('Password is required');
if ($pk === '') fail('Public key is required');
if (!preg_match('/^[a-zA-Z0-9_]{3,30}$/', $u))
    fail('Username must be 3-30 characters: letters, numbers, underscore only');
if (strlen($pw) < 6)
    fail('Password must be at least 6 characters');
if ($dn === '') $dn = $u;
$dn = substr($dn, 0, 80);

$db = db();

// Check if username taken
$st = $db->prepare('SELECT id FROM users WHERE username = ? LIMIT 1');
$st->execute(array($u));
if ($st->fetch()) fail('Username already taken — please choose another');

// Insert user. Username remains the login identity; display_name is the renameable label.
$hash = password_hash($pw, PASSWORD_BCRYPT, array('cost' => 10));
$db->prepare('INSERT INTO users (username, display_name, password, public_key, key_backup, key_backup_iv, timezone, country) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
   ->execute(array($u, $dn, $hash, $pk, ($kb !== '' ? $kb : null), substr($ki,0,64), substr($tz,0,64), strtoupper(substr($ct,0,8))));

try {
    if ($tz !== '' || $ct !== '') set_presence_location($u, $tz, $ct);
    else touch_presence($u);
} catch (Exception $e) {}

ok(array('username' => $u, 'display_name' => $dn, 'message' => 'Account created'));
