<?php

namespace App\Console\Commands;

use App\Repositories\BoxSettingsRepository;
use App\Repositories\CompanyRepository;
use App\Repositories\UserSubscriptionRepository;
use App\StripeUser;
use App\UserSubscription;
use Carbon\Carbon;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate box 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(UserSubscription::all() as $us) {
            $box=null;
            $bool1 = ($us->active) ? 1 : 0; //la suscripcio esta activa
            $bool2 = ($us->end_date!=null) ? 1 : 0; //la suscripcio no es ilimitada
            $bool3 = ($us->pricing && $us->pricing->stripe_id!=null && sizeof($us->pricing->boxes) > 0 && ($box = $us->pricing->boxes[0])) ? 1 : 0;//te un pricing assignat que esta a stripe i associat a un box
            $bool4 = ($us->stripe_id!=null) ? 1 : 0; //user subscription has a stripe identifier
            $bool5 = ($box && $bool2 && Carbon::now() >= $us->end_date->addDays(-($box->generate_box_orders_before_renew))) ? 1 : 0; //estem dins el periode de poder generar el seguent order
            $bool6 = ($us->price!=null && $us->price > 0) ? 1 : 0; //es una subscripcio de pago
            $bool7 = (UserSubscriptionRepository::paymentToPay($us->id)==null) ? 1 : 0; //no s'ha generat un box order anteriorment
            $bool8 = ($us->renew == true) ? 1 : 0; //vol ser renovat
            $bool9 = ($bool3 && ($stripe_user = StripeUser::where([["user_id", $us->user_id],["company_id", $box->company_id]])->first()) && $stripe_user->stripe_payment_method_id != null) ? 1 : 0; //te el pagament automatic configurat amb aquella empresa
            $bool10 = ($bool3 && $box->company->stripe_id != null) ? 1 : 0;

            //Testing purposes only:
            /*if($us->id == 81 || $us->id == 80) {
                echo "$bool1 $bool2 $bool3 $bool4 $bool5 $bool5 $bool6 $bool7 $bool8 $bool9 $bool10 \n";
            }*/

            if( $bool1 && $bool2 && $bool3 && $bool4 && $bool5 && $bool6 && $bool7 && $bool8 && $bool9 && $bool10) {
                echo "Generating for subscription #$us->id... ";
                $box_order = UserSubscriptionRepository::createUserSubscriptionBoxOrder($us->id, $us->user_id, $box->id, $us->pricing);
                echo "Box Order #$box_order->id generated. OK!\n";
            }
        }
        echo "Finished.\n";
    }
}
