<?php

namespace App\Console\Commands;

use App\Models\Category;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import categories from WordPress system';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $categories = DB::connection('wordpress')
            ->table('wp_terms as t')
            ->join('wp_term_taxonomy as tt', 't.term_id', '=', 'tt.term_id')
            ->where('tt.taxonomy', 'category')
            ->select(
                't.term_id as wp_id',
                't.name',
                't.slug',
                'tt.description',
                'tt.parent'
            )
            ->get();

        collect($categories)->chunk(50)->each(function ($chunk) {
            foreach ($chunk as $key => $category) {
                $categoryName = trim(html_entity_decode($category->name, ENT_QUOTES | ENT_HTML5, 'UTF-8'));
                $categorySlug = urldecode($category->slug);
                $categorySlug = Str::slug($this->convertJapaneseToRomaji(trim($categorySlug)));
                $categoryDescription = trim(html_entity_decode($category->description, ENT_QUOTES | ENT_HTML5, 'UTF-8'));

                $newCategory = Category::where('id', $category->wp_id)->first();
                if (! $newCategory) {
                    Category::create([
                        'id'          => $category->wp_id,
                        'type'        => 0,
                        'name'        => $categoryName,
                        'slug'        => $categorySlug,
                        'description' => $categoryDescription,
                        'parent_id'   => $category->parent ?? 0,
                        'created_at'  => now(),
                        'updated_at'  => now(),
                    ]);
                } else {
                    $newCategory->update([
                        'id'          => $category->wp_id,
                        'type'        => 0,
                        'name'        => $categoryName,
                        'slug'        => $categorySlug,
                        'description' => $categoryDescription,
                        'parent_id'   => $category->parent ?? 0,
                        'updated_at'  => now(),
                    ]);
                }

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

        $this->info('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;
    }
}
