<?php

namespace App\Extensions;

use Carbon\Carbon;
use Laravel\Cashier\Payment;
use Laravel\Cashier\Subscription;
use Laravel\Cashier\SubscriptionBuilder;

class CustomSubscriptionBuilder extends SubscriptionBuilder {

    protected $current_period_start;

    public function create($paymentMethod = null, array $options = []) {
        //1. Check and get parameters
        $subscription = $options["subscription"];
        if(!$subscription) throw new \Exception("You must provide a company/user subscription in order to set metadata.");
        unset($options["subscription"]);

        //2. Set metadata
        $this->metadata = [];
        if(isset($options["subscription_id"])) {
            $this->metadata["subscription_id"] = $options["subscription_id"];
            unset($options["subscription_id"]);
        }
        elseif(isset($options["user_subscription_id"])) {
            $this->metadata["user_subscription_id"] = $options["user_subscription_id"];
            unset($options["user_subscription_id"]);
        }

        //3. Get customer
        $customer = $this->getStripeCustomer($paymentMethod, $options);

        //4. Create subscription on stripe
        /** @var \Stripe\Subscription $stripeSubscription */
        $stripeSubscription = $customer->subscriptions->create($this->buildPayload());

        //5. Actualitzem subscription local
        $subscription->name = $this->name;
        $subscription->stripe_id = $stripeSubscription->id;
        $subscription->stripe_status = $stripeSubscription->status;
        $subscription->stripe_plan = $this->plan;
        $subscription->quantity = $this->quantity;
        $subscription->save();

        /*if ($subscription->incomplete()) {
            (new Payment(
                $stripeSubscription->latest_invoice->payment_intent
            ))->validate();
        }*/

        return $subscription;
    }
}
