<?php

namespace Daylight\Core\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\Console\Output\BufferedOutput;

class InstallCommand extends Command
{
    protected $signature = 'daylight:install';

    protected $description = 'Installation guide for Daylight E-Commerce Core';

    public function handle(): void
    {
        $this->info('Installing Daylight E-Commerce Core..');

        $output = new BufferedOutput;

        Artisan::call('vendor:publish', [
            '--provider' => "Spatie\Permission\PermissionServiceProvider",
        ], $output);

        Artisan::call('vendor:publish', [
            '--provider' => "Spatie\LaravelSettings\LaravelSettingsServiceProvider",
            '--tag' => 'migrations',
        ], $output);

        Artisan::call('vendor:publish', [
            '--provider' => "Spatie\LaravelSettings\LaravelSettingsServiceProvider",
            '--tag' => 'config',
        ], $output);

        Artisan::call('daylight:publish-assets', [], $output);

        // Migrations
        if ($this->confirm('Would you like to publish the config files?', true)) {
            Artisan::call('vendor:publish', [
                '--provider' => "Daylight\Core\DaylightServiceProvider",
                '--tag' => 'daylight.config',
            ], $output);
        }

        // Migrations
        if ($this->confirm('Would you like to run migrations?', true)) {
            Artisan::call('migrate', [], $output);
        }

        if ($this->confirm('Would you like to seed the database with default information?', true)) {
            Artisan::call('db:seed', [
                '--class' => 'Daylight\\Core\\Database\\Seeders\\DatabaseSeeder',
            ], $output);
        }

        if ($this->confirm('Would you like to create a super admin user?', true)) {
            $name = $this->ask('First name');
            $lastName = $this->ask('Last name');
            $email = $this->ask('Email');
            $password = $this->secret('Password', 'password');

            $user = (daylightModel('customer'))::first()->users()->updateOrCreate([
                'email' => $email,
            ], [
                'name' => $name,
                'last_name' => $lastName,
                'password' => Hash::make($password),
            ]);

            $user->markEmailAsVerified();
            $user->assignRole('System Administrator');
        }

        Artisan::call('cache:clear');

        $this->info('Installation completed successfully. Happy coding!');
    }
}
