<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import pipopa 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();

        $listCategory = [];
        foreach ($categories as $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)));

            $listCategory[$category->wp_id] = [
                'name'   => $categoryName,
                'slug'   => $categorySlug,
                'parent' => $category->parent ?? 0,
            ];
        }

        $aiChatbotId = null;
        foreach ($listCategory as $key => $category) {
            if ($category['slug'] == 'ai-chatbot') {
                $aiChatbotId = $key;
                break;
            }
        }

        $result = [];
        if ($aiChatbotId) {
            $result = $this->getCategory($listCategory, $aiChatbotId);
        }

        $newResult = [];
        foreach ($result as $item) {
            $children = count($item['children']) > 0 ? $item['children'] : null;

            $newItem = [
                'name' => $item['name'],
                'slug' => $item['slug'],
            ];

            if ($children) {
                $newItem['children'] = $children;
            }

            $newResult[] = $newItem;
        }

        file_put_contents(public_path('wordpress-pipopa-categories.json'), json_encode($newResult));

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