<?php

namespace Ignite\Core\Database\Seeders;

use Ignite\Core\Entities\User;
use Ignite\Core\Entities\Participant;

/**
 * php artisan db:seed --class="Ignite\Core\Database\Seeders\ParticipantTableSeeder"
 * php artisan module:seed Core
 */
class ParticipantTableSeeder extends AbstractSeeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        parent::run();

        $strategy = $this->strategy('json', [
            'filepath' => $this->getFilepath('core_participant.json')
        ]);

        /** @var \Illuminate\Support\Collection $sources */
        $sources = $strategy->run();

        foreach ($sources as $source) {
            try {
                if ($source['email'] === 'it@brightspot.email') {
                    $source['email'] = config('core.admin.email', 'it@brightspot.email');
                }

                $user = User::where('email', $source['email'])->firstOrFail();
                $source['user_id'] = $user->getKey();
                $source['email'] = $user->email;
                if (! $user->participant) {
                    $source['approved_at'] = date('Y-m-d H:i:s');
                }

                Participant::updateOrCreate(
                    ['email' => $source['email']],
                    $source
                );
            } catch (\Exception $e) {
                echo json_encode($source) . PHP_EOL;
                echo $e->getMessage() . PHP_EOL;
                continue;
            }
        }
    }
}
