<?php

namespace App\Jobs\StripeWebhooks;

use App\Models\SubscriptionServicePackage;

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Spatie\WebhookClient\Models\WebhookCall;
use Stripe\Service\SubscriptionService;

class SubscriptionRenewedJob implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    /** @var \Spatie\WebhookClient\Models\WebhookCall */
    public $webhookCall;

    public function __construct(WebhookCall $webhookCall)
    {
        $this->webhookCall = $webhookCall;
    }

    public function handle()
    {
        Log::info('Renew Job fired');
        // Log::info($this->webhookCall->payload['data']['object']['subscription']);

        $event_data = $this->webhookCall->payload['data']['object'];


        if ($event_data['subscription']) {
            Log::info($event_data);
            $last_sub = SubscriptionServicePackage::where('stripe_subscription_id', $this->webhookCall->payload['data']['object']['subscription'])->latest()->first();

            if ($last_sub) {
                try {
                    DB::beginTransaction();
                    $subService = new \App\Services\SubscriptionService();
                    $end_date = Carbon::parse($event_data['period_end']);
                    $stripe_subscription_id = $event_data['subscription'];
                    $stripe_invoice_id = $event_data['id'];
                    $subService->subscriptionRenew(
                        $end_date,
                        $last_sub,
                        $stripe_subscription_id,
                        $stripe_invoice_id
                    );

                    $subService->clientSubscriptionUpdate(
                        $last_sub->client_id,
                        $end_date
                    );

                    $last_sub->update([
                        'status' => 'expired'
                    ]);

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    Log::error($e->getMessage());
                }
            }
        }{
            Log::info('Subscription not found');
        }
    }
}
