<?php

namespace App\Console\Commands;

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

class ReadSMSCommand extends AbstractCommand
{
    /**
     * A friendly name of the command that will be used when loggin messages.
     *
     * @var string
     */
    protected $command_title = 'Attach MSN to task ';

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'read:sms';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check the sms sent to seraph and send it to the lates user sent a message to this client and the user who has assigned the task for which the notification was sent for.';

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

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        try {
            if (Config::get('sms_mail.enabled')) {
                // Try to connect to the server
                $server = new \Fetch\Server(Config::get('sms_mail.server'), Config::get('sms_mail.port'), Config::get('sms_mail.protocol'));
                $server->setParam('DISABLE_AUTHENTICATOR', 'GSSAPI');
                $server->setAuthentication(Config::get('sms_mail.username'), Config::get('sms_mail.password'));

                $messages = $server->search('UNSEEN', 5);
                // print_r($messages);


                // Login as admin
                Auth::loginUsingId(1);

                if (count($messages)) {
                    $counter = 0;
                    foreach ($messages as $message) {
                        try {
                            //Get the mobile phone number from the subject
                            $number = substr($message->getSubject(), 16, 10);

                            // Get today's date
                            $today = Carbon::now()->toDateString();

                            //Get the lates customer notification sent to this number and gets the task id to post the comment. 
                            $notification = CustomerNotification::where('type', 'sms')->where('sent_to', 'like', '%'.$number.'%')->orderBy('id', 'desc')->first();

                            if (! $notification) {
                                $this->info('['.Carbon::now()->toDateTimeString().'] There is not notifications sent for the number '.$number.'.');

                                return;
                            }

                            $to = [$notification->user->email];

                            //If the sender of the notification is not the same user than the one that has the task for which the notification has been sent to 
                            if ($notification->task->assigned_to != $notification->created_by) {
                                array_push($to, $notification->task->user->email);
                            }

                            if ($notification->task->user->email) {
                                GlobalMailerService::send('emails.alerts.sms_notification', ['sms' => $message, 'notification' => $notification], function ($message) use ($notification) {
                                    $message->to($notification->task->user->email)->subject('SMS from '.$notification->task->client->name.'.')->priority(1);
                                });

                                $counter++;
                            }
                        } catch (\Exception $e) {
                            $this->info($e);
                            Log::error($e);
                        }
                    }

                    $this->info('['.Carbon::now()->toDateTimeString().'] SMS received '.count($messages).' . Emails sent '.$counter.'.');
                } else {
                    $this->info('['.Carbon::now()->toDateTimeString().'] No sms notifications to send.');
                }
            } else {
                $this->info('Automatic SMS reader is disabled.');
            }
        } catch (\Exception $e) {
            $this->info($e);
            Log::error($e);
        }
    }
}
