<?php

namespace App\Console\Commands;

use App\Repositories\CompanyOrderRepository;
use App\Repositories\PreferenceRepository;
use App\Repositories\SubscriptionRepository;
use App\Subscription;
use Carbon\Carbon;
use Illuminate\Console\Command;

class GenerateUpcomingRenewalSubscriptionCompanyOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generate:company-order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate company orders for subscriptions that will be automatically renewed.';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        foreach(Subscription::all() as $s) {
            $bool1 = ($s->active) ? 1 : 0; //la suscripcio esta activa
            $bool2 = ($s->plan && $s->plan->stripe_id!=null) ? 1 : 0;//te un plan assignat que esta a stripe
            $bool3 = ($s->stripe_id!=null) ? 1 : 0; //subscription has a stripe identifier
            $bool4 = ($s->end_date && Carbon::now() >= $s->end_date->addDays(-(PreferenceRepository::find("generate_company_orders_before_renew")->value))) ? 1 : 0; //estem dins el periode de poder generar el seguent order
            $bool5 = ($s->plan->total!=null && $s->plan->total > 0) ? 1 : 0; //es una subscripcio de pago
            $bool6 = (SubscriptionRepository::getOrderToPay($s->id)==null) ? 1 : 0; //no s'ha generat un company order anteriorment
            $bool7 = ($s->company->stripe_id != null && $s->company->stripe_payment_method_id) ? 1 : 0; //te el pagament automatic configurat aquella empresa

            //Testing purposes only:
            /*if($s->id == 9 || $s->id == 10) {
                echo "$bool1 $bool2 $bool3 $bool4 $bool5 $bool5 $bool6 $bool7 \n";
            }*/

            if( $bool1 && $bool2 && $bool3 && $bool4 && $bool5 && $bool6 && $bool7 ) {
                echo "Generating for subscription #$s->id... ";
                $order = CompanyOrderRepository::create([
                    "company_id" => $s->company_id,
                    "subscription_id" => $s->id,
                    "subtotal" => $s->plan->subtotal,
                    "vat" => $s->plan->tax_amount,
                    "total" => $s->plan->total
                ]);
                echo "Company Order #$order->id generated. OK!\n";
            }
        }
        echo "Finished.\n";
    }
}
