<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\OpenpayWebhook;
use Illuminate\Support\Facades\Log;

class OpenPayWebhookController extends Controller
{
    public function handle(Request $request)
    {
        try {
            $payload = $request->all();

            $webhook = OpenpayWebhook::create([
                'event_type' => $payload['type'] ?? null,
                'transaction_id' => $payload['transaction']['id'] ?? null,
                'payload' => $payload,
                'status' => 'received',
            ]);

            // 👉 Aquí luego procesaremos pagos, suscripciones, etc.
            // Por ahora solo almacenamos

            $webhook->update(['status' => 'processed']);

            return response()->json(['ok' => true], 200);
        } catch (\Throwable $e) {

            Log::error('OpenPay Webhook Error', [
                'error' => $e->getMessage(),
            ]);

            OpenpayWebhook::create([
                'payload' => $request->all(),
                'status' => 'failed',
            ]);

            return response()->json(['error' => true], 500);
        }
    }
}
