<?php

namespace App\Console\Commands;

use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

#[Signature('migrate:taxonomies:execute')]
#[Description('Migrate taxonomies, make sure you have configured the migration before that.')]
class MigrateTaxonomiesExecute extends Command
{
    public function handle()
    {
        $taxMap = json_decode(DB::table('migration_settings')->where('key', 'wp_taxonomies_to_laravel_tables')->value('value'), true);

        if( !$taxMap ){
            $this->error("No WP taxonomies need to be transferred.");
            return self::FAILURE;
        }

        if( $this->ask("Are you sure you want launch that migration? Write ok if you want to launch it.", "") !== 'ok' ){
            return self::SUCCESS;
        }

        foreach ( $taxMap as $wpTax => $table )
        {
            $this->info("Migrate: {$wpTax} => {$table}");

            $terms = DB::connection('old_wp')
                ->table('term_taxonomy')
                ->join('terms', 'term_taxonomy.term_id', '=', 'terms.term_id')
                ->where('term_taxonomy.taxonomy', $wpTax)
                ->select('term_taxonomy.term_taxonomy_id', 'terms.name', 'terms.slug')
                ->get();

            $this->withProgressBar($terms, function ($term) use ($table) {

                $exists = DB::table('migrations_logs')
                    ->where('source_system', 'wp')
                    ->where('source_table', 'wp_term_taxonomy')
                    ->where('source_id', $term->term_taxonomy_id )
                    ->exists();

                if( $exists )
                    return;

                $Id = DB::table( $table )->where('slug', $term->slug)->value('id');

                if( $Id === null) {
                    $Id = DB::table($table)
                        ->insertGetId([
                            'name' => $term->name, 'slug' => $term->slug,
                            'created_at' => now(), 'updated_at' => now()
                        ]);
                }

                DB::table('migrations_logs')->insert([
                    'source_system' => 'wp',
                    'source_table' => 'wp_term_taxonomy',
                    'source_id' => $term->term_taxonomy_id,
                    'target_table' => $table,
                    'target_id' => $Id,
                    'status' => 'done',
                    'migrated_at' => now(),
                    'created_at' => now(),
                    'updated_at' => now()
                ]);
            });
            $this->newLine();
        }

        $this->info("Migration done");
        return self::SUCCESS;
    }
}
