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

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

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

$u  = isset($body['username'])  ? trim($body['username'])  : '';
$pw = isset($body['password'])  ? $body['password']        : '';
$tz = isset($body['timezone'])  ? trim($body['timezone'])  : '';
$ct = isset($body['country'])   ? trim($body['country'])   : '';

if ($u === '')  fail('Username is required');
if ($pw === '') fail('Password is required');

$db = db();
$st = $db->prepare('SELECT * FROM users WHERE username = ? LIMIT 1');
$st->execute(array($u));
$row = $st->fetch();

if (!$row)                              fail('Incorrect username or password', 401);
if (!password_verify($pw, $row['password'])) fail('Incorrect username or password', 401);

// Update presence + optional browser-detected timezone/country in UTC-safe form.
try {
    if ($tz !== '' || $ct !== '') set_presence_location($u, $tz, $ct);
    else touch_presence($u);
} catch (Exception $e) {}

ok(array(
    'token'        => make_token($u),
    'username'     => $u,
    'display_name' => ($row['display_name'] !== '' ? $row['display_name'] : $u),
    'avatar'       => $row['avatar'],
    'about'        => $row['about'],
    'timezone'     => isset($row['timezone']) ? $row['timezone'] : '',
    'country'      => isset($row['country']) ? $row['country'] : '',
    'publicKey'    => $row['public_key'],
    'keyBackup'    => isset($row['key_backup']) ? $row['key_backup'] : null,
    'keyBackupIv'  => isset($row['key_backup_iv']) ? $row['key_backup_iv'] : ''
));
