<?php

namespace App\Console\Commands;

use App\Models\Category;
use Illuminate\Console\Command;

class ImportWordpressPipopaJsonCategories extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:wordpress-pipopa-json-categories';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import pipopa categories from Json file';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $filePath = public_path('wordpress-pipopa-categories.json');
        $jsonData = file_get_contents($filePath);
        $categories = json_decode($jsonData, true);

        foreach ($categories as $key => $category) {
            $categoryName = $category['name'];
            $categorySlug = 'pipopa-' . $category['slug'];

            $newCategory = Category::where('type', 1)
                ->where('slug', $categorySlug)
                ->first();

            if (! $newCategory) {
                $newCategory = Category::create([
                    'type'       => 1,
                    'name'       => $categoryName,
                    'slug'       => $categorySlug,
                    'parent_id'  => 0,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            } else {
                $newCategory->update([
                    'type'       => 1,
                    'name'       => $categoryName,
                    'parent_id'  => 0,
                    'updated_at' => now(),
                ]);
            }

            $this->info("Importing category {$key}: ID: " . $newCategory->id . ' - Name: ' . $categoryName . ' - Slug: ' . $categorySlug);
        }

        $this->info('Pipopa categories imported successfully!');
    }

    /**
     * Convert Japanese text to Romaji.
     *
     * @param string $string
     * @return string
     */
    private function convertJapaneseToRomaji($string, $default = 'category')
    {
        $romaji = null;
        $default = $default . '-' . uniqid();

        try {
            $kakasiOutput = shell_exec('echo ' . escapeshellarg($string) . ' | kakasi -i utf8 -Ha -Ka -Ja -Ea -ka 2>/dev/null');
            $romaji = trim($kakasiOutput);
        } catch (\Exception $e) {
            $this->error('Failed to convert Japanese to Romaji: ' . $e->getMessage());
        }

        if (empty($romaji) || $romaji === ' ') {
            $romaji = transliterator_transliterate(
                'Any-Latin; NFKD; [:Nonspacing Mark:] Remove; Lower; NFC',
                $string
            );
        }

        if (empty($romaji)) {
            $romaji = $default;
        }

        if ($romaji === $default) {
            $this->warn('Failed to convert Japanese to Romaji for string: ' . $string);
        }

        return $romaji;
    }

    private function getCategory($list, $parentId)
    {
        $result = [];
        foreach ($list as $id => $item) {
            if ($item['parent'] == $parentId) {
                $item['children'] = $this->getCategory($list, $id);
                $result[] = $item;
            }
        }

        return $result;
    }
}
