<?php
namespace App\Services\Payments;

use App\Models\PaymentAttempt;
use App\Models\PaymentProfile;
use App\Modules\Admin\Financials\InboundPayment;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Stripe\Account;
class StripeWebhookService
{
    public function handlePaymentSuccess($intent)
    {
        $paymentIntentId = $intent->id;
        Log::info('StripeWebhookService: handlePaymentSuccess', [ 'payment_intent_id' => $paymentIntentId, ]);
        $paymentAttempt = PaymentAttempt::where('payment_intent_id', $paymentIntentId)->first();
        if (!$paymentAttempt) {
            Log::warning('PaymentAttempt not found for intent: ' . $paymentIntentId);
            return;
        }

        // Already processed
        if ($paymentAttempt->status === 'succeeded') {
            return;
        }
        // Call business logic (InboundPayment updates balance, etc.)
        $module = app()->make(\App\Modules\Admin\Financials\InboundPayment::class, [
            'paymentMethodService' => app()->make(\App\Services\Payments\PaymentMethodService::class),
        ]);

        $module->finalizeSuccessfulPayment($paymentAttempt);

         // Update status
        $paymentAttempt->update(['status' => 'succeeded']);
    }

    /**
     * Handle failed Stripe payment intents.
     *
     * @param  \Stripe\PaymentIntent  $paymentIntent
     * @return void
     */
    public function handlePaymentFailure($paymentIntent): void
    {
        $intentId = $paymentIntent->id;
        $status = $paymentIntent->status;

        // Update the corresponding PaymentAttempt if it exists
        $attempt = PaymentAttempt::where('payment_intent_id', $intentId)->first();

        if ($attempt) {
            $attempt->status = 'failed';
            $attempt->save();
            Log::info('StripeWebhookService: handlePaymentFailure PaymentAttempt', $attempt->toArray());
        } else {
            /*
            Log::warning('StripeWebhookService: handlePaymentFailure for unknown payment intent', [
                'intent_id' => $intentId,
                'status' => $status,
            ]);
            */
        }

        
    }
    
    /**
     * Handle the `account.updated` webhook from Stripe.
     *
     * This is triggered when a **Connected Account** (e.g., a contractor or loaner on your platform)
     * has been updated — typically due to onboarding progress, compliance review,
     * new capabilities, or submitted information.
     *
     * The method:
     * - Extracts metadata from the updated Stripe account
     * - Locates the corresponding PaymentProfile (internal DB model)
     * - Stores the relevant Stripe data as JSON metadata for tracking and diagnostics
     *
     * @see https://docs.stripe.com/api/accounts/object
     * @param \Stripe\Account $connectedAccount  The updated connected account object from Stripe
     * @return void
     */

    public function handleAccountUpdated(Account $connectedAccount): void
    {
        
        $accountId = $connectedAccount->id ?? null;

        if (!$accountId) {
            Log::warning('StripeWebhookService: handleAccountUpdated, missing account ID.');
            return;
        }
        
        $profile = PaymentProfile::where('provider', 'stripe')
            ->where('provider_account_id', $accountId)
            ->first();

        if (!$profile) {
            Log::info("StripeWebhookService: No PaymentProfile found for updated Stripe connected account: $accountId");
            return;
        }
       
        // Extract useful fields for tracking and diagnostics
        $metadata = [
            'business_type' => $connectedAccount->business_type ?? null,
            'type' => $connectedAccount->type ?? null,
            'email' => $connectedAccount->email ?? null,
            'country' => $connectedAccount->country ?? null,
            'capabilities' => $connectedAccount->capabilities ?? [],
            'charges_enabled' => $connectedAccount->charges_enabled ?? false,
            'payouts_enabled' => $connectedAccount->payouts_enabled ?? false,
            'details_submitted' => $connectedAccount->details_submitted ?? false,
            'requirements' => [
                'currently_due' => $connectedAccount->requirements->currently_due ?? [],
                'errors' => $connectedAccount->requirements->errors ?? [],
                'disabled_reason' => $connectedAccount->requirements->disabled_reason ?? null,
            ],
        ];
        /*
        $profile->metadata = $metadata;
        $profile->save();
        */
        Log::info("StripeWebhookService: handleAccountUpdated for connected account ID: $accountId", [
            'company_id' => $profile->company_id,
            'metadata' => $metadata,
        ]);

    }


}