<?php
class TranslationController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $languages = $db->fetchAll("SELECT * FROM sys_languages WHERE is_active = 1 ORDER BY sort_order");
        $groups = $db->fetchAll("SELECT DISTINCT translation_group FROM sys_translations ORDER BY translation_group");
        $this->view('translations/index', [
            'title' => lang('admin.translations'),
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/translations'], ['label' => lang('admin.translations')]],
            'languages' => $languages,
            'groups' => $groups,
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $langId = (int)$request->post('language_id', 1);
        $group = $request->post('group_filter', '');
        $search = trim($request->post('search')['value'] ?? '');

        $where = "t.language_id = ?";
        $params = [$langId];
        if ($group) { $where .= " AND t.translation_group = ?"; $params[] = $group; }
        if ($search !== '') { $where .= " AND (t.translation_key LIKE ? OR t.translation_value LIKE ?)"; $s = "%{$search}%"; $params[] = $s; $params[] = $s; }

        $rows = $db->fetchAll("SELECT * FROM sys_translations t WHERE {$where} ORDER BY t.translation_group, t.translation_key LIMIT 200", $params);
        $data = [];
        foreach ($rows as $r) {
            $data[] = [
                'id' => $r['id'],
                'group' => e($r['translation_group']),
                'key' => e($r['translation_key']),
                'value' => '<input type="text" class="form-control form-control-sm translation-input" data-id="' . $r['id'] . '" value="' . e($r['translation_value']) . '">',
            ];
        }
        $this->json(['draw' => (int)$request->post('draw', 1), 'recordsTotal' => count($data), 'recordsFiltered' => count($data), 'data' => $data]);
    }

    public function save(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $translations = $request->post('translations', []);
        $db = $this->db();
        $count = 0;
        foreach ($translations as $id => $value) {
            $db->update('sys_translations', ['translation_value' => $value, 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [(int)$id]);
            $count++;
        }
        $this->json(['success' => true, 'message' => "{$count} translations saved"]);
    }
}