<?php

function dataGetDescriptions($p = null) {
    $user = requireAuth();
    requireSubscription($user);

    [$singles, $freqs, $combos, $nodeCombs, $tiangan] = [
        query('SELECT * FROM single_nodes ORDER BY node, val'),
        query('SELECT * FROM freq_rules ORDER BY num, cnt'),
        query('SELECT * FROM combo_rules ORDER BY id'),
        query('SELECT * FROM node_comb_rules ORDER BY val'),
        query('SELECT * FROM tiangan_desc ORDER BY num'),
    ];

    respond([
        'singleNodes' => array_map(fn($r) => [
            'id'=>$r['id'],'node'=>$r['node'],'val'=>$r['val'],
            'desc'=>['en'=>$r['desc_en'],'ms'=>$r['desc_ms'],'zh'=>$r['desc_zh']],
            'sensDesc'=>['en'=>$r['sens_en'],'ms'=>$r['sens_ms'],'zh'=>$r['sens_zh']],
        ], $singles),
        'freqRules' => array_map(fn($r) => [
            'id'=>$r['id'],'num'=>$r['num'],'cnt'=>$r['cnt'],
            'desc'=>['en'=>$r['desc_en'],'ms'=>$r['desc_ms'],'zh'=>$r['desc_zh']],
            'sensDesc'=>['en'=>$r['sens_en'],'ms'=>$r['sens_ms'],'zh'=>$r['sens_zh']],
        ], $freqs),
        'comboRules' => array_map(fn($r) => [
            'id'=>$r['id'],'combo'=>$r['combo'],
            'groups'=>json_decode($r['groups_json'],true)??[],
            'desc'=>['en'=>$r['desc_en'],'ms'=>$r['desc_ms'],'zh'=>$r['desc_zh']],
            'sensDesc'=>['en'=>$r['sens_en'],'ms'=>$r['sens_ms'],'zh'=>$r['sens_zh']],
        ], $combos),
        'nodeCombRules' => array_map(fn($r) => [
            'id'=>$r['id'],'val'=>$r['val'],
            'pairs'=>json_decode($r['pairs_json'],true)??[],
            'desc'=>['en'=>$r['desc_en'],'ms'=>$r['desc_ms'],'zh'=>$r['desc_zh']],
            'sensDesc'=>['en'=>$r['sens_en'],'ms'=>$r['sens_ms'],'zh'=>$r['sens_zh']],
        ], $nodeCombs),
        'tianganDesc' => array_map(fn($r) => [
            'id'=>$r['id'],'tg'=>$r['tg'],'num'=>$r['num'],
            'desc'=>['en'=>$r['desc_en'],'ms'=>$r['desc_ms'],'zh'=>$r['desc_zh']],
            'sensDesc'=>['en'=>$r['sens_en'],'ms'=>$r['sens_ms'],'zh'=>$r['sens_zh']],
        ], $tiangan),
    ]);
}

function dataGetLanguages($p = null) {
    $rows   = query('SELECT lang, lang_key, lang_value FROM language_strings');
    $result = [];
    foreach ($rows as $r) {
        $val = json_decode($r['lang_value'], true);
        $result[$r['lang']][$r['lang_key']] = $val !== null ? $val : $r['lang_value'];
    }
    respond($result);
}

function dataSaveDescriptions($p = null) {
    $user = requireAuth();
    if (!in_array($user['role'], ['admin','super_admin'], true)) error('Admin only', 403);
    $body = getBody();

    foreach ($body['singleNodes'] ?? [] as $r) {
        $d = $r['desc'] ?? []; $s = $r['sensDesc'] ?? [];
        if (!empty($r['id'])) {
            execute('UPDATE single_nodes SET node=?,val=?,desc_en=?,desc_ms=?,desc_zh=?,sens_en=?,sens_ms=?,sens_zh=? WHERE id=?',
                [$r['node'],$r['val'],$d['en']??'',$d['ms']??'',$d['zh']??'',$s['en']??'',$s['ms']??'',$s['zh']??'',$r['id']]);
        } else {
            execute('INSERT INTO single_nodes (node,val,desc_en,desc_ms,desc_zh,sens_en,sens_ms,sens_zh) VALUES (?,?,?,?,?,?,?,?)',
                [$r['node'],$r['val'],$d['en']??'',$d['ms']??'',$d['zh']??'',$s['en']??'',$s['ms']??'',$s['zh']??'']);
        }
    }
    foreach ($body['freqRules'] ?? [] as $r) {
        $d = $r['desc'] ?? []; $s = $r['sensDesc'] ?? [];
        if (!empty($r['id'])) {
            execute('UPDATE freq_rules SET num=?,cnt=?,desc_en=?,desc_ms=?,desc_zh=?,sens_en=?,sens_ms=?,sens_zh=? WHERE id=?',
                [$r['num'],$r['cnt'],$d['en']??'',$d['ms']??'',$d['zh']??'',$s['en']??'',$s['ms']??'',$s['zh']??'',$r['id']]);
        } else {
            execute('INSERT INTO freq_rules (num,cnt,desc_en,desc_ms,desc_zh,sens_en,sens_ms,sens_zh) VALUES (?,?,?,?,?,?,?,?)',
                [$r['num'],$r['cnt'],$d['en']??'',$d['ms']??'',$d['zh']??'',$s['en']??'',$s['ms']??'',$s['zh']??'']);
        }
    }
    foreach ($body['comboRules'] ?? [] as $r) {
        $d = $r['desc'] ?? []; $s = $r['sensDesc'] ?? [];
        $gj = json_encode($r['groups'] ?? []);
        if (!empty($r['id'])) {
            execute('UPDATE combo_rules SET combo=?,groups_json=?,desc_en=?,desc_ms=?,desc_zh=?,sens_en=?,sens_ms=?,sens_zh=? WHERE id=?',
                [$r['combo'],$gj,$d['en']??'',$d['ms']??'',$d['zh']??'',$s['en']??'',$s['ms']??'',$s['zh']??'',$r['id']]);
        } else {
            execute('INSERT INTO combo_rules (combo,groups_json,desc_en,desc_ms,desc_zh,sens_en,sens_ms,sens_zh) VALUES (?,?,?,?,?,?,?,?)',
                [$r['combo'],$gj,$d['en']??'',$d['ms']??'',$d['zh']??'',$s['en']??'',$s['ms']??'',$s['zh']??'']);
        }
    }
    foreach ($body['nodeCombRules'] ?? [] as $r) {
        $d = $r['desc'] ?? []; $s = $r['sensDesc'] ?? [];
        $pj = json_encode($r['pairs'] ?? []);
        if (!empty($r['id'])) {
            execute('UPDATE node_comb_rules SET pairs_json=?,val=?,desc_en=?,desc_ms=?,desc_zh=?,sens_en=?,sens_ms=?,sens_zh=? WHERE id=?',
                [$pj,$r['val'],$d['en']??'',$d['ms']??'',$d['zh']??'',$s['en']??'',$s['ms']??'',$s['zh']??'',$r['id']]);
        } else {
            execute('INSERT INTO node_comb_rules (pairs_json,val,desc_en,desc_ms,desc_zh,sens_en,sens_ms,sens_zh) VALUES (?,?,?,?,?,?,?,?)',
                [$pj,$r['val'],$d['en']??'',$d['ms']??'',$d['zh']??'',$s['en']??'',$s['ms']??'',$s['zh']??'']);
        }
    }
    foreach ($body['tianganDesc'] ?? [] as $r) {
        $d = $r['desc'] ?? []; $s = $r['sensDesc'] ?? [];
        execute('UPDATE tiangan_desc SET desc_en=?,desc_ms=?,desc_zh=?,sens_en=?,sens_ms=?,sens_zh=? WHERE tg=?',
            [$d['en']??'',$d['ms']??'',$d['zh']??'',$s['en']??'',$s['ms']??'',$s['zh']??'',$r['tg']]);
    }
    respond(['message' => 'Descriptions saved']);
}

function dataDeleteDescription($params = null) {
    requireAdmin();
    [$table, $id] = is_array($params) ? $params : [null, null];
    $allowed = ['single_nodes','freq_rules','combo_rules','node_comb_rules','tiangan_desc'];
    if (!in_array($table, $allowed)) error('Invalid table');
    execute("DELETE FROM $table WHERE id=?", [$id]);
    respond(['message' => 'Deleted']);
}

function dataSaveLanguages($p = null) {
    requireAdmin();
    $langs = getBody();
    foreach ($langs as $lang => $keys) {
        foreach ($keys as $k => $v) {
            $val = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : (string)$v;
            execute('INSERT INTO language_strings (lang,lang_key,lang_value) VALUES (?,?,?) ON DUPLICATE KEY UPDATE lang_value=VALUES(lang_value)',
                [$lang, $k, $val]);
        }
    }
    respond(['message' => 'Languages saved']);
}
