<?php

namespace App\Jobs;

// These are the classes we need to import for our job to work
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\UserSubscriber; // Your model for tracking user subscriptions
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class CheckBazaarSubscription implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    // This variable will hold the user's subscription details
    protected $userSubscriber;

    /**
     * This is the constructor. It runs when we first create the job.
     * We pass the user's subscription data here so the job knows what to check.
     */
    public function __construct(UserSubscriber $userSubscriber)
    {
        $this->userSubscriber = $userSubscriber;
    }

    /**
     * This is the main part of the job that does the work.
     * Laravel will automatically run this 'handle' method in the background.
     */
    public function handle()
    {
        // Get the purchase token from the subscription details we received
        $purchase_token = $this->userSubscriber->purchase_token;
        $package_name = 'com.razzaghi.lawbook.android'; // Your app's package name

        // If there's no purchase token, we can't do anything, so we stop.
        if (!$purchase_token) {
            Log::info('Job skipped: No purchase token for UserSubscriber ID: ' . $this->userSubscriber->id);
            return;
        }

        // This is the URL for the external subscription API
        $url = "https://pardakht.cafebazaar.ir/devapi/v2/api/applications/{$package_name}/active-subscriptions/{$purchase_token}";

        // We use a try-catch block to handle any potential errors gracefully
        try {
            // Make the API call using Laravel's built-in HTTP client
            $response = Http::withHeaders([
                // IMPORTANT: Replace this with your actual secret key!
                'CAFEBAZAAR-PISHKHAN-API-SECRET' => 'eyJhbGciOiJIUzI1NiIsImtpZCI6ImFuY2llbnQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJuYXNoZXItcGlzaGtoYW4tYXBpIiwiaWF0IjoxNzQwMjQ3NTMzLCJleHAiOjQ4OTM4NDc1MzMsImFwaV9hZ2VudF9pZCI6MzQ2NX0.UCrr3IHxCqn77ckxfnaubrsyCfrhPm18gJgyg1qNqwA',
            ])->get($url);

            // Check if the API call was successful
            if ($response->successful()) {
                $data = $response->json();

                // Check if the subscription is still valid according to the API response
                if (isset($data['subscriptions'][0]['validUntilTimestampMsec']) && $data['subscriptions'][0]['validUntilTimestampMsec'] > now()->timestamp * 1000) {

                    // Convert the expiration date from the API into a standard format
                    $bazaarExpiredAt = Carbon::createFromTimestampMs($data['subscriptions'][0]['validUntilTimestampMsec']);

                    // If the expiration date in our database is different, update it
                    if ($this->userSubscriber->expired_at->notEqualTo($bazaarExpiredAt)) {
                        $this->userSubscriber->update(['expired_at' => $bazaarExpiredAt]);
                        Log::info('Subscription date updated for user: ' . $this->userSubscriber->user_id);
                    }
                } else {
                    // If the subscription is no longer valid, update it in our database to expire now
                    $this->userSubscriber->update(['expired_at' => now()]);
                    Log::warning('Subscription found expired on Bazaar for user: ' . $this->userSubscriber->user_id);
                }
            } else {
                 // If the API call failed, log the error for debugging
                 Log::error('Failed to fetch subscription from Bazaar', ['status' => $response->status(), 'body' => $response->body()]);
            }

        } catch (\Exception $e) {
            // If something else went wrong (e.g., network error), log it
            Log::error('Exception while checking Bazaar subscription', ['error' => $e->getMessage()]);
        }
    }
}