<?php

namespace App\Console\Commands;

use App\Mail\Digest;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class SendDigest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'digest:send {--T|test} {--D|daily} {--W|weekly} {--F|fortnightly} {--M|monthly}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send a digest of recent updates.';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if (!$this->option('daily') &&
            !$this->option('weekly') &&
            !$this->option('fortnightly') &&
            !$this->option('monthly')
        ) {
            $this->error('No schedule specified.');
            return;
        }

        $test_address = $this->option('test') ? [config('app.test_address')] : null;

        // These are seperated because I may want to send multiple types
        // of digest in a single commend.
        if ($this->option('daily')) {
            foreach (($test_address ?? config('app.daily_digest_recipients')) as $recipient) {
                Log::debug("Daily digest email sent to '{$recipient}'.");
                Mail::to($recipient)->send(new Digest('daily', config('app.current_trip_id')));
            }
        }

        if ($this->option('weekly')) {
            foreach (($test_address ?? config('app.weekly_digest_recipients')) as $recipient) {
                Log::debug("Weekly digest email sent to '{$recipient}'.");
                Mail::to($recipient)->send(new Digest('weekly', config('app.current_trip_id')));
            }
        }

        if ($this->option('fortnightly')) {
            foreach (($test_address ?? config('app.fortnightly_digest_recipients')) as $recipient) {
                Log::debug("Fortnightly digest email sent to '{$recipient}'.");
                Mail::to($recipient)->send(new Digest('fortnightly', config('app.current_trip_id')));
            }
        }

        if ($this->option('monthly')) {
            foreach (($test_address ?? config('app.monthly_digest_recipients')) as $recipient) {
                Log::debug("Monthly digest email sent to '{$recipient}'.");
                Mail::to($recipient)->send(new Digest('monthly', config('app.current_trip_id')));
            }
        }
    }
}