<?php

namespace App\Console\Commands;

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

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rename subscription plans and remove Gold Plan';

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

        $replacements = [
            'Basic Plan (Monthly)' => 'Basic (Monthly)',
            'Basic Plan (3 Months)' => 'Basic (3 Months)',
            'Silver Plan (Monthly)' => 'Silver (Monthly)',
            'Silver Plan (3 Months)' => 'Silver (3 Months)',
        ];

        foreach ($replacements as $old => $new) {
            try {
                // Check if target name already exists
                if (DB::table('plans')->where('name', $new)->exists()) {
                    $this->warn("Skipping '$old': Target name '$new' already exists.");
                    continue;
                }

                $updated = DB::table('plans')
                    ->where('name', $old)
                    ->update(['name' => $new]);
                
                if ($updated) {
                    $this->info("Renamed: '$old' -> '$new'");
                } else {
                    $this->warn("Skipped (Not Found): '$old'");
                }
            } catch (\Exception $e) {
                $this->error("Error renaming '$old': " . $e->getMessage());
            }
        }

        try {
            $updated = DB::table('plans')->where('name', 'Gold Plan')->update(['is_active' => false]);
            if ($updated) {
                $this->info("Deactivated 'Gold Plan'");
            } else {
                $this->warn("Gold Plan not found or already inactive");
            }
        } catch (\Exception $e) {
            $this->error("Error hiding Gold Plan: " . $e->getMessage());
        }

        $this->info('Done!');
    }
}
