<?php

namespace App\Console\Commands;

use App\Models\Article;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class UpdateWordpressPostsSlug extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update:wordpress-posts-slug';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update posts slug from WordPress system';

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

        foreach ($posts as $key => $post) {
            $postId = $post['id'];
            $postSlug = $post['slug'];
            Article::where('id', $postId)->update([
                'slug' => $postSlug,
            ]);

            $this->info("Importing post {$key} ID: " . $postId . ':' . $postSlug);
        }

        $this->info('Posts slugs exported successfully: ' . public_path('wordpress-posts-slug.json'));

        /*$posts = DB::connection('wordpress')
            ->table('wp_posts')
            ->where('post_type', 'post')
            ->select('*')
            ->get();

        collect($posts)->chunk(50)->each(function ($chunk) {
            foreach ($chunk as $key => $post) {
                $postId = $post->ID;
                $postSlug = trim($post->post_name);
                if (empty($postSlug)) continue;

                Article::where('id', $postId)->update([
                    'slug' => $postSlug
                ]);

                $this->info("Importing post {$key} ID: " . $postId . ":" . $postSlug);
            }
        });

        $this->info('Posts slugs exported successfully: ' . public_path('wordpress-posts-slug.json'));*/
    }

    /**
     * Convert Japanese text to Romaji.
     *
     * @param string $string
     * @return string
     */
    private function convertJapaneseToRomaji($string, $default = 'article')
    {
        $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;
    }
}
