<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\PaymentIntent;

class PaymentsController extends Controller
{
    /**
     * Capture all PaymentIntents in 'requires_capture' status.
     */
    public function captureAllUncaptured(Request $request): \Illuminate\Http\JsonResponse
    {
        /// Validate that we have an array of PaymentIntent IDs
        $request->validate([
            'payment_intent_ids' => 'required|array',
            'payment_intent_ids.*' => 'string'
        ]);

        // Retrieve the list of PaymentIntent IDs from request
        $paymentIntentIds = $request->input('payment_intent_ids');

        // Initialize Stripe
//        Stripe::setApiKey(env('STRIPE_SECRET'));
        Stripe::setApiKey(env('SV_STRIPE_SK'));

        // Prepare containers for successes and errors
        $capturedList = [];
        $errorList = [];

        // Loop through each ID and attempt to capture
        foreach ($paymentIntentIds as $piId) {
            try {
                $paymentIntent = PaymentIntent::retrieve($piId);

                // Only capture if it is in a capturable state
                if ($paymentIntent->status === 'requires_capture') {
                    $captured = $paymentIntent->capture();
                    $capturedList[] = [
                        'id' => $captured->id,
                        'status' => $captured->status,
                    ];
                } else {
                    // If it’s not in requires_capture, skip or log a message
                    $errorList[] = [
                        'payment_intent' => $piId,
                        'error' => 'PaymentIntent not in capturable state. Current status: ' . $paymentIntent->status,
                    ];
                }
            } catch (\Exception $e) {
                // Log or record any errors
                $errorList[] = [
                    'payment_intent' => $piId,
                    'error' => $e->getMessage(),
                ];
            }
        }

        // Return a JSON response with successful captures & errors
        return response()->json([
            'captured' => $capturedList,
            'errors'   => $errorList,
        ]);
    }
}
