<?php
namespace App\Services\Payments;

use Illuminate\Support\Facades\Http;
use App\Models\Order;

class FlutterwaveAdapter implements PaymentGateway
{
    public function createCheckout(array $p): PaymentIntent
    {
        $resp = Http::withToken(env('PAYMENT_FLUTTERWAVE_SECRET'))
            ->asJson()->post(env('PAYMENT_FLUTTERWAVE_BASE').'/payments', [
                'tx_ref'=>$p['reference'],
                'amount'=>$p['amount'],
                'currency'=>$p['currency'] ?? 'TZS',
                'redirect_url'=>$p['return_url'],
                'customer'=>['email'=>'customer@example.com'],
                'customizations'=>['title'=>'BlueBando']
            ])->json();
        $url = $resp['data']['link'] ?? null;
        return new PaymentIntent($resp['data']['id'] ?? null, $url, $p['reference']);
    }

    public function verify(string $reference): PaymentStatus { return new PaymentStatus('unknown'); }
    public function handleWebhook(array $request): void {
        $ref = $request['data']['tx_ref'] ?? null;
        if (!$ref) return;
        $order = Order::where('reference',$ref)->first();
        if ($order) $order->update(['status'=> ($request['data']['status'] ?? '') === 'successful' ? 'paid' : 'failed', 'meta_json'=>$request]);
    }
}
