<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\SubscriptionMemberResource;
use App\Http\Resources\SubscriptionResource;
use App\Models\EasypaisaCustomer;
use App\Models\Product;
use App\Models\Subscription;
use App\Models\SubscriptionMember;
use DateTime;
use DateTimeZone;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SubscriptionController extends Controller
{
    // =========================================================================
    //  ENDPOINT 1 — POST /api/v1/subscriptions/create
    //
    //  Accepts:
    //    customer_id  (required)
    //    product_id   (required if variant not provided)
    //    variant      (required if product_id not provided)
    //    age          (optional years) — fallback when customer DOB is missing
    //    dependents   (optional array) — list of dependent members
    //      └─ each: name, relationship, dob (or age), gender, cnic, mobile
    //
    //  Flow:
    //   1. Validate inputs
    //   2. Resolve product
    //   3. Resolve self contribution by DOB / age
    //   4. Resolve each dependent contribution by their DOB / age
    //   5. Create subscription (pending_payment) with total_premium
    //   6. Create subscription_members rows (self + dependents)
    //   7. Call Easypaisa createPayment with total amount
    //   8. Return full response
    // =========================================================================

    public function createPendingSubscription(Request $request): JsonResponse
    {
        $request->validate([
            'customer_id'  => 'required|exists:easypaisa_customers,customer_id',
            'product_id'   => 'required_without:variant|nullable|exists:products,product_id',
            'variant'      => 'required_without:product_id|nullable|in:platinum,gold,silver,bronze',
            'age'          => 'nullable|integer|min:0|max:120',

            // Dependents array
            'dependents'                => 'nullable|array|max:10',
            'dependents.*.name'         => 'required|string|max:150',
            'dependents.*.relationship' => 'required|in:spouse,son,daughter',
            'dependents.*.dob'          => 'nullable|date|before:today',
            'dependents.*.age'          => 'nullable|integer|min:0|max:120',
            'dependents.*.gender'       => 'nullable|in:male,female,other',
            'dependents.*.cnic'         => 'nullable|string|max:15|regex:/^\d{5}-\d{7}-\d{1}$/',
            'dependents.*.mobile'       => 'nullable|string|max:20',
        ]);

        try {
            DB::beginTransaction();

            // ── 1. Load customer ──────────────────────────────────────────────
            $customer = EasypaisaCustomer::findOrFail($request->integer('customer_id'));

            // ── 2. Resolve product ────────────────────────────────────────────
            if ($request->filled('product_id')) {
                $product = Product::with(['plan', 'contributions'])
                    ->findOrFail($request->integer('product_id'));
            } else {
                $product = Product::with(['plan', 'contributions'])
                    ->where('variant', $request->input('variant'))
                    ->where('is_active', true)
                    ->whereHas('plan', fn($q) => $q->where('is_active', true))
                    ->first();

                if (!$product) {
                    return response()->json([
                        'status'  => 404,
                        'message' => 'No active product found for variant: ' . $request->input('variant'),
                    ], 404);
                }
            }

            $plan = $product->plan;

            if (!$product->is_active || !$plan->is_active) {
                return response()->json([
                    'status'  => 422,
                    'message' => 'Selected product or plan is not currently available.',
                ], 422);
            }

            // ── 3. Guard: duplicate active/pending subscription ───────────────
            $existing = Subscription::where('customer_id', $customer->customer_id)
                ->where('product_id', $product->product_id)
                ->whereIn('policy_status', [
                    Subscription::STATUS_PENDING_PAYMENT,
                    Subscription::STATUS_ACTIVE,
                ])
                ->first();

            if ($existing) {
                return response()->json([
                    'status'       => 409,
                    'message'      => 'Customer already has an active or pending subscription for this product.',
                    'subscription' => new SubscriptionResource($existing->load('customer', 'plan', 'product', 'members')),
                ], 409);
            }

            // ── 4. Resolve SELF contribution ──────────────────────────────────
            $fallbackAgeYears = $request->filled('age') ? $request->integer('age') : null;
            [$selfContribution, $selfAgeMonths] = $this->resolveContribution(
                $customer->dob,
                $product,
                $fallbackAgeYears
            );

            if (!$selfContribution) {
                return response()->json([
                    'status'  => 422,
                    'message' => 'No pricing bracket found for policy holder\'s age. Provide DOB or age.',
                ], 422);
            }

            // ── 5. Resolve DEPENDENT contributions ───────────────────────────
            $dependentsInput   = $request->input('dependents', []);
            $resolvedDependents = [];

            foreach ($dependentsInput as $index => $dep) {
                $depDob = !empty($dep['dob']) ? \Carbon\Carbon::parse($dep['dob']) : null;
                $depAge = isset($dep['age']) ? (int) $dep['age'] : null;

                [$depContribution, $depAgeMonths] = $this->resolveContribution(
                    $depDob,
                    $product,
                    $depAge
                );

                if (!$depContribution) {
                    return response()->json([
                        'status'  => 422,
                        'message' => "No pricing bracket found for dependent #{$index} ({$dep['name']}). Provide dob or age.",
                    ], 422);
                }

                $resolvedDependents[] = [
                    'name'                   => $dep['name'],
                    'member_type'            => $dep['relationship'],
                    'dob'                    => $depDob?->format('Y-m-d'),
                    'gender'                 => $dep['gender']  ?? null,
                    'cnic'                   => $dep['cnic']    ?? null,
                    'mobile'                 => $dep['mobile']  ?? null,
                    'age_in_months'          => $depAgeMonths,
                    'contribution_age_group' => $depContribution->age_group_label,
                    'premium'                => (float) $depContribution->contribution_pkr,
                    'premium_paisa'          => (int) ceil($depContribution->contribution_pkr) * 100,
                ];
            }

            // ── 6. Calculate totals ───────────────────────────────────────────
            $selfPremium      = (float) $selfContribution->contribution_pkr;
            $selfPremiumPaisa = (int) ceil($selfPremium) * 100;

            $depTotalPremium  = array_sum(array_column($resolvedDependents, 'premium'));
            $totalPremium     = $selfPremium + $depTotalPremium;
            $totalPremiumPaisa= (int) ceil($totalPremium) * 100;
            $membersCount     = 1 + count($resolvedDependents);

            // ── 7. Create subscription ────────────────────────────────────────
            $subscription = Subscription::create([
                'customer_id'            => $customer->customer_id,
                'plan_id'                => $plan->plan_id,
                'product_id'             => $product->product_id,
                'variant'                => $product->variant,
                'plan_eful_code'         => $plan->plan_eful_code,
                'efu_product_name'       => $product->efu_product_name,
                'premium'                => $selfPremium,
                'premium_paisa'          => $selfPremiumPaisa,
                'total_premium'          => $totalPremium,
                'total_premium_paisa'    => $totalPremiumPaisa,
                'members_count'          => $membersCount,
                'currency'               => 'PKR',
                'contribution_age_group' => $selfContribution->age_group_label,
                'policy_status'          => Subscription::STATUS_PENDING_PAYMENT,
                'grace_period_days'      => 30,
            ]);

            // ── 8. Create SELF member row ─────────────────────────────────────
            SubscriptionMember::create([
                'subscription_id'        => $subscription->subscription_id,
                'customer_id'            => $customer->customer_id,
                'member_type'            => SubscriptionMember::TYPE_SELF,
                'full_name'              => $customer->full_name,
                'dob'                    => $customer->dob?->format('Y-m-d'),
                'gender'                 => $customer->gender,
                'cnic'                   => $customer->cnic,
                'mobile'                 => $customer->msisdn,
                'age_in_months'          => $selfAgeMonths,
                'contribution_age_group' => $selfContribution->age_group_label,
                'premium'                => $selfPremium,
                'premium_paisa'          => $selfPremiumPaisa,
            ]);

            // ── 9. Create DEPENDENT member rows ──────────────────────────────
            foreach ($resolvedDependents as $dep) {
                SubscriptionMember::create([
                    'subscription_id'        => $subscription->subscription_id,
                    'customer_id'            => $customer->customer_id,
                    'member_type'            => $dep['member_type'],
                    'full_name'              => $dep['name'],
                    'dob'                    => $dep['dob'],
                    'gender'                 => $dep['gender'],
                    'cnic'                   => $dep['cnic'],
                    'mobile'                 => $dep['mobile'],
                    'age_in_months'          => $dep['age_in_months'],
                    'contribution_age_group' => $dep['contribution_age_group'],
                    'premium'                => $dep['premium'],
                    'premium_paisa'          => $dep['premium_paisa'],
                ]);
            }

            // ── 10. Call Easypaisa createPayment (total amount) ───────────────
            $paymentOrderId    = 'EFU-' . $subscription->subscription_id . '-' . now()->format('YmdHis');
            $paymentOrderTitle = 'EFU-' . strtoupper($product->variant) . '-' . $subscription->subscription_id;

            $paymentResponse = $this->callCreatePayment(
                $subscription->subscription_id,
                $paymentOrderId,
                $paymentOrderTitle,
                $totalPremiumPaisa   // ← total of all members
            );

            $subscription->update([
                'payment_order_id'    => $paymentOrderId,
                'payment_order_title' => $paymentOrderTitle,
                'payment_response'    => $paymentResponse,
            ]);

            DB::commit();

            Log::info('SubscriptionController@createPendingSubscription: Created.', [
                'subscription_id'    => $subscription->subscription_id,
                'customer_id'        => $customer->customer_id,
                'variant'            => $product->variant,
                'self_premium'       => $selfPremium,
                'dep_total_premium'  => $depTotalPremium,
                'total_premium'      => $totalPremium,
                'members_count'      => $membersCount,
            ]);

            return response()->json([
                'status'  => 201,
                'message' => 'Subscription created. Awaiting payment confirmation.',
                'data'    => [
                    'subscription'     => new SubscriptionResource(
                        $subscription->load('customer', 'plan', 'product', 'members')
                    ),
                    'payment_response' => $paymentResponse,
                ],
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('SubscriptionController@createPendingSubscription: Error.', [
                'message' => $e->getMessage(),
                'trace'   => $e->getTraceAsString(),
            ]);
            return response()->json([
                'status'  => 500,
                'message' => 'Failed to create subscription.',
                'detail'  => $e->getMessage(),
            ], 500);
        }
    }
    
    
    // =========================================================================
//  ENDPOINT — POST /api/v1/subscriptions/calculate-premium
//
//  Accepts:
//    product_id  (required if variant not provided)
//    variant     (required if product_id not provided)
//    self_age    (required — years, integer)
//    dependents  (optional array)
//      └─ each: name, relationship, age (years, integer)
//
//  Returns:
//    self        — { age_years, age_months, age_group, premium_pkr, premium_paisa }
//    dependents  — array of same shape + name, relationship
//    total_premium_pkr
//    total_premium_paisa
//    members_count
// =========================================================================

public function calculatePremium(Request $request): JsonResponse
{
    $request->validate([
        'product_id'               => 'required_without:variant|nullable|exists:products,product_id',
        'variant'                  => 'required_without:product_id|nullable|in:platinum,gold,silver,bronze',
        'self_age'                 => 'required|integer|min:0|max:120',

        'dependents'               => 'nullable|array|max:10',
        'dependents.*.name'        => 'nullable|string|max:150',
        'dependents.*.relationship'=> 'nullable|in:spouse,son,daughter',
        'dependents.*.age'         => 'required|integer|min:0|max:120',
    ]);

    // ── Resolve product ───────────────────────────────────────────────────
    if ($request->filled('product_id')) {
        $product = Product::with(['plan', 'contributions'])
            ->findOrFail($request->integer('product_id'));
    } else {
        $product = Product::with(['plan', 'contributions'])
            ->where('variant', $request->input('variant'))
            ->where('is_active', true)
            ->whereHas('plan', fn($q) => $q->where('is_active', true))
            ->first();

        if (!$product) {
            return response()->json([
                'status'  => 404,
                'message' => 'No active product found for variant: ' . $request->input('variant'),
            ], 404);
        }
    }

    if (!$product->is_active || !$product->plan->is_active) {
        return response()->json([
            'status'  => 422,
            'message' => 'Selected product or plan is not currently available.',
        ], 422);
    }

    // ── Resolve SELF ──────────────────────────────────────────────────────
    $selfAgeYears  = $request->integer('self_age');
    $selfAgeMonths = $selfAgeYears * 12;

    $selfContribution = $product->contributions->first(
        fn($c) => $selfAgeMonths >= $c->age_min_months
               && $selfAgeMonths <= $c->age_max_months
    );

    if (!$selfContribution) {
        return response()->json([
            'status'  => 422,
            'message' => "No pricing bracket found for self age: {$selfAgeYears} years.",
        ], 422);
    }

    $selfResult = [
        'member_type'   => 'self',
        'name'          => null,
        'relationship'  => 'self',
        'age_years'     => $selfAgeYears,
        'age_months'    => $selfAgeMonths,
        'age_group'     => $selfContribution->age_group_label,
        'premium_pkr'   => (float) $selfContribution->contribution_pkr,
        'premium_paisa' => (int) ceil($selfContribution->contribution_pkr) * 100,
    ];

    // ── Resolve DEPENDENTS ────────────────────────────────────────────────
    $dependentsInput  = $request->input('dependents', []);
    $dependentsResult = [];

    foreach ($dependentsInput as $index => $dep) {
        $depAgeYears  = (int) $dep['age'];
        $depAgeMonths = $depAgeYears * 12;

        $depContribution = $product->contributions->first(
            fn($c) => $depAgeMonths >= $c->age_min_months
                   && $depAgeMonths <= $c->age_max_months
        );

        $label = $dep['name'] ?? "Dependent #" . ($index + 1);

        if (!$depContribution) {
            return response()->json([
                'status'  => 422,
                'message' => "No pricing bracket found for {$label} age: {$depAgeYears} years.",
            ], 422);
        }

        $dependentsResult[] = [
            'member_type'   => 'dependent',
            'name'          => $dep['name']         ?? null,
            'relationship'  => $dep['relationship'] ?? null,
            'age_years'     => $depAgeYears,
            'age_months'    => $depAgeMonths,
            'age_group'     => $depContribution->age_group_label,
            'premium_pkr'   => (float) $depContribution->contribution_pkr,
            'premium_paisa' => (int) ceil($depContribution->contribution_pkr) * 100,
        ];
    }

    // ── Totals ────────────────────────────────────────────────────────────
    $totalPkr   = $selfResult['premium_pkr']
                + array_sum(array_column($dependentsResult, 'premium_pkr'));
    $totalPaisa = (int) ceil($totalPkr) * 100;

    return response()->json([
        'status'  => 200,
        'message' => 'Premium calculated successfully.',
        'data'    => [
            'product_id'          => $product->product_id,
            'variant'             => $product->variant,
            'plan_id'             => $product->plan->plan_id,
            'currency'            => 'PKR',
            'members_count'       => 1 + count($dependentsResult),
            'self'                => $selfResult,
            'dependents'          => $dependentsResult,
            'total_premium_pkr'   => $totalPkr,
            'total_premium_paisa' => $totalPaisa,
        ],
    ], 200);
}

    // =========================================================================
    //  ENDPOINT 2 — POST /api/v1/subscriptions/activate
    // =========================================================================

    public function activateSubscription(Request $request): JsonResponse
    {
        $request->validate([
            'subscription_id' => 'required|exists:subscriptions,subscription_id',
            'transaction_id'  => 'required|string|max:150',
            'activation_data' => 'nullable|array',
        ]);

        $subscription = Subscription::findOrFail($request->integer('subscription_id'));

        try {
            if (!$subscription->isPending()) {
                return response()->json([
                    'status'        => 422,
                    'message'       => 'Subscription cannot be activated. Current status: ' . $subscription->policy_status,
                    'policy_status' => $subscription->policy_status,
                ], 422);
            }

            $duplicate = Subscription::where('transaction_id', $request->input('transaction_id'))
                ->where('subscription_id', '!=', $subscription->subscription_id)
                ->exists();

            if ($duplicate) {
                return response()->json([
                    'status'  => 409,
                    'message' => 'Transaction ID already used for another subscription.',
                ], 409);
            }

            $certId       = $subscription->cert_id      ?? 'CERT-' . $subscription->subscription_id;
            $policyNumber = $subscription->policy_number ?? 'POL-'  . $subscription->subscription_id;

            $coverageStart      = now()->toDateString();
            $coverageEnd        = now()->addYear()->toDateString();
            $gracePeriodEndDate = now()->addYear()->addDays($subscription->grace_period_days)->toDateString();

            $subscription->update([
                'policy_status'         => Subscription::STATUS_ACTIVE,
                'transaction_id'        => $request->input('transaction_id'),
                'cert_id'               => $certId,
                'policy_number'         => $policyNumber,
                'coverage_start_date'   => $coverageStart,
                'coverage_end_date'     => $coverageEnd,
                'expiry_date'           => $coverageEnd,
                'grace_period_end_date' => $gracePeriodEndDate,
                'activated_at'          => now(),
                'activation_response'   => $request->input('activation_data'),
            ]);

            Log::info('SubscriptionController@activateSubscription: Activated.', [
                'subscription_id' => $subscription->subscription_id,
                'transaction_id'  => $request->input('transaction_id'),
                'members_count'   => $subscription->members_count,
            ]);

            return response()->json([
                'status'  => 200,
                'message' => 'Subscription activated successfully. Policy is now active.',
                'data'    => new SubscriptionResource(
                    $subscription->fresh()->load('customer', 'plan', 'product', 'members')
                ),
            ], 200);

        } catch (\Exception $e) {
            Log::error('SubscriptionController@activateSubscription: Error.', [
                'message' => $e->getMessage(),
            ]);
            return response()->json([
                'status'  => 500,
                'message' => 'Failed to activate subscription.',
                'detail'  => $e->getMessage(),
            ], 500);
        }
    }

    // =========================================================================
    //  ADDITIONAL ENDPOINTS
    // =========================================================================

    public function show(Subscription $subscription): JsonResponse
    {
        return response()->json([
            'status' => 200,
            'data'   => new SubscriptionResource(
                $subscription->load('customer', 'plan', 'product', 'members')
            ),
        ]);
    }

    public function byCustomer(Request $request, EasypaisaCustomer $customer): JsonResponse
    {
        $subscriptions = Subscription::where('customer_id', $customer->customer_id)
            ->with(['plan', 'product', 'members'])
            ->when($request->filled('status'), fn($q) => $q->where('policy_status', $request->input('status')))
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json([
            'status' => 200,
            'data'   => SubscriptionResource::collection($subscriptions),
        ]);
    }

    public function index(Request $request): JsonResponse
    {
        $subscriptions = Subscription::with(['customer', 'plan', 'product', 'members'])
            ->when($request->filled('status'),      fn($q) => $q->where('policy_status', $request->input('status')))
            ->when($request->filled('customer_id'), fn($q) => $q->where('customer_id',   $request->integer('customer_id')))
            ->when($request->filled('product_id'),  fn($q) => $q->where('product_id',    $request->integer('product_id')))
            ->when($request->filled('variant'),     fn($q) => $q->where('variant',       $request->input('variant')))
            ->orderBy('created_at', 'desc')
            ->paginate($request->integer('per_page', 15));

        return response()->json([
            'status' => 200,
            'data'   => SubscriptionResource::collection($subscriptions),
            'meta'   => [
                'total'        => $subscriptions->total(),
                'current_page' => $subscriptions->currentPage(),
                'last_page'    => $subscriptions->lastPage(),
            ],
        ]);
    }

    public function cancelSubscription(Request $request): JsonResponse
{
    $request->validate([
        'subscription_id' => 'required|exists:subscriptions,subscription_id',
        'customer_id'     => 'nullable|exists:easypaisa_customers,customer_id',
        'reason'          => 'nullable|string|max:500',
    ]);

    $subscription = Subscription::findOrFail($request->integer('subscription_id'));

    // ── Optional ownership guard ──────────────────────────────────────────
    if (
        $request->filled('customer_id') &&
        $subscription->customer_id !== $request->integer('customer_id')
    ) {
        return response()->json([
            'status'  => 403,
            'message' => 'This subscription does not belong to the given customer.',
        ], 403);
    }

    // ── Guard: only cancellable from pending_payment or active ────────────
    $cancellableStatuses = [
        Subscription::STATUS_PENDING_PAYMENT,
        Subscription::STATUS_ACTIVE,
    ];

    if (!in_array($subscription->policy_status, $cancellableStatuses)) {
        return response()->json([
            'status'        => 422,
            'message'       => 'Subscription cannot be cancelled. Current status: ' . $subscription->policy_status,
            'policy_status' => $subscription->policy_status,
        ], 422);
    }

    try {
        $subscription->update([
            'policy_status'         => Subscription::STATUS_CANCELLED,
            'cancellation_reason'   => $request->input('reason'),
            'cancelled_at'          => now(),
        ]);

        Log::info('SubscriptionController@cancelSubscription: Cancelled.', [
            'subscription_id' => $subscription->subscription_id,
            'customer_id'     => $subscription->customer_id,
            'previous_status' => $subscription->getOriginal('policy_status'),
            'reason'          => $request->input('reason'),
        ]);

        return response()->json([
            'status'  => 200,
            'message' => 'Subscription cancelled successfully.',
            'data'    => new SubscriptionResource(
                $subscription->fresh()->load('customer', 'plan')
            ),
        ], 200);

    } catch (\Exception $e) {
        Log::error('SubscriptionController@cancelSubscription: Error.', [
            'message' => $e->getMessage(),
        ]);
        return response()->json([
            'status'  => 500,
            'message' => 'Failed to cancel subscription.',
            'detail'  => $e->getMessage(),
        ], 500);
    }
}
    // =========================================================================
    //  PRIVATE HELPERS
    // =========================================================================

    /**
     * Resolve the contribution bracket.
     * Priority: $dob (Carbon) → $fallbackAgeYears → [null, null]
     *
     * @return array [$contribution|null, $ageInMonths|null]
     */
    private function resolveContribution(
        $dob,
        Product $product,
        ?int    $fallbackAgeYears = null
    ): array {
        // ── Priority 1: age from API request — always overrides DOB ──────────
        if ($fallbackAgeYears !== null) {
            $ageInMonths  = $fallbackAgeYears * 12;
            $contribution = $product->contributions->first(
                fn($c) => $ageInMonths >= $c->age_min_months
                       && $ageInMonths <= $c->age_max_months
            );
            return [$contribution, $ageInMonths];
        }

        // ── Priority 2: calculate from DOB ────────────────────────────────────
        if ($dob) {
            $ageInMonths  = (int) \Carbon\Carbon::parse($dob)->diffInMonths(now());
            $contribution = $product->contributions->first(
                fn($c) => $ageInMonths >= $c->age_min_months
                       && $ageInMonths <= $c->age_max_months
            );
            return [$contribution, $ageInMonths];
        }

        // ── Priority 3: nothing available ─────────────────────────────────────
        return [null, null];
    }

    private function callCreatePayment(
        int    $subscriptionId,
        string $paymentOrderId,
        string $paymentOrderTitle,
        int    $premiumPaisa
    ): array {
        $clientId    = config('easypaisa.client_id');
        $accessToken = config('easypaisa.access_token');
        $merchantId  = config('easypaisa.merchant_id');
        $appId       = config('easypaisa.app_id');
        $baseUrl     = config('easypaisa.base_url');
        $privateKey  = openssl_pkey_get_private(config('easypaisa.private_key'));

        $date        = new DateTime('now', new DateTimeZone('Asia/Karachi'));
        $requestTime = $date->format("Y-m-d\TH:i:s.vP");

        $data = [
            'merchantID'        => $merchantId,
            'appID'             => $appId,
            'paymentOrderTitle' => $paymentOrderTitle,
            'paymentOrderID'    => $paymentOrderId,
            'paymentAmount'     => [
                'currency' => 'PKR',
                'value'    => (string) $premiumPaisa,
            ],
        ];

        $signatureString =
            "POST /v1/payments/createPayment\n" .
            "{$clientId}.{$requestTime}.{$accessToken}." .
            json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        openssl_sign($signatureString, $signature, $privateKey, OPENSSL_ALGO_SHA256);
        $signatureEncoded = urlencode(base64_encode($signature));

        $headers = [
            'Content-Type'  => 'application/json',
            'Client-Id'     => $clientId,
            'Request-Time'  => $requestTime,
            'Access-Token'  => $accessToken,
            'Signature'     => "algorithm=RSA2048, keyVersion=1, signature={$signatureEncoded}",
        ];

        Log::info('SubscriptionController@callCreatePayment', [
            'subscription_id'  => $subscriptionId,
            'payment_order_id' => $paymentOrderId,
            'premium_paisa'    => $premiumPaisa,
        ]);

        $response     = Http::withHeaders($headers)->post($baseUrl . '/v1/payments/createPayment', $data);
        $responseBody = $response->json() ?? [];

        Log::info('SubscriptionController@callCreatePayment: Response', [
            'status'   => $response->status(),
            'response' => $responseBody,
        ]);

        return $responseBody;
    }
}