<?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:categories:execute')]
#[Description('Migrate categories, make sure you have configured the migration before that.')]
class MigrateCategoriesExecute extends Command
{

    private const string TABLE = 'categories';

    public function handle()
    {
        $taxMap = json_decode(DB::table('migration_settings')->where('key', 'wp_categories_to_entry_sections')->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;
        }

        $table = self::TABLE;

        foreach ( $taxMap as $wpTax => $restrictedTo )
        {
            $this->info("Migrate: {$wpTax} restricted to {$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, $restrictedTo) {

                $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;

                $existing = DB::table( $table )->where('slug', $term->slug)->first();

                if( $existing === null) {
                    $Id = DB::table($table)
                        ->insertGetId([
                            'name' => $term->name, 'slug' => $term->slug,
                            'restricted_to' => json_encode([$restrictedTo]),
                            'created_at' => now(), 'updated_at' => now()
                        ]);
                } else {
                    $Id = $existing->id;
                    $restrictedToField = json_decode($existing->restricted_to, true) ?? [];
                    if( !in_array( $restrictedTo, $restrictedToField, true ) ){
                        $restrictedToField[] = $restrictedTo;
                        DB::table($table)
                            ->where('id', $Id)
                            ->update(['restricted_to' => json_encode($restrictedToField), '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;
    }
}
