<?php

namespace App\Helpers\FirstParty\Purchase;

use App\Helpers\FirstParty\Credits\CreditsHelper;
use App\Helpers\FirstParty\Credits\CreditsService;
use App\Helpers\FirstParty\Stripe\StripeHelper;
use App\Models\PaymentWebhookProcessedLog;
use Laravel\Cashier\Events\WebhookReceived;

class CreditsPurchaseHelper
{
    public static function handleWebhookEvents(WebhookReceived $event)
    {

        switch (StripeHelper::getEventType($event)) {
            case 'checkout.session.completed':
                self::handleCheckoutSessionCompleted($event);
                break;
        }
    }

    private static function handleCheckoutSessionCompleted($event)
    {

        $object = StripeHelper::getEventObject($event);

        // Check if the webhook has already been processed
        $payment_webhook_processed_log = PaymentWebhookProcessedLog::where('provider', 'stripe')
            ->where('log_id', $object['id'])
            ->where('log_type', 'checkout_session')
            ->first();

        if (! is_null($payment_webhook_processed_log)) {
            return;
        }

        // Get the user associated with the checkout session
        $user = StripeHelper::getUserByStripeID($object['customer']);

        if ($user) {

            // Get the line items from the checkout session
            StripeHelper::setStripeApiKey();
            $lineItems = \Stripe\Checkout\Session::allLineItems($object['id']);

            // dd($lineItems);

            foreach ($lineItems->data as $lineItem) {
                $stripe_price_id = $lineItem->price->id;

                // Get the credit pack associated with the price ID
                $credit_pack = CreditsHelper::getCreditPackByStripePriceId($stripe_price_id);

                if (is_null($credit_pack)) {
                    continue;
                }

                $total_credits = PurchaseHelper::getPlanSystemProperty($credit_pack, 'credits');

                // Deposit the credits to the user's account
                CreditsService::depositAlacarte($user->id, $total_credits, "Purchased {$credit_pack['name']}");
            }
        }

        // Mark the webhook as processed
        PaymentWebhookProcessedLog::create([
            'provider' => 'stripe',
            'log_id' => $object['id'],
            'log_type' => 'checkout_session',
        ]);
    }
}
