<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Modules\Bookings\TaskFeedback;
use App\Console\Commands\AbstractCommand;



class SendReminder extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'feedback:sendreminder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send a feedback (on google) reminder email';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            $feedbacks = TaskFeedback::where('rating', '>=', '4')->where('reminder_sent', '=', 0)->get();
        } catch (Exception $e){
            $this->error('Something went wrong when attempting to query the database');
            $this->error($e->getMessage());
            $this->error($e->getTrace());
            return false;
        }

        foreach ($feedbacks as $item){

            $customersEmail = $item->task->client->email;

            try {
                \App\Seraph\Services\GlobalMailerService::send(
                    'emails.alerts.feedback_request', [],
                    function ($message) use ($customersEmail) {
                        $message->to($customersEmail)->subject('Thank you for your feedback');
                });
            } catch (Exception $e){
                $this->error('Something went wrong when attempting to send an email');
                $this->error($e->getMessage());
                $this->error($e->getTrace());
                return false;
            }

            $this->info('Reminder sent to ' . $customersEmail . ' from ' . $mailFrom);

            try{
                TaskFeedback::where('task_id', '=', $item->task_id)->update(array('reminder_sent' => 1));
            } catch (Exception $e){
                $this->error('Something went wrong when attempting to update the database');
                $this->error($e->getMessage());
                $this->error($e->getTrace());
                return false;
            }

        }

        $this->info('All reminder emails sent');

        return true;

    }
}
