<?php
// Настройки
$baseDir = $_SERVER['DOCUMENT_ROOT'] . '/local/templates/operator/components';
$txtEnFile = __DIR__ . '/en.txt';
$txtCnFile = __DIR__ . '/cn.txt';

$action = $_GET['action'] ?? '';
$message = '';
$messageType = '';

// Функция сканирования и экспорта
function scanAndExport($baseDir, $txtEnFile, $txtCnFile) {
    if (!is_dir($baseDir)) {
        return "Ошибка: Папка $baseDir не найдена.";
    }

    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($baseDir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );

    $count = 0;
    $enContent = '';
    $cnContent = '';

    foreach ($iterator as $file) {
        // Ищем все php файлы внутри папок lang/ru/
        if ($file->isFile() && preg_match('~[\\\\/]lang[\\\\/]ru[\\\\/][^\\\\/]+\.php$~i', $file->getPathname())) {
            $sourcePath = $file->getPathname();
            
            // Формируем пути для en и cn
            $targetEnPath = preg_replace('~[\\\\/]lang[\\\\/]ru[\\\\/]~i', '/lang/en/', $sourcePath);
            $targetCnPath = preg_replace('~[\\\\/]lang[\\\\/]ru[\\\\/]~i', '/lang/cn/', $sourcePath);
            
            // Создаем папки, если их нет
            if (!is_dir(dirname($targetEnPath))) mkdir(dirname($targetEnPath), 0755, true);
            if (!is_dir(dirname($targetCnPath))) mkdir(dirname($targetCnPath), 0755, true);
            
            // Копируем файлы
            copy($sourcePath, $targetEnPath);
            copy($sourcePath, $targetCnPath);
            
            // Читаем содержимое
            $fileContent = file_get_contents($sourcePath);
            
            // Формируем относительный путь для txt (начинается с /local/...)
            $relativeEn = str_replace($_SERVER['DOCUMENT_ROOT'], '', $targetEnPath);
            $relativeCn = str_replace($_SERVER['DOCUMENT_ROOT'], '', $targetCnPath);
            
            // Добавляем в буфер txt файлов (путь + перенос строки + содержимое + 2 переноса)
            $enContent .= $relativeEn . "\n" . $fileContent . "\n\n";
            $cnContent .= $relativeCn . "\n" . $fileContent . "\n\n";
            
            $count++;
        }
    }

    // Сохраняем txt файлы
    file_put_contents($txtEnFile, $enContent);
    file_put_contents($txtCnFile, $cnContent);

    return "Успешно! Обработано файлов: $count. Созданы файлы en.txt и cn.txt.";
}

// Функция загрузки переводов
function loadTranslations($baseDir, $txtEnFile, $txtCnFile) {
    $count = 0;
    $errors = [];

    // Обрабатываем оба файла
    foreach (['en' => $txtEnFile, 'cn' => $txtCnFile] as $lang => $txtFile) {
        if (!file_exists($txtFile)) {
            $errors[] = "Файл $txtFile не найден.";
            continue;
        }

        $txtContent = file_get_contents($txtFile);
        
        // Парсим txt файл. 
        // Ищем строки, начинающиеся с /local/ и заканчивающиеся на .php, 
        // а всё, что идет до следующего такого пути, считаем содержимым файла.
        $pattern = '~^(/local/[^\r\n]+\.php)[\r\n]+(.*?)(?=^/local/[^\r\n]+\.php|\z)~ms';
        
        if (preg_match_all($pattern, $txtContent, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $match) {
                $relativePath = $match[1];
                $fileContent = $match[2];
                
                // Убираем лишние переносы строк в конце, если они появились при копировании
                $fileContent = rtrim($fileContent, "\r\n") . "\n"; 
                
                $absolutePath = $_SERVER['DOCUMENT_ROOT'] . $relativePath;
                
                if (file_put_contents($absolutePath, $fileContent) !== false) {
                    $count++;
                } else {
                    $errors[] = "Не удалось записать: $absolutePath";
                }
            }
        }
    }

    $result = "Загрузка завершена. Обновлено файлов: $count.";
    if (!empty($errors)) {
        $result .= "\nОшибки:\n" . implode("\n", $errors);
    }
    return $result;
}

// Обработка действий
if ($action === 'scan') {
    $message = scanAndExport($baseDir, $txtEnFile, $txtCnFile);
    $messageType = 'success';
} elseif ($action === 'load') {
    $message = loadTranslations($baseDir, $txtEnFile, $txtCnFile);
    $messageType = 'success';
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Менеджер языковых файлов</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 40px auto; padding: 20px; background: #f9f9f9; }
        h1 { color: #333; }
        .btn { display: inline-block; padding: 12px 24px; margin: 10px 10px 10px 0; font-size: 16px; color: #fff; background: #007bff; text-decoration: none; border-radius: 5px; border: none; cursor: pointer; }
        .btn-green { background: #28a745; }
        .btn:hover { opacity: 0.9; }
        .alert { padding: 15px; margin-top: 20px; border-radius: 5px; white-space: pre-wrap; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .info { background: #e2e3e5; color: #383d41; padding: 15px; border-radius: 5px; margin-bottom: 20px; font-size: 14px;}
    </style>
</head>
<body>

    <h1>Менеджер языковых файлов (ru -> en/cn)</h1>
    
    <div class="info">
        <strong>Папка для сканирования:</strong> <?= htmlspecialchars($baseDir) ?><br>
        <strong>Файлы для переводов:</strong> <?= htmlspecialchars($txtEnFile) ?> и <?= htmlspecialchars($txtCnFile) ?>
    </div>

    <a href="?action=scan" class="btn" onclick="return confirm('Начать сканирование и копирование файлов?');">1. Сканировать и подготовить файлы</a>
    <a href="?action=load" class="btn btn-green" onclick="return confirm('Загрузить переводы из txt файлов? Это перезапишет текущие файлы en и cn.');">2. Загрузить переводы из txt</a>

    <?php if ($message): ?>
        <div class="alert alert-<?= $messageType ?>">
            <?= nl2br(htmlspecialchars($message)) ?>
        </div>
    <?php endif; ?>

    <hr style="margin-top: 40px;">
    <h3>Инструкция:</h3>
    <ol>
        <li>Нажмите <strong>«Сканировать и подготовить файлы»</strong>. Скрипт найдет все файлы в <code>lang/ru/</code>, создаст папки <code>lang/en/</code> и <code>lang/cn/</code> и скопирует файлы туда.</li>
        <li>Рядом со скриптом появятся файлы <code>en.txt</code> и <code>cn.txt</code>.</li>
        <li>Откройте их в любом текстовом редакторе и переведите тексты. <strong>Важно:</strong> не удаляйте первую строку каждого блока (она содержит путь к файлу).</li>
        <li>Сохраните txt файлы и нажмите <strong>«Загрузить переводы из txt»</strong>.</li>
    </ol>

</body>
</html>