<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Reminder;
use App\CoiUsers;
use Carbon\Carbon;
use Mail;
use App\Mail\MtnCoiReminder;

class ReminderCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:reminder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send reminder to non-participants';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Log::info('i am running');
        $users = CoiUsers::whereNull('coi_status')->get();
        $rem = Reminder::first();
        if ($rem !==null && $rem->nextout !==null) {
          if (Carbon::parse($rem->nextout)->isPast()) {
            foreach ($users as $key) {
              if ($key->email !==null) {
                $data=[
                  'name'=>$key->name,
                  'reminder'=>$rem->reminder,
                ];
          Mail::to($key->email)->send(new MtnCoiReminder($data));
              }

            }

            // update nextout
            if ($rem->freq == 'Daily') {
              $rem->update([
                'nextout'=>Carbon::parse($rem->nextout)->addDays(1),
              ]);

            }elseif ($rem->freq == 'Weekly') {
              $rem->update([
                'nextout'=>Carbon::parse($rem->nextout)->addWeek(),
              ]);
            }elseif ($rem->freq == 'Monthly') {
              $rem->update([
                'nextout'=>Carbon::parse($rem->nextout)->addMonth(),
              ]);
            }elseif ($rem->freq == 'Yearly') {
              $rem->update([
                'nextout'=>Carbon::parse($rem->nextout)->addYear(),
              ]);
            }elseif ($rem->freq == 'None') {
              $rem->update([
                'nextout'=>null,
              ]);
            }

          }else {
            Log::info('next out is not today');
          }

        }else {
          Log::info('reminder is null or nextout is null');
        }


    }
}
