<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class PaystackService
{
    protected $secretKey;
    protected $baseUrl = 'https://api.paystack.co';

    public function __construct()
    {
        $this->secretKey = env('PAYSTACK_SECRET_KEY');
    }

    /**
     * Create a new customer on Paystack.
     */
    public function createCustomer($user)
    {
        $response = Http::withToken($this->secretKey)
            ->post("{$this->baseUrl}/customer", [
                'email' => $user->email,
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'phone' => $user->phone,
            ]);

        if ($response->successful()) {
            return $response->json()['data']['customer_code'];
        }

        Log::error('Paystack Customer Create Error: ' . $response->body());
        return null;
    }

    /**
     * Assign a Dedicated Virtual Account (DVA) to a customer.
     */
    public function createVirtualAccount($customerCode)
    {
        $response = Http::withToken($this->secretKey)
            ->post("{$this->baseUrl}/dedicated_account", [
                'customer' => $customerCode,
                'preferred_bank' => 'wema-bank', // Common for Paystack DVAs in Nigeria
            ]);

        if ($response->successful()) {
            return $response->json()['data'];
        }

        // If it fails, maybe the customer already has one or provider issue
        Log::error('Paystack DVA Create Error: ' . $response->body());
        return null;
    }

    /**
     * Verify a transaction via reference (used for checkouts or webhooks).
     */
    public function verifyTransaction($reference)
    {
        $response = Http::withToken($this->secretKey)
            ->get("{$this->baseUrl}/transaction/verify/{$reference}");

        if ($response->successful()) {
            return $response->json()['data'];
        }

        return null;
    }
}
