<?php namespace App\Console\Commands;

use Formatter;
use Illuminate\Console\Command;
use Tobuli\Entities\DeviceService;
use Tobuli\Entities\EmailTemplate;
use Tobuli\Entities\SmsTemplate;

use Bugsnag\BugsnagLaravel\BugsnagFacade as Bugsnag;

class CheckServiceCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'service:check';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check service expiration command.';

    private $smsTemplate;

    private $emailTemplate;

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $this->smsTemplate = SmsTemplate::where('name', 'service_expiration')->first();
        $this->emailTemplate = EmailTemplate::where('name', 'service_expiration')->first();

        $services = DeviceService::expireByDays('device_services.remind_date')
            ->notSend()
            ->notExpired()
            ->get();

        foreach ($services as $service) {
            $this->sendEventInfo($service);
        }


        $services = DeviceService::expireByOdometer('device_services.remind')
            ->notSend()
            ->notExpired()
            ->get();

        foreach ($services as $service) {
            $this->sendEventInfo($service);
        }


        $services = DeviceService::expireByEngineHours('device_services.remind')
            ->notSend()
            ->notExpired()
            ->get();

        foreach ($services as $service) {
            $this->sendEventInfo($service);
        }

        return 'DONE';
    }

    private function sendEventInfo($service)
    {
        if ($service->user)
            Formatter::byUser($service->user);
        else
            Formatter::byDefault();

        try {
            sendTemplateEmail($service->email, $this->emailTemplate, $service);
        } catch (\Exception $e) {
            Bugsnag::notifyException($e);
        }

        try {
            sendTemplateSMS($service->mobile_phone, $this->smsTemplate, $service, $service->user_id);
        } catch (\Exception $e) {
            Bugsnag::notifyException($e);
        }

        $service->update(['event_sent' => 1]);
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array();
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array();
    }
}
