<?php
session_start();
require_once '../connect.php';
if (!isset($_SESSION['user_id'])) { jsonResponse(false, 'Unauthorized'); }
$account_id = (int)($_SESSION['account_id'] ?? 0);
$user_id = (int)($_SESSION['user_id'] ?? 0);
if (!currentUserIsAdmin($conn) && !userCan($conn, 'settings', 'tab_languages')) { jsonResponse(false, 'Unauthorized'); }

$action = $_POST['action'] ?? $_GET['action'] ?? '';

if ($action === 'add_language') {
    $code = preg_replace('/[^a-zA-Z0-9_-]/', '', $_POST['code'] ?? '');
    $name = trim($_POST['name'] ?? '');
    $direction = ($_POST['direction'] ?? 'ltr') === 'rtl' ? 'rtl' : 'ltr';
    if (!$code || !$name) jsonResponse(false, 'Language code and name are required');
    $ec = $conn->real_escape_string($code);
    $en = $conn->real_escape_string($name);
    $ed = $conn->real_escape_string($direction);
    $conn->query("INSERT INTO languages (code,name,direction,status,is_default) VALUES ('$ec','$en','$ed',1,0) ON DUPLICATE KEY UPDATE name=VALUES(name), direction=VALUES(direction), status=1");
    $conn->query("INSERT IGNORE INTO translations (language_id, key_id, value) SELECT l.id, tk.id, '' FROM languages l JOIN translation_keys tk WHERE l.code='$ec'");
    jsonResponse(true, 'Language saved');
}

if ($action === 'update_language') {
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $direction = ($_POST['direction'] ?? 'ltr') === 'rtl' ? 'rtl' : 'ltr';
    $status = (int)($_POST['status'] ?? 1) ? 1 : 0;
    if (!$id || !$name) jsonResponse(false, 'Language not found');
    $en = $conn->real_escape_string($name);
    $ed = $conn->real_escape_string($direction);
    $conn->query("UPDATE languages SET name='$en', direction='$ed', status=$status WHERE id=$id");
    jsonResponse(true, 'Language updated');
}

if ($action === 'set_default') {
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) jsonResponse(false, 'Language not found');
    $conn->query("UPDATE languages SET is_default=0");
    $conn->query("UPDATE languages SET is_default=1, status=1 WHERE id=$id");
    $q = $conn->query("SELECT code FROM languages WHERE id=$id LIMIT 1");
    if ($q && $q->num_rows && columnExists($conn, 'accounts', 'default_language_code')) {
        $code = $conn->real_escape_string($q->fetch_assoc()['code']);
        $conn->query("UPDATE accounts SET default_language_code='$code' WHERE id=$account_id");
    }
    jsonResponse(true, 'Default language updated');
}

if ($action === 'save_translations') {
    $language_id = (int)($_POST['language_id'] ?? 0);
    $values = $_POST['translations'] ?? [];
    if (!$language_id) jsonResponse(false, 'Language not found');
    foreach ($values as $keyId => $value) {
        $keyId = (int)$keyId;
        $value = $conn->real_escape_string((string)$value);
        if ($keyId > 0) {
            $conn->query("INSERT INTO translations (language_id,key_id,value) VALUES ($language_id,$keyId,'$value') ON DUPLICATE KEY UPDATE value=VALUES(value)");
        }
    }
    jsonResponse(true, 'Translations saved');
}

if ($action === 'add_key') {
    $key = trim($_POST['key'] ?? '');
    $fallback = trim($_POST['fallback'] ?? '');
    $group = trim($_POST['group_name'] ?? 'custom');
    if (!$key || !$fallback) jsonResponse(false, 'Key and fallback are required');
    crmRegisterTranslationKey($conn, $key, $fallback, $group ?: 'custom');
    $conn->query("INSERT IGNORE INTO translations (language_id, key_id, value) SELECT l.id, tk.id, '' FROM languages l JOIN translation_keys tk WHERE tk.`key`='".$conn->real_escape_string($key)."'");
    jsonResponse(true, 'Translation key added');
}

jsonResponse(false, 'Invalid action');
