<?php

namespace App\Console\Commands;


use Illuminate\Console\Command;


use MtcPharmacy\Subscriptions\Classes\Subscription;



/**
 * 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.');
    }
}
