<?php

namespace App\Http\Controllers;

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

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

        try {
            $event = Webhook::constructEvent(
                $payload,
                $signature,
                $secret
            );
        } catch (SignatureVerificationException $e) {
            return response('Firma inválida', 400);
        }

        // 👉 Evento que nos importa
        if ($event->type === 'checkout.session.completed') {

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

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

            if ($pagoId) {
                Pago::where('id', $pagoId)->update([
                    'estado' => 'pagado',
                ]);
            }
        }

        return response('OK', 200);
    }
}
