<?php
// Fill CSV `Value` column from resources/lang files when available.
$input = __DIR__ . '/../storage/app/translations_missing_admin_converted.csv';
$output = __DIR__ . '/../storage/app/translations_missing_admin_converted_filled.csv';

if (!file_exists($input)) {
    fwrite(STDERR, "Input CSV not found: $input\n");
    exit(2);
}

$in = fopen($input, 'r');
$out = fopen($output, 'w');
if (!$in || !$out) {
    fwrite(STDERR, "Failed to open input/output files.\n");
    exit(3);
}

// Read header
$headerLine = fgets($in);
if ($headerLine === false) {
    fwrite(STDERR, "Empty CSV file.\n");
    exit(4);
}
// Normalize header and write it back
fwrite($out, rtrim($headerLine, "\r\n") . PHP_EOL);

$langCache = [];
$rowCount = 0;
// Try to bootstrap Laravel to access DB translations if available
$appBooted = false;
try {
    if (file_exists(__DIR__ . '/../vendor/autoload.php') && file_exists(__DIR__ . '/../bootstrap/app.php')) {
        require __DIR__ . '/../vendor/autoload.php';
        $app = require_once __DIR__ . '/../bootstrap/app.php';
        $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
        $kernel->bootstrap();
        $appBooted = true;
    }
} catch (Throwable $e) {
    // Ignore bootstrap failures and continue with file-based filling
    $appBooted = false;
}
while (($line = fgets($in)) !== false) {
    // Parse semicolon-delimited CSV with double-quote enclosure
    $cols = str_getcsv(trim($line, "\n\r"), ';', '"');
    // Support both quoted and unquoted CSVs
    if (count($cols) < 4) {
        // pad if necessary
        $cols = array_pad($cols, 4, '');
    }
    $filename = trim($cols[0], ' "');
    $language = trim($cols[1], ' "');
    $keycode  = trim($cols[2], ' "');
    $value    = isset($cols[3]) ? $cols[3] : '';

    // Only fill if empty
    if ($value === null || $value === '') {
        $langKey = $language . '::' . $filename;
        if (!isset($langCache[$langKey])) {
            $path = __DIR__ . "/../resources/lang/{$language}/{$filename}.php";
            if (file_exists($path)) {
                $data = include $path;
                if (!is_array($data)) $data = [];
                $langCache[$langKey] = $data;
            } else {
                $langCache[$langKey] = null; // mark missing
            }
        }
        $translations = $langCache[$langKey];
        if (is_array($translations) && array_key_exists($keycode, $translations)) {
            $value = $translations[$keycode];
        } elseif ($appBooted) {
            // Try DB translations using the Translation model if available
            try {
                $modelClass = '\\Klevze\\ControlPanel\\Models\\Content\\Translation';
                if (class_exists($modelClass)) {
                    $rec = $modelClass::where('file', $filename)->where('keycode', $keycode)->first();
                    if ($rec && isset($rec->value) && is_array($rec->value) && array_key_exists($language, $rec->value)) {
                        $value = $rec->value[$language];
                    }
                }
            } catch (Throwable $e) {
                // ignore DB issues
            }
        }
    }

    // Ensure value is string
    if (is_array($value)) {
        $value = json_encode($value, JSON_UNESCAPED_UNICODE);
    }

    // Write row using semicolon delimiter and double quotes
    // fputcsv will escape quotes correctly
    fputcsv($out, [$filename, $language, $keycode, $value], ';', '"');
    $rowCount++;
}

fclose($in);
fclose($out);

fwrite(STDOUT, "Filled {$rowCount} rows. Output: {$output}\n");
exit(0);
