<?php

namespace App\Console\Commands;

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

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $remote = DB::connection('remote');
        $local  = DB::connection('mysql');

        $audiences  = $remote->table('audiences')->get();
        $people     = $remote->table('people')->get();

        $audiences->each(function($item) use (&$local) {
            $_item = $local->table('audiences')->find($item->id);
            if ($_item == null)
            {
                $local->table('audiences')->insert([
                    'id'        => $item->id,
                    'name'      => $item->name,
                    'user_id'   => $item->user_id,
                    'mode'      => $item->mode,
                    'nodes'     => $item->nodes,
                    'filters'   => $item->filters,
                    'created_at'=> $item->created_at
                ]);
            }
        });

        $people->each(function($per) use (&$local) {
            $_per = $local->table('people')->find($per->id);
            if ($_per == null)
            {
                $local->table('people')->insert([
                    'id'        => $per->id,
                    'first_name'=> $per->first_name,
                    'last_name' => $per->last_name,
                    'full_name' => $per->full_name,
                    'email'     => $per->email,
                    'phone_number'=> $per->phone_number,
                    'meta'      => $per->meta,
                    'created_at'=> $per->created_at
                ]);
            }
        });
    }
}
