<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Models\UserPreference;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;

class CreateDefaultAdmin extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'admin:create-default';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a default admin user (admin@admin.com / password)';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $email = 'admin@admin.com';
        $password = 'password';
        $name = 'Administrator';

        // Check if admin already exists
        if (User::where('email', $email)->exists()) {
            $user = User::where('email', $email)->first();
            $user->update(['is_admin' => true]);
            $this->info("✓ User '{$user->name}' is now an admin!");
            $this->table(
                ['Field', 'Value'],
                [
                    ['Email', $user->email],
                    ['Password', 'password (existing)'],
                    ['Admin', 'Yes'],
                ]
            );
            return 0;
        }

        // Create admin user
        $user = User::create([
            'name' => $name,
            'email' => $email,
            'password' => Hash::make($password),
            'subscription_status' => 'paid',
            'is_admin' => true,
            'trial_start_date' => Carbon::now(),
            'trial_expiry_date' => Carbon::now()->addDays(14),
        ]);

        // Create default preferences
        UserPreference::create([
            'user_id' => $user->id,
            'quiet_hours_start' => Carbon::now()->setTime(18, 0),
            'quiet_hours_end' => Carbon::now()->setTime(8, 0),
            'onboarding_completed' => true,
        ]);

        $this->info('✓ Default admin user created successfully!');
        $this->newLine();
        $this->table(
            ['Field', 'Value'],
            [
                ['Name', $user->name],
                ['Email', $user->email],
                ['Password', $password],
                ['Admin', 'Yes'],
                ['Status', 'Paid'],
            ]
        );
        $this->newLine();
        $this->warn('⚠️  IMPORTANT: Change the password after first login!');
        $this->info('Login at: http://localhost/reminder/admin');
        
        return 0;
    }
}
