<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Tobuli\Entities\Subscription;
use Tobuli\Helpers\Payments\Payments;


class CheckSubscriptionsCommand extends Command
{
    const SUB_DAYS = 7;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Handle expired subscriptions';

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

    /**
     * Execute the command.
     *
     * @return void
     */
    public function fire()
    {
        $subscriptions = Subscription::subscribable()->where('active', 1)
            ->where('expiration_date', '<', date('Y-m-d'))
            ->where('expiration_date', '>', Carbon::now()->subDays(self::SUB_DAYS))
            ->with('user', 'billing_plan')
            ->get();

        if ($subscriptions->isEmpty()) {
            echo 'Done';
            return;
        }

        $payments = new Payments();

        foreach ($subscriptions as $subscription) {
            if (is_null($subscription->user) || is_null($subscription->billing_plan)) {
                $subscription->cancel();
                continue;
            }

            $is_active = $payments->setGateway($subscription->gateway)
                ->isSubscriptionActive($subscription);

            if ( ! $is_active)
                continue;

            $payments->renewSubscription($subscription);
        }

        echo 'Done';
    }
}
