<?php

namespace App\Services;

use App\Repos\SettingRepo;
use Stripe\Stripe;
use Stripe\Price;
use Stripe\Checkout\Session;
use Stripe\Webhook;
use Stripe\Customer;
use Stripe\Subscription;

class StripeService
{
    public static function auth()
    {
        $stripeKey = SettingRepo::findByNameOrFail('stripe_key');
        Stripe::setApiKey($stripeKey->value);
    }

    public static function createCustomer(string $name, string $email)
    {
        self::auth();
        return Customer::create([
            'name' => $name,
            'email' => $email,
        ]);
    }

    public static function createSession(string $customerId, string $priceId)
    {
        self::auth();
        $price = Price::retrieve($priceId);
        $payload = [
            'customer' => $customerId,
            'line_items' => [[
                'price' => $price->id,
                'quantity' => 1,
            ]],
            'mode' => 'subscription',
            'success_url' => url('payment?status=success'),
            'cancel_url' => url('payment?status=canceled'),
            'customer_update' => [
                'address' => 'auto',
            ],
        ];
        $session = Session::create($payload);
        return $session->url;
    }

    public static function webhookEvent(string $payload, string $sigHeader)
    {
        self::auth();
        $secret = SettingRepo::findByNameOrFail('stripe_webhook_secret');
        return Webhook::constructEvent(
            $payload,
            $sigHeader,
            $secret->value
        );
    }

    public static function retriveSubscription(string $id)
    {
        self::auth();
        return Subscription::retrieve($id);
    }

    public static function cancelSubscription(string $id)
    {
        self::auth();
        $subscription = new Subscription($id);
        return $subscription->cancel();
    }
}
