<?php
require_once __DIR__ . '/config.php';
$me = must_auth();
ensure_app_schema();

if ($_SERVER['REQUEST_METHOD']==='GET') {
    $t  = isset($_GET['username']) ? trim($_GET['username']) : $me;
    $st = db()->prepare("SELECT u.username,
               IF(u.display_name='',u.username,u.display_name) AS display_name,
               u.avatar,u.about,u.timezone,u.country,u.public_key,
               DATE_FORMAT(p.last_seen,'%Y-%m-%dT%H:%i:%sZ') AS last_seen,
               IF(p.last_seen>=DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 SECOND),1,0) AS online
        FROM users u
        LEFT JOIN presence p ON p.username=u.username
        WHERE u.username=? LIMIT 1");
    $st->execute(array($t)); $r=$st->fetch();
    if (!$r) fail('Not found',404);
    $r['online'] = (bool)$r['online'];
    $r['publicKey'] = $r['public_key'];
    unset($r['public_key']);
    ok($r);
}

if ($_SERVER['REQUEST_METHOD']==='POST') {
    $b = json_decode(file_get_contents('php://input'),true) ?: array();
    $up=array(); $pr=array();
    if (isset($b['displayName'])) {
        $dn = trim((string)$b['displayName']);
        if ($dn === '') fail('Display name cannot be empty');
        $up[]='display_name=?'; $pr[]=substr($dn,0,80);
    }
    if (isset($b['about']))     { $up[]='about=?';     $pr[]=substr(trim($b['about']),0,255); }
    if (isset($b['timezone']))  { $up[]='timezone=?';  $pr[]=substr(trim($b['timezone']),0,64); }
    if (isset($b['country']))   { $up[]='country=?';   $pr[]=strtoupper(substr(trim($b['country']),0,8)); }
    if (isset($b['publicKey'])&&$b['publicKey']!=='') { $up[]='public_key=?'; $pr[]=trim($b['publicKey']); }
    if (isset($b['keyBackup'])&&$b['keyBackup']!=='') { $up[]='key_backup=?'; $pr[]=trim($b['keyBackup']); }
    if (isset($b['keyBackupIv'])) { $up[]='key_backup_iv=?'; $pr[]=substr(trim($b['keyBackupIv']),0,64); }
    if ($up) { $pr[]=$me; db()->prepare("UPDATE users SET ".implode(',',$up)." WHERE username=?")->execute($pr); }
    if (isset($b['timezone']) || isset($b['country'])) {
        set_presence_location($me, isset($b['timezone'])?$b['timezone']:'', isset($b['country'])?$b['country']:'');
    }
    ok();
}
fail('Method not allowed',405);
