<?php

namespace MtcPharmacy\Subscriptions\Console\Commands;

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

/**
 * Collect payments for repeat orders generated by GenerateOrdersFromSubscriptionsCommand.
 *
 * Example: php artisan subscriptions:collect_payments_for_repeat_orders
 */
class CollectPaymentsForRepeatOrdersCommand extends Command implements Isolatable
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'subscriptions:collect_payments_for_repeat_orders';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Collect payments for repeat orders generated by GenerateOrdersFromSubscriptionsCommand';

    /**
     * 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')
            ->get();

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

        foreach ($active_subscriptions as $sub) {
            $latest_order = $sub->getLatestOrder();
            if ($latest_order && !$latest_order->paid) {
                $this->info("Collecting payment for sub id:{$sub->id} / order id:{$latest_order->id}...");
                Log::info("Collecting payment for sub id:{$sub->id} / order id:{$latest_order->id}...");
                try {
                    $sub->collectPayment($latest_order);
                } catch (\Exception $e) {
                    Log::error("Failed to collect payment for sub id:{$sub->id} / order id:{$latest_order->id}: " . $e->getMessage(), ['exception' => $e]);
                    $this->error("Failed to collect payment for sub id:{$sub->id}: " . $e->getMessage());
                }
            }
        }
    }

}
