<?php
ob_start();
session_start();

// ==================== تنظیمات ====================
$languages = [
    'arabic'    => ['name' => 'العربية',     'file' => 'arabic.json',    'dir' => 'rtl', 'lang' => 'ar'],
    'french'    => ['name' => 'Français',    'file' => 'french.json',    'dir' => 'ltr', 'lang' => 'fr'],
    'japanese'  => ['name' => '日本語',      'file' => 'japanese.json',  'dir' => 'ltr', 'lang' => 'ja'],
    'persian'   => ['name' => 'فارسی',       'file' => 'persian.json',   'dir' => 'rtl', 'lang' => 'fa'],
    'spanish'   => ['name' => 'Español',     'file' => 'spanish.json',   'dir' => 'ltr', 'lang' => 'es'],
    'turkish'   => ['name' => 'Türkçe',      'file' => 'turkish.json',   'dir' => 'ltr', 'lang' => 'tr'],
];

$current_lang = $_GET['lang'] ?? 'persian';
if (!isset($languages[$current_lang])) {
    $current_lang = 'persian';
}

$json_file = __DIR__ . "/languages/" . $languages[$current_lang]['file'];
$lang_dir  = $languages[$current_lang]['dir'];
$lang_code = $languages[$current_lang]['lang'];

// ==================== ترجمه‌های رابط ویرایشگر ====================
$ui = [
    'persian' => [
        'title'       => 'ویرایشگر ترجمه‌ها',
        'subtitle'    => 'مدیریت ترجمه‌های سامانه رولت',
        'key'         => 'نام کلید',
        'translation' => 'متن ترجمه',
        'save'        => 'ذخیره نهایی تغییرات'
    ],
    'arabic' => [
        'title'       => 'محرر الترجمات',
        'subtitle'    => 'إدارة ترجمات نظام الروليت',
        'key'         => 'اسم المفتاح',
        'translation' => 'النص المترجم',
        'save'        => 'حفظ التغييرات النهائية'
    ],
    'french' => [
        'title'       => 'Éditeur de traductions',
        'subtitle'    => 'Gestion des traductions du système de roulette',
        'key'         => 'Nom de la clé',
        'translation' => 'Texte traduit',
        'save'        => 'Enregistrer les modifications finales'
    ],
    'japanese' => [
        'title'       => '翻訳エディター',
        'subtitle'    => 'ルーレットシステムの翻訳管理',
        'key'         => 'キー名',
        'translation' => '翻訳テキスト',
        'save'        => '最終変更を保存'
    ],
    'spanish' => [
        'title'       => 'Editor de traducciones',
        'subtitle'    => 'Gestión de traducciones del sistema de ruleta',
        'key'         => 'Nombre de clave',
        'translation' => 'Texto traducido',
        'save'        => 'Guardar cambios finales'
    ],
    'turkish' => [
        'title'       => 'Çeviri Düzenleyici',
        'subtitle'    => 'Rulet sistemi çeviri yönetimi',
        'key'         => 'Anahtar Adı',
        'translation' => 'Çeviri Metni',
        'save'        => 'Değişiklikleri Kaydet'
    ]
];

$current_ui = $ui[$current_lang] ?? $ui['persian'];

// ==================== ذخیره تغییرات ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    $data = $_POST['translations'] ?? [];
    $json_data = [];
    foreach ($data as $key => $value) {
        if ($key !== '') {
            $json_data[$key] = $value;
        }
    }
    
    if (file_put_contents($json_file, json_encode($json_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))) {
        $success = "✅ ترجمه‌ها با موفقیت ذخیره شدند.";
    } else {
        $error = "❌ خطا در ذخیره فایل.";
    }
}

// بارگذاری ترجمه‌ها
$translations = [];
if (file_exists($json_file)) {
    $translations = json_decode(file_get_contents($json_file), true) ?: [];
}
?>

<!DOCTYPE html>
<html lang="<?= $lang_code ?>" dir="<?= $lang_dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="icon" type="image/png" href="chip.png">
    <link rel="stylesheet" href="style.css">
    <title><?= $current_ui['title'] ?> - Roulette</title>
    <style>
        * { margin:0; padding:0; box-sizing:border-box; }
        html, body, button, input {
            background: #0b0c10;
            color: #f3f4f6;
            font-family: "Noto Sans Arabic", "Noto Sans", system-ui, -apple-system, sans-serif;
        }
        .container {
            max-width: 1300px;
            margin: 0 auto;
            padding: 1.5rem;
        }
        .header {
            text-align: center;
            margin-bottom: 2rem;
        }
        .header h1 {
            color: #eab308;
            font-size: 2rem;
        }
        .lang-selector {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            justify-content: center;
            margin-bottom: 2rem;
        }
        .lang-btn {
            padding: 12px 22px;
            background: #12141c;
            border: 1px solid #1f2937;
            color: #f3f4f6;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 1.1rem;
            text-decoration: none;
        }
        .lang-btn:hover { border-color: #eab308; }
        .lang-btn.active {
            background: #eab308;
            color: #0b0c10;
            border-color: #eab308;
            font-weight: bold;
        }
        .card {
            background: #12141c;
            border: 1px solid #1f2937;
            border-radius: 1rem;
            padding: 1.5rem;
            box-shadow: 0 10px 25px rgba(0,0,0,0.35);
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 14px 12px;
            text-align: right;
            border-bottom: 1px solid #1f2937;
        }
        th {
            background: #1a1d28;
            color: #eab308;
            font-weight: 700;
        }
        td.key {
            font-family: monospace;
            color: #9ca3af;
            width: 38%;
        }
        td input {
            width: 100%;
            background: #191c26;
            border: 1px solid #374151;
            border-radius: 0.75rem;
            padding: 12px;
            color: #f3f4f6;
            font-size: 1rem;
        }
        td input:focus {
            border-color: #eab308;
            outline: none;
        }
        .save-btn {
            margin-top: 25px;
            width: 100%;
            padding: 16px;
            background: #16a34a;
            color: white;
            border: none;
            border-radius: 0.75rem;
            font-size: 1.2rem;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        .save-btn:hover {
            background: #22c55e;
        }
        .alert {
            padding: 14px;
            border-radius: 0.75rem;
            margin: 15px 0;
            text-align: center;
        }
        .success { background: #166534; color: #86efac; }
        .error   { background: #7f1d1d; color: #fda4af; }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h1><?= $current_ui['title'] ?></h1>
        <p><?= $current_ui['subtitle'] ?></p>
    </div>

    <!-- انتخاب زبان -->
    <div class="lang-selector">
        <?php foreach ($languages as $key => $info): ?>
            <a href="?lang=<?= $key ?>" class="lang-btn <?= $current_lang === $key ? 'active' : '' ?>">
                <?= $info['name'] ?>
            </a>
        <?php endforeach; ?>
    </div>

    <div class="card">
        <?php if (isset($success)): ?>
            <div class="alert success"><?= $success ?></div>
        <?php endif; ?>
        <?php if (isset($error)): ?>
            <div class="alert error"><?= $error ?></div>
        <?php endif; ?>

        <form method="post">
            <table>
                <thead>
                    <tr>
                        <th><?= $current_ui['key'] ?></th>
                        <th><?= $current_ui['translation'] ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($translations as $key => $value): ?>
                    <tr>
                        <td class="key"><?= htmlspecialchars($key) ?></td>
                        <td>
                            <input type="text" 
                                   name="translations[<?= htmlspecialchars($key) ?>]" 
                                   value="<?= htmlspecialchars($value) ?>" 
                                   dir="<?= $lang_dir ?>">
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <button type="submit" name="save" class="save-btn">
                <?= $current_ui['save'] ?>
            </button>
        </form>
    </div>
</div>

</body>
</html>