<?php
/**
 * Add missing translations for v1.7.10:
 *  - Tools section: Repair Translation Links + Fix Elementor Template Shortcodes cards/detail
 *  - Dashboard: Delete translations button + bulk delete
 *  - Tool card descs: SEO titles, short descriptions, router exclude, string translations
 *
 * Usage: php add-v1710-translations.php
 */

$envFile = 'E:\\repos\\meeptech\\.env.local';
$envContent = file_get_contents($envFile);
preg_match('/OPENAI_API_KEY=(.+)/', $envContent, $m);
$apiKey = trim($m[1] ?? '');
if (!$apiKey) { die("No API key found in $envFile\n"); }

$langDir = __DIR__;
$domain  = 'ai-translator-for-elementor-and-polylang';

$languages = [
    'de_DE' => 'German',
    'es_ES' => 'Spanish',
    'fr_FR' => 'French',
    'it_IT' => 'Italian',
    'nl_NL' => 'Dutch',
    'pl_PL' => 'Polish',
    'pt_BR' => 'Brazilian Portuguese',
    'ru_RU' => 'Russian',
    'uk'    => 'Ukrainian',
];

$allStrings = [
    // Tools hub card — short descriptions
    'Reconcile inconsistent translation links (dashboard list, switcher, cart/checkout swap).',
    'Rewrite [elementor-template id="X"] shortcodes in translated posts to use the per-language template.',
    'Re-translate SEO title, description, OG/Twitter for existing translations.',
    'Re-translate WooCommerce product short descriptions (post excerpt).',
    'Override UI strings not covered automatically (gateway titles, privacy text, plugin strings).',
    'Stop the router from prefixing custom plugin/API endpoints.',

    // Fix Elementor Template Shortcodes tool — title, detail desc, buttons, results
    'Fix Elementor Template Shortcodes',
    'Rewrites [elementor-template id="X"] shortcodes embedded in translated posts so each id points at the per-language translated template instead of the source-language one. Run "Scan" to preview which posts would change, then "Fix Shortcodes".',
    'Fix Shortcodes',
    'Fixed',
    'Would fix',
    'No translated posts have source-language template shortcodes.',
    'translated post(s) with [elementor-template id="X"] shortcodes updated to the per-language template.',
    'Reload the affected pages to see the result.',
    'Rewrite Elementor template shortcodes now? This updates post content and is safe to run multiple times.',

    // Repair Translation Links — updated long description (wording changed from 1.6.x)
    'Reconciles translation links so the dashboard page list, language switcher, and the cart/checkout page swap all agree. Fixes translated pages that wrongly appear as their own source and links left inconsistent by older versions. Run "Scan" first to preview the number of inconsistencies, then "Repair Links".',

    // Dashboard delete buttons
    'Delete translations',
    'Permanently delete all translations of this page. The source page is kept. Cannot be undone.',
    'Permanently delete (cannot be undone)',
    'Delete selected translations',
];

foreach ($languages as $locale => $langName) {
    $poFile = $langDir . "/{$domain}-{$locale}.po";
    if (!file_exists($poFile)) {
        echo "SKIP: $poFile not found\n";
        continue;
    }

    echo "=== Processing: $langName ($locale) ===\n";
    $poContent = file_get_contents($poFile);

    $missing = [];
    foreach ($allStrings as $str) {
        $escaped = addcslashes($str, '"');
        if (strpos($poContent, 'msgid "' . $escaped . '"') === false) {
            $missing[] = $str;
        }
    }

    if (empty($missing)) {
        echo "  No missing strings!\n\n";
        continue;
    }

    echo "  Missing: " . count($missing) . " strings\n";
    echo "  Translating...\n";

    $result = translateBatch($missing, $langName, $apiKey);

    if ($result === false) {
        echo "  ERROR: Translation failed\n\n";
        continue;
    }

    $appendBlock = "\n\n# --- Added by add-v1710-translations.php (" . date('Y-m-d') . ") ---\n";
    foreach ($missing as $i => $original) {
        if (isset($result[$i])) {
            $appendBlock .= "\n";
            $appendBlock .= formatPoEntry($original, $result[$i]);
        }
    }

    file_put_contents($poFile, $poContent . $appendBlock);
    echo "  Appended " . count($result) . " translations to $poFile\n\n";
}

echo "=== Compiling .mo files ===\n";
require_once __DIR__ . '/generate-mo-files.php';
echo "\nDone!\n";

// ============================================================
function translateBatch(array $strings, string $targetLang, string $apiKey): array|false {
    $systemPrompt = "You are a professional translator specializing in WordPress plugin UI translations. Translate the following English strings to {$targetLang}.

RULES:
1. Return ONLY a JSON array of translated strings in the exact same order
2. Preserve all placeholders like %s, %d, %1\$s exactly as-is
3. Keep brand names untranslated: WordPress, WooCommerce, Elementor, Polylang, WPML
4. Use formal/polite form for UI text
5. '[elementor-template id=\"X\"]' is a WordPress shortcode — keep it exactly as-is, untranslated
6. 'Scan (preview)' means a dry-run preview button — translate naturally
7. Short counter labels ('groups', 'links', 'source refs') — keep concise
8. 'Fixed' and 'Would fix' are past-tense and conditional UI verbs for a shortcode rewrite tool

Format: [\"translation 1\", \"translation 2\", ...]";

    $userPrompt = "Translate these " . count($strings) . " strings to {$targetLang}:\n\n" . json_encode($strings, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

    $payload = [
        'model'    => 'gpt-4o-mini',
        'messages' => [
            ['role' => 'system', 'content' => $systemPrompt],
            ['role' => 'user',   'content' => $userPrompt],
        ],
        'temperature' => 0.2,
    ];

    $ch = curl_init('https://api.openai.com/v1/chat/completions');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey,
        ],
        CURLOPT_POSTFIELDS  => json_encode($payload),
        CURLOPT_TIMEOUT     => 60,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        echo "    API error ($httpCode): " . substr($response, 0, 300) . "\n";
        return false;
    }

    $data    = json_decode($response, true);
    $content = $data['choices'][0]['message']['content'] ?? '';
    $content = preg_replace('/^```(?:json)?\s*/m', '', $content);
    $content = preg_replace('/\s*```\s*$/m', '', $content);
    $content = trim($content);

    $result = json_decode($content, true);
    if (!is_array($result) || count($result) !== count($strings)) {
        echo "    Parse error (expected " . count($strings) . ", got " . (is_array($result) ? count($result) : 'null') . ")\n";
        echo "    Response: " . substr($content, 0, 300) . "\n";
        return false;
    }

    return $result;
}

function formatPoEntry(string $msgid, string $msgstr): string {
    return 'msgid '  . formatPoString($msgid)  . "\n"
         . 'msgstr ' . formatPoString($msgstr) . "\n";
}

function formatPoString(string $str): string {
    $str = str_replace('\\', '\\\\', $str);
    $str = str_replace('"',  '\\"',  $str);

    if (strpos($str, "\n") !== false) {
        $lines  = explode("\n", $str);
        $result = '""' . "\n";
        foreach ($lines as $i => $line) {
            $result .= '"' . $line . ($i < count($lines) - 1 ? '\\n' : '') . '"' . "\n";
        }
        return rtrim($result);
    }

    return '"' . $str . '"';
}
