<?php

namespace App\Console\Commands;

use App\Modules\Clients\Client;
use App\Modules\Clients\Customer;
use App\Modules\Clients\Events\DynamicsClientSync;
use App\Modules\Clients\Events\DynamicsCustomerSync;
use Illuminate\Console\Command;

class SyncCrmContacts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:crm-contacts';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Synchronizes all the customers from Seraph with Microsoft Dynamics CRM.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('This will update or create new clients and customers in Microsoft Dynamics CRM.');

        if ($this->confirm('Do you wish to continue?')) {
            $this->syncClients();
            $this->syncCustomers();
        }
    }

    /**
     * Synchronizes all the clients with the CRM.
     *
     * @return void
     */
    protected function syncClients()
    {
        $clients = Client::all();
        $service = new DynamicsClientSync();
        $bar = $this->output->createProgressBar($clients->count());

        $clients->each(function($client) use ($service, $bar) {
            $service->sendToDynamicsCrm($client);
            $bar->advance();
        });

        $bar->finish();
        $this->info('Completed synchronizing clients.');
    }

    /**
     * Synchronizes all the customers with the CRM.
     *
     * @return void
     */
    protected function syncCustomers()
    {
        $service = new DynamicsCustomerSync();
        $bar = $this->output->createProgressBar(Customer::count());

        Customer::chunk(500, function($customers) use ($service, $bar) {
            $customers->each(function($client) use ($service, $bar) {
                $service->sendToDynamicsCrm($client);
                $bar->advance();
            });
        });

        $bar->finish();
        $this->info('Completed synchronizing customers.');
    }
}
