<?php

namespace App\Modules\Bookings;

use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Seraph\Services\GlobalMailerService;

class SladeLegalEvents
{
    private $sendTo = 'amanda.hodson@slade-legal.co.uk';

    /**
     * Workflow triggered when saving a task.
     *
     * @param  App\Modules\Bookings\Task $model
     *
     * @return bool
     */
    public function saving($model)
    {
        if ($model->client_id != 231 || $model->client_type != 'client') {
            return;
        }

        if ($model->type != 'support' || $model->status_id != 10) { // only works on work completed
            return;
        } // Only send emails if this is a remote support

        if ($model->completed && $model->isDirty('completed')) {
            $this->sendEmail($model);
        }
    }

    /**
     * Send an email to the main account.
     *
     * @param  App\Modules\Bookings\Task $model
     *
     * @return void
     */
    private function sendEmail($model)
    {
        try {
            GlobalMailerService::send(
                'emails.tasks.completed-public', [
                    'task' => $model,
                ],
                function ($message) use ($model) {
                    $message->to($this->sendTo)
                            ->subject(sprintf('A support ticket has been closed [%s]', $model->id));
                }
            );

            Log::info(sprintf('Successfully emailed %s that task %s has been marked as completed.', $this->sendTo, $model->id));
        } catch (Exception $e) {
            Log::error($e);
        }
    }
}
