<?php

namespace App\Modules\Bookings;

use Illuminate\Console\Command;

use App\Modules\Bookings\TaskFeedback;
use App\Modules\Bookings\Task;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use App\Seraph\Services\GlobalMailerService;

class FeedbackReceived
{

    /**
 * Create a new job instance.
 *
 * @param  TaskFeedback $taskFeedback
 * @return void
 */

  protected $taskFeedback;

    /**
     * email destinations depending on task type
     *
     * @var \App\Modules\Bookings\TaskFeedback;
     */

    protected $destinations = [
      'support' => 'supportManager@computerassistance',
      'repairs' => 'repairManager@computerassistance',
      'onsite' => 'onsiteManager@computerassistance',
    ];

      /**
     * Subscribe to events.
     *
     * @param  mixed $events
     *
     * @return null
     */
    public function subscribe($events)
    {
        $events->listen('FeedbackReceived', 'App\Modules\Bookings\FeedbackReceived@fire');
    }

    /**
     * Fire the event.
     *
     * @param  \App\Modules\Bookings\TaskFeedback $taskFeedback
     *
     * @return void
     */
    public function fire($feedback)
    {

      // config/emails.php

      // 'feedback' => [
    	// 	'repairs'    => ['emma@computerassistance.co.uk','junaid@computerassistance.co.uk'],
    	// 	'repairs_cc' => ['raphael@computerassistance.uk.com'],
    	// 	'support'    => ['cathren@computerassistance.uk.com','junaid@computerassistance.co.uk'],
    	// 	'support_cc' => ['raphael@computerassistance.uk.com'],
    	// ],

        // echo "feedback object";
        // print_r($feedback,false);


      $task = $feedback->task;

      $client = $task->client;


      if($task->type == 'repair') {
        $mailTo = config('emails.feedback.repairs');
      }
      else if ($task->type == 'support') {
        $mailTo = config('emails.feedback.support');
      }
      else {
        $mailTo = config('emails.support');
      }

      // $mailTo[0] is the dept manager
      $manager = User::where('email', 'like', substr($mailTo[0], 0, 8).'%')->first();

      $user = $task->user;

      GlobalMailerService::send('emails.alerts.feedback_received', ['manager' => $manager, $subject = 'Feedback received for ' . $task->type. ' task: ' . $task->id, 'task' => $task, 'feedback' => $feedback, 'whoTo' => $mailTo, 'user' => $user, 'client' => $client] , function ($message) use ($mailTo, $user, $subject, $client) {
        $message->to($mailTo[0])->cc($mailTo[1])->subject($subject);
    });

    }

}
