<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: text/plain; charset=utf-8');

// Load .env
$envPath = __DIR__ . '/.env';
if (file_exists($envPath)) {
    foreach (file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#' || strpos($line, '=') === false) continue;
        [$k, $v] = explode('=', $line, 2);
        putenv(trim($k) . '=' . trim($v));
        $_ENV[trim($k)] = trim($v);
    }
}

// Security
if (($_GET['key'] ?? '') !== 'tiangan-import-2024') {
    die('403 - wrong key');
}

// Connect DB
$pdo = new PDO(
    'mysql:host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_NAME') . ';charset=utf8mb4',
    getenv('DB_USER'), getenv('DB_PASS'),
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

// Read descriptions.json
$file = __DIR__ . '/descriptions.json';
if (!file_exists($file)) die("❌ descriptions.json not found in api/ folder");

$data = json_decode(file_get_contents($file), true);
if (!$data) die("❌ Invalid JSON");

function getd($d, $lang) {
    if (!$d) return '';
    if (is_string($d)) return $lang === 'en' ? $d : '';
    return $d[$lang] ?? '';
}

$count = 0;

// Import tianganDesc
foreach ($data['tianganDesc'] ?? [] as $r) {
    $d = $r['desc'] ?? [];
    $s = $r['sensDesc'] ?? [];
    $stmt = $pdo->prepare('UPDATE tiangan_desc SET desc_en=?, desc_ms=?, desc_zh=?, sens_en=?, sens_ms=?, sens_zh=? WHERE tg=?');
    $stmt->execute([
        getd($d,'en'), getd($d,'ms'), getd($d,'zh'),
        getd($s,'en'), getd($s,'ms'), getd($s,'zh'),
        $r['tg']
    ]);
    echo "✅ Updated 天干: {$r['tg']} (EN:" . strlen(getd($d,'en')) . " MS:" . strlen(getd($d,'ms')) . " ZH:" . strlen(getd($d,'zh')) . " chars)\n";
    $count++;
}

// Import nodeCombRules
$ncCount = 0;
foreach ($data['nodeCombRules'] ?? [] as $r) {
    $d = $r['desc'] ?? [];
    $s = $r['sensDesc'] ?? [];
    $pairs = json_encode($r['pairs'] ?? [], JSON_UNESCAPED_UNICODE);
    $stmt = $pdo->prepare('INSERT INTO node_comb_rules (id, pairs_json, val, desc_en, desc_ms, desc_zh, sens_en, sens_ms, sens_zh) VALUES (?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE pairs_json=?, val=?, desc_en=?, desc_ms=?, desc_zh=?, sens_en=?, sens_ms=?, sens_zh=?');
    $stmt->execute([
        $r['id'], $pairs, $r['val'],
        getd($d,'en'), getd($d,'ms'), getd($d,'zh'),
        getd($s,'en'), getd($s,'ms'), getd($s,'zh'),
        $pairs, $r['val'],
        getd($d,'en'), getd($d,'ms'), getd($d,'zh'),
        getd($s,'en'), getd($s,'ms'), getd($s,'zh'),
    ]);
    $ncCount++;
}

echo "\n✅ tianganDesc: $count rows updated\n";
echo "✅ nodeCombRules: $ncCount rows imported\n";
echo "\n🎉 Done! Delete this file after use.";
