<?php
// ---------------- تنظیمات دیتابیس ----------------
$host = "localhost";
$db   = "tabrizli_arkbam";
$user = "tabrizli_arkbamuser";
$pass = "01478520Mi!!";
$charset = "utf8mb4";

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("خطا در اتصال: " . $e->getMessage());
}

session_start();

// ---------------- صفحه فعال ----------------
$page = $_GET['page'] ?? 'home';

// ---------------- عملیات ذخیره زبان ----------------
if ($page === 'languages' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("INSERT INTO languages (code, name) VALUES (?, ?)");
    $stmt->execute([$_POST['code'], $_POST['name']]);
    header("Location: index.php?page=languages");
    exit;
}

// ---------------- عملیات ذخیره ترجمه ----------------
if ($page === 'translations' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("INSERT INTO translations (language_id, `group`, `key`, `value`) VALUES (?, ?, ?, ?)");
    $stmt->execute([$_POST['language_id'], $_POST['group'], $_POST['key'], $_POST['value']]);
    header("Location: index.php?page=translations");
    exit;
}

// ---------------- عملیات Import ----------------
if ($page === 'import' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['json_file'])) {
    $fileContent = file_get_contents($_FILES['json_file']['tmp_name']);
    $data = json_decode($fileContent, true);

    if ($data && isset($data['languages'], $data['translations'])) {
        // وارد کردن زبان‌ها
        foreach ($data['languages'] as $lang) {
            $stmt = $pdo->prepare("INSERT IGNORE INTO languages (id, code, name) VALUES (?, ?, ?)");
            $stmt->execute([$lang['id'], $lang['code'], $lang['name']]);
        }
        // وارد کردن ترجمه‌ها
        foreach ($data['translations'] as $tr) {
            $stmt = $pdo->prepare("INSERT INTO translations (language_id, `group`, `key`, `value`) VALUES (?, ?, ?, ?)");
            $stmt->execute([$tr['language_id'], $tr['group'], $tr['key'], $tr['value']]);
        }
        $importMsg = "✅ داده‌ها با موفقیت وارد شدند.";
    } else {
        $importMsg = "❌ فایل JSON معتبر نیست.";
    }
}

// ---------------- عملیات Export ----------------
if ($page === 'export' && isset($_GET['download'])) {
    $languages = $pdo->query("SELECT * FROM languages")->fetchAll(PDO::FETCH_ASSOC);
    $Language = $pdo->query("SELECT * FROM Language")->fetchAll(PDO::FETCH_ASSOC);
    $translations = $pdo->query("SELECT * FROM translations")->fetchAll(PDO::FETCH_ASSOC);

    $exportData = [
        "languages" => $languages,
        "translations" => $translations
    ];

    header('Content-Type: application/json');
    header('Content-Disposition: attachment; filename="translations_export.json"');
    echo json_encode($exportData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}
?>
<!DOCTYPE html>
<html lang="fa">
<head>
    <meta charset="UTF-8">
    <title>مدیریت زبان‌ها و ترجمه‌ها</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container py-4">

    <h1 class="mb-4">🌐 مدیریت زبان‌ها و ترجمه‌ها</h1>
    <a href="index2.php" class="btn btn-secondary">صفحه اصلی</a>
    <a href="index2.php?page=languages" class="btn btn-primary">مدیریت زبان‌ها</a>
    <a href="index2.php?page=translations" class="btn btn-success">مدیریت ترجمه‌ها</a>
    <a href="index2.php?page=import" class="btn btn-warning">ورود (Import)</a>
    <a href="index2.php?page=export" class="btn btn-info">خروجی (Export)</a>
    <hr>

<?php
// ---------------- صفحه اصلی ----------------
if ($page === 'home') {
    echo "<h2>👋 به سیستم مدیریت زبان‌ها خوش آمدید</h2>";
}

// ---------------- مدیریت زبان‌ها ----------------
if ($page === 'languages') {
    $Language = $pdo->query("SELECT * FROM Language")->fetchAll(PDO::FETCH_ASSOC);
    ?>
    <h2>📌 لیست زبان‌ها</h2>
    <table class="table table-bordered">
        <tr><th>ID</th><th>کد</th><th>نام</th></tr>
        <?php foreach ($language as $lang): ?>
            <tr>
                <td><?= $lang['id'] ?></td>
                <td><?= $lang['LanguageCode'] ?></td>
                <td><?= $lang['LanguageName'] ?></td>
            </tr>
        <?php endforeach; ?>
    </table>

    <h3 class="mt-4">➕ افزودن زبان جدید</h3>
    <form method="POST">
        <input name="code" class="form-control mb-2" placeholder="کد زبان (مثلا fa)">
        <input name="name" class="form-control mb-2" placeholder="نام زبان (مثلا فارسی)">
        <button class="btn btn-primary">ذخیره</button>
    </form>
    <?php
}

// ---------------- مدیریت ترجمه‌ها ----------------
if ($page === 'translations') {
    $languages = $pdo->query("SELECT * FROM languages")->fetchAll(PDO::FETCH_ASSOC);
    $translations = $pdo->query("SELECT t.*, l.name as lang_name FROM translations t JOIN languages l ON l.id=t.language_id")->fetchAll(PDO::FETCH_ASSOC);
    ?>
    <h2>📑 لیست ترجمه‌ها</h2>
    <table class="table table-bordered">
        <tr><th>زبان</th><th>گروه</th><th>کلید</th><th>مقدار</th></tr>
        <?php foreach ($translations as $tr): ?>
            <tr>
                <td><?= $tr['lang_name'] ?></td>
                <td><?= $tr['group'] ?></td>
                <td><?= $tr['key'] ?></td>
                <td><?= $tr['value'] ?></td>
            </tr>
        <?php endforeach; ?>
    </table>

    <h3 class="mt-4">➕ افزودن ترجمه جدید</h3>
    <form method="POST">
        <select name="language_id" class="form-control mb-2">
            <?php foreach ($languages as $lang): ?>
                <option value="<?= $lang['id'] ?>"><?= $lang['name'] ?></option>
            <?php endforeach; ?>
        </select>
        <input name="group" class="form-control mb-2" placeholder="گروه (مثلا auth)">
        <input name="key" class="form-control mb-2" placeholder="کلید (مثلا login)">
        <input name="value" class="form-control mb-2" placeholder="مقدار (مثلا ورود)">
        <button class="btn btn-success">ذخیره</button>
    </form>
    <?php
}

// ---------------- Import ----------------
if ($page === 'import') {
    if (isset($importMsg)) echo "<div class='alert alert-info'>$importMsg</div>";
    ?>
    <h2>📥 ورود داده‌ها (Import)</h2>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="json_file" class="form-control mb-2" accept=".json" required>
        <button class="btn btn-warning">بارگذاری و ورود</button>
    </form>
    <?php
}

// ---------------- Export ----------------
if ($page === 'export') {
    ?>
    <h2>📤 خروجی داده‌ها (Export)</h2>
    <a href="index.php?page=export&download=1" class="btn btn-info">دانلود JSON</a>
    <?php
}
?>

</body>
</html>
