<?php

use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');

// ... existing code ...

Artisan::command('postcode:generate-config', function () {
    $csvPath = storage_path('app/PLZ-Liste.csv');
    $configPath = config_path('postCode.php');

    if (! File::exists($csvPath)) {
        $this->error('CSV-Datei nicht gefunden: ' . $csvPath);
        return 1;
    }

    $handle = fopen($csvPath, 'r');

    if ($handle === false) {
        $this->error('CSV-Datei konnte nicht geöffnet werden.');
        return 1;
    }

    $map = [];

    $header = fgetcsv($handle, 0, ';');

    while (($row = fgetcsv($handle, 0, ';')) !== false) {
        if (count($row) < 2) {
            continue;
        }

        $plz = trim($row[0]);
        $bundesland = trim($row[1]);

        if ($plz === '' || $bundesland === '') {
            continue;
        }

        $map[$plz] = $bundesland;
    }

    fclose($handle);

    ksort($map);

    $content = "<?php\n\nreturn [\n    'map' => [\n";

    foreach ($map as $plz => $bundesland) {
        $content .= "        '" . addslashes($plz) . "' => '" . addslashes($bundesland) . "',\n";
    }

    $content .= "    ],\n];\n";

    File::put($configPath, $content);

    $this->info('Config erfolgreich generiert: ' . $configPath);

    return 0;
})->purpose('Generate config/postCode.php from storage/app/PLZ-Liste.csv');
