<?php

namespace App\Http\Controllers;

use App\Models\Pago;
use Illuminate\Http\Request;
use Stripe\Exception\SignatureVerificationException;
use Stripe\Webhook;

class StripeWebhookController extends Controller
{
    public function handle(Request $request)
    {
        $payload = $request->getContent();
        $sigHeader = $request->header('Stripe-Signature');
        $secret = config('services.stripe.webhook_secret');

        try {
            $event = Webhook::constructEvent(
                $payload,
                $sigHeader,
                $secret
            );
        } catch (SignatureVerificationException $e) {
            return response()->json(['error' => 'Webhook inválido'], 400);
        }

        switch ($event->type) {

            case 'checkout.session.completed':

                $session = $event->data->object;

                $pagoId = $session->metadata->pago_id ?? null;

                if ($pagoId) {

                    $pago = Pago::find($pagoId);

                    if ($pago) {
                        $pago->estado = 'pagado';
                        $pago->save();
                    }
                }

                break;

            case 'payment_intent.payment_failed':

                // manejar fallo de pago
                break;
        }

        return response()->json(['status' => 'ok']);
    }
}
