<?php
/**
 * Add missing translations for v1.7.11 — action menu strings.
 * Usage: php add-v1711-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 = [
    'Delete page',           // ⋯ menu item (source row)
    'More actions',          // title/aria-label on the ⋯ toggle button
    'Delete translations (%d)', // ⋯ menu item with count; %d = number of translations
];

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

    echo "=== $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 "  OK — nothing missing\n\n"; continue; }

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

    $system = "You are a professional translator for WordPress plugin UIs. Translate English strings to {$langName}.
RULES: JSON array, same order. Keep %d exactly. Use formal/polite form. 'Delete page' = permanently delete just that page.";
    $user   = "Translate to {$langName}:\n\n" . json_encode($missing, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

    $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(['model'=>'gpt-4o-mini','messages'=>[['role'=>'system','content'=>$system],['role'=>'user','content'=>$user]],'temperature'=>0.2]),
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $resp = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
    if ($code !== 200) { echo "  API error $code\n\n"; continue; }

    $data    = json_decode($resp, true);
    $content = preg_replace('/^```(?:json)?\s*|\s*```$/m', '', trim($data['choices'][0]['message']['content'] ?? ''));
    $result  = json_decode($content, true);
    if (!is_array($result) || count($result) !== count($missing)) { echo "  Parse error\n\n"; continue; }

    $block = "\n\n# --- Added by add-v1711-translations.php (" . date('Y-m-d') . ") ---\n";
    foreach ($missing as $i => $orig) {
        $esc  = function(string $s): string {
            $s = str_replace(['\\','"'], ['\\\\','\\"'], $s);
            return '"' . $s . '"';
        };
        $block .= "\nmsgid "  . $esc($orig)       . "\n";
        $block .= "msgstr " . $esc($result[$i]) . "\n";
    }
    file_put_contents($poFile, $poContent . $block);
    echo "  Appended " . count($result) . " strings\n\n";
}

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