<?php

namespace App\Console\Commands;

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

class DatabaseUpdate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'database:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Apply database updates for schema changes and data migrations';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting database updates...');

        // Apply all update methods
        $this->renameAssociationToPlatformOrganization();
        $this->addLocationNotSpecifiedCountry();

        $this->info('Database updates completed successfully!');

        return 0;
    }

    /**
     * Rename 'Association' to 'Timebank Organization' across the database
     * Updates categories table from Association/PlatformOrganization to TimebankOrganization
     * Updates category_translations table with proper translations
     */
    private function renameAssociationToPlatformOrganization()
    {
        $this->info('Renaming Association to Timebank Organization...');

        try {
            DB::beginTransaction();

            // Update categories table: change type from Association to TimebankOrganization
            $categoriesUpdated = DB::table('categories')
                ->where('type', 'SiteContents\\Static\\Association')
                ->update(['type' => 'SiteContents\\Static\\TimebankOrganization']);

            if ($categoriesUpdated > 0) {
                $this->info("  ✓ Updated {$categoriesUpdated} category record(s) from Association");
            }

            // Also update any PlatformOrganization entries to TimebankOrganization
            $platformUpdated = DB::table('categories')
                ->where('type', 'SiteContents\\Static\\PlatformOrganization')
                ->update(['type' => 'SiteContents\\Static\\TimebankOrganization']);

            if ($platformUpdated > 0) {
                $this->info("  ✓ Updated {$platformUpdated} category record(s) from PlatformOrganization");
            }

            if ($categoriesUpdated === 0 && $platformUpdated === 0) {
                $this->warn('  ℹ No categories found to update');
            }

            // Update category_translations table
            // Get the category ID for TimebankOrganization
            $category = DB::table('categories')
                ->where('type', 'SiteContents\\Static\\TimebankOrganization')
                ->first();

            if ($category) {
                $translations = [
                    'en' => [
                        'name' => 'Timebank organization page',
                        'slug' => 'timebank-organization-page',
                    ],
                    'nl' => [
                        'name' => 'Timebank organisatie pagina',
                        'slug' => 'timebank-organisatie-pagina',
                    ],
                    'de' => [
                        'name' => 'Timebank-Organisation Seite',
                        'slug' => 'timebank-organisation-seite',
                    ],
                    'es' => [
                        'name' => 'Organización de Timebank página',
                        'slug' => 'organizacion-de-timebank-pagina',
                    ],
                    'fr' => [
                        'name' => 'Organisation de Timebank page',
                        'slug' => 'organisation-de-timebank-page',
                    ],
                ];

                $translationsUpdated = 0;
                foreach ($translations as $locale => $data) {
                    $updated = DB::table('category_translations')
                        ->where('category_id', $category->id)
                        ->where('locale', $locale)
                        ->update([
                            'name' => $data['name'],
                            'slug' => $data['slug'],
                        ]);

                    $translationsUpdated += $updated;
                }

                if ($translationsUpdated > 0) {
                    $this->info("  ✓ Updated {$translationsUpdated} category translation(s) (name and slug)");
                } else {
                    $this->warn('  ℹ No category translations found to update');
                }
            }

            DB::commit();

            $this->info('  ✓ Renamed to Timebank Organization successfully');

        } catch (\Exception $e) {
            DB::rollBack();
            $this->error('  ✗ Failed to rename: ' . $e->getMessage());
        }
    }

    /**
     * Add the "Location not specified" placeholder country (id=10, code=XX) with translations.
     * Used for profiles whose Cyclos country was unmapped (code 863).
     */
    private function addLocationNotSpecifiedCountry()
    {
        $this->info('Adding "Location not specified" placeholder country...');

        try {
            DB::beginTransaction();

            DB::table('countries')->upsert(
                [['id' => 10, 'code' => 'XX', 'flag' => '🌐', 'phonecode' => '']],
                ['id']
            );

            $locales = [
                ['id' => 37, 'locale' => 'en', 'name' => '~ Location not specified'],
                ['id' => 38, 'locale' => 'nl', 'name' => '~ Locatie niet opgegeven'],
                ['id' => 39, 'locale' => 'fr', 'name' => '~ Emplacement non précisé'],
                ['id' => 40, 'locale' => 'es', 'name' => '~ Ubicación no especificada'],
                ['id' => 41, 'locale' => 'de', 'name' => '~ Standort nicht angegeben'],
            ];

            foreach ($locales as $locale) {
                DB::table('country_locales')->upsert(
                    [['id' => $locale['id'], 'country_id' => 10, 'name' => $locale['name'], 'alias' => null, 'locale' => $locale['locale']]],
                    ['id']
                );
            }

            DB::commit();

            $this->info('  ✓ "Location not specified" country added/updated');

        } catch (\Exception $e) {
            DB::rollBack();
            $this->error('  ✗ Failed to add location not specified country: ' . $e->getMessage());
        }
    }
}
