<?php

namespace MtcPharmacy\Subscriptions\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use MtcPharmacy\Subscriptions\Classes\Subscription;

/**
 * Send reminder emails to members about upcoming subscription renewals.
 *
 * Example: php artisan subscriptions:send_subscription_update_reminder
 */


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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send email for subscription update reminder';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info(__METHOD__);

        $active_subscriptions = Subscription::active()
            ->whereNotNull('next_issue_date')
            ->whereDate('next_issue_date', '=', Carbon::now()->addDays(Subscription::ORDER_CREATE_DAYS_BEFORE_DISPATCH + 2)->format('Y-m-d'))
            ->get();

        if (count($active_subscriptions) === 0) {
            $this->info('Done.');
            return;
        }

        foreach ($active_subscriptions as $sub) {
            $this->info('Sent Subscription Update Reminder Email to ' . $sub->member->email . ' for #' . $sub->id);
            // Send an email for assessment
            $sub->emailSubscriptionUpdates(
                'Update Your Subscription If Needed',
                'update_subscription_reminder',
            );
        }

    }

}
