<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Carbon\Carbon;
use App\Modules\Bookings\TaskFeedback;
use App\Seraph\Services\GlobalMailerService;

class FeedbackReminderCommand extends AbstractCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'seraph:feedback-reminder';

    /**
     * A friendly name of the command that will be used when loggin messages.
     *
     * @var string
     */
    protected $command_title = 'Feedback Reminder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sends out feedback requests once a job has been completed.';

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

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        // Mail::pretend();

        // Get tomorrows date
        $startDate = Carbon::now()->subDays(1)->toDateString();
        $this->info('Looking for feedback requests queued before: '.$startDate);

        // Get a list of repairs that are prebooks with tomorrows date - MODERNIZED
        $feedbacks = TaskFeedback::where('emailed', 0)
                                ->incomplete()
                                ->whereDate('created_at', '<=', $startDate)
                                ->get();

        if (count($feedbacks)) {
            $this->info('Found '.count($feedbacks).' feedback requests that need to be sent.');

            foreach ($feedbacks as $feedback) {
                try {
                    // Grab the client
                    $client = $feedback->task->client;
                    $this->info('Emailing '.$client->email);

                    GlobalMailerService::send('emails.alerts.feedback', ['feedback' => $feedback], function ($message) use ($client) {
                        $message->to($client->email)->subject('Computer Assistance: How did we do?')->priority(1);
                    });

                    $feedback->emailed = 1;
                    $feedback->emailed_at = Carbon::now()->toDateTimeString();
                    $feedback->save();
                } catch (Exception $e) {
                    $this->error($e->__toString());
                }
            }
        } else {
            $this->info('No feedback requests were found');
        }
    }

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

        ];
    }

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

        ];
    }
}
