<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Mtc\Shop\Order;
use MtcPharmacy\Subscriptions\Classes\Subscription;
use MtcPharmacy\Subscriptions\Classes\SubscriptionItem;
use App\SubscriptionBundleType;
use MtcPharmacy\Subscriptions\Classes\SubscriptionPreference;


/**
 * Examples:
 *     php artisan subscriptions:generate_orders_from_subscriptions
 */


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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate orders from active subscriptions';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // TODO: expire relevant subscriptions

        $active_subscriptions = Subscription::active()->get();

        foreach ($active_subscriptions as $sub) {
            $this->info("Processing subscription id:{$sub->id}");

            $this->info(" - generating order...");
            $generated_order = $sub->generateNewOrder(false, true);
            if ($generated_order) {
                $sub->next_issue_date = null;
                $sub->save();
                $this->info(" - generated order id:{$generated_order->id}");
            } else {
                $this->info(" - no order was generated.");
            }
        }

        $this->info('Done.');
    }

}
