<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Console\Commands\AbstractCommand;
use App\Modules\Bookings\Support;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Seraph\Services\GlobalMailerService;

class UntouchedReminderCommand extends AbstractCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'untouched:reminder';

    protected $command_title = 'SupportUntouchedReminders';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sends a reminder email for all the jobs that haven\'t been touched for at less 24 hours.';

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

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $date = Carbon::now()->subHours(24)->toDateTimeString();
        $untouchedTasks = [];
        $users = Group::findOrFail(11)->users()->pluck('id');

        $tasks = Support::support()->where('completed', 0)->where('updated_at', '<', $date)->whereIn('assigned_to', $users)->orderBy('assigned_to', 'updated_at', 'DESC')->get();

        foreach ($tasks as $task) {

            // Check for comments
            if ($task->comments()->where('created_at', '>', $date)->count() > 0) {
                continue;
            }

            // Check for re-assignments
            if ($task->assigned_changes()->where('created_at', '>', $date)->count() > 0) {
                continue;
            }

            array_push($untouchedTasks, $task);
        }

        if (count($untouchedTasks) > 0) {
            GlobalMailerService::send('emails.alerts.support-untouched-reminders', ['tasks' => $tasks], function ($message) {
                $message->to(config('emails.managers.support'))->subject('Untouched tasks summary.')->priority(1);
            });

            $this->info('['.Carbon::now()->toDateTimeString().'] Email successfully sent! Count: '.count($tasks));
        } else {
            $this->info('['.Carbon::now()->toDateTimeString().'] No remote support jobs found that require notification');
        }
    }

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

        ];
    }

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

        ];
    }
}
