<?php
// =============================================================================
// /api/languages.php — translation strings per language.
//
// All strings for a language live as a single row keyed `lang_strings_<code>`
// with a JSON-encoded `{ key: value }` object as the value.
//
// GET                    → { languages: ['en','fr',...], default: 'en' }
// GET ?code=fr           → { code:'fr', strings: { _12_hour_format: '12h', ... } }
// POST action=save_lang  → { code, strings: {key:value, ...} }
// POST action=add_lang   → { code }
// POST action=delete_lang→ { code }   (cannot delete default 'en')
// =============================================================================
require_once __DIR__ . '/_common.php';
require_csrf_unless_get();

function lang_key($code) { return 'lang_strings_' . $code; }
function lang_codes() {
    $row = db_one('SELECT value FROM webview_settings WHERE key=?', ['lang_codes']);
    if (!$row || !$row['value']) return ['en','ar','fr','es','pt','tr','de','zh-cn','pl'];
    $parts = array_filter(array_map('trim', explode(',', $row['value'])));
    return $parts ?: ['en'];
}
function lang_codes_set(array $codes) {
    db_exec('INSERT INTO webview_settings (key, value, updated_at) VALUES (?, ?, ?)
             ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at',
            ['lang_codes', implode(',', $codes), time()]);
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $code = isset($_GET['code']) ? strtolower(preg_replace('/[^a-z0-9-]/i', '', (string)$_GET['code'])) : '';
    if ($code === '') {
        json_response(['languages' => lang_codes(), 'default' => 'en']);
    }
    $row = db_one('SELECT value FROM webview_settings WHERE key=?', [lang_key($code)]);
    $strings = $row ? json_decode($row['value'], true) : [];
    if (!is_array($strings)) $strings = [];
    json_response(['code' => $code, 'strings' => $strings]);
}

require_method('POST');
list($action, $body) = read_action();
$now = time();

if ($action === 'save_lang') {
    $code = strtolower(preg_replace('/[^a-z0-9-]/i', '', (string)($body['code'] ?? '')));
    if ($code === '') json_error('code required', 400);
    $strings = $body['strings'] ?? null;
    if (!is_array($strings)) json_error('strings object required', 400);
    db_exec('INSERT INTO webview_settings (key, value, updated_at) VALUES (?, ?, ?)
             ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at',
            [lang_key($code), json_encode($strings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), $now]);
    json_response(['ok' => true, 'count' => count($strings)]);
}

if ($action === 'add_lang') {
    $code = strtolower(preg_replace('/[^a-z0-9-]/i', '', (string)($body['code'] ?? '')));
    if ($code === '' || strlen($code) > 8) json_error('valid code required', 400);
    $codes = lang_codes();
    if (!in_array($code, $codes, true)) {
        $codes[] = $code;
        lang_codes_set($codes);
    }
    json_response(['ok' => true, 'codes' => $codes]);
}

if ($action === 'delete_lang') {
    $code = strtolower(preg_replace('/[^a-z0-9-]/i', '', (string)($body['code'] ?? '')));
    if ($code === '' || $code === 'en') json_error('cannot delete default', 400);
    $codes = array_values(array_filter(lang_codes(), fn($c) => $c !== $code));
    lang_codes_set($codes);
    db_exec('DELETE FROM webview_settings WHERE key=?', [lang_key($code)]);
    json_response(['ok' => true, 'codes' => $codes]);
}

json_error('unknown action', 400);
