<?php

namespace App\Services;

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

class PaystackService
{
    private string $secretKey;
    private string $baseUrl;

    public function __construct()
    {
        $this->secretKey = config('invotrack.paystack.secret_key');
        $this->baseUrl   = config('invotrack.paystack.payment_url');
    }

    // ─────────────────────────────────────────
    // INITIALIZE TRANSACTION
    // Called when client clicks "Pay Now"
    // Returns authorization_url + reference
    // ─────────────────────────────────────────
    public function initializeTransaction(array $data): array
    {
        $response = Http::withToken($this->secretKey)
            ->post("{$this->baseUrl}/transaction/initialize", [
                'email'     => $data['email'],
                'amount'    => $data['amount'],       // in kobo (₦1 = 100 kobo)
                'reference' => $data['reference'],
                'currency'  => 'NGN',
                'callback_url' => $data['callback_url'],
                'metadata'  => $data['metadata'] ?? [],
            ]);

        if ($response->successful() && $response->json('status') === true) {
            return [
                'success'           => true,
                'authorization_url' => $response->json('data.authorization_url'),
                'reference'         => $response->json('data.reference'),
                'access_code'       => $response->json('data.access_code'),
            ];
        }

        Log::error('Paystack initialize failed', [
            'response' => $response->json(),
            'data'     => $data,
        ]);

        return [
            'success' => false,
            'message' => $response->json('message') ?? 'Payment initialization failed',
        ];
    }

    // ─────────────────────────────────────────
    // VERIFY TRANSACTION
    // Called after Paystack redirects back
    // Always verify server-side — never trust client
    // ─────────────────────────────────────────
    public function verifyTransaction(string $reference): array
    {
        $response = Http::withToken($this->secretKey)
            ->get("{$this->baseUrl}/transaction/verify/{$reference}");

        if ($response->successful() && $response->json('status') === true) {
            $data = $response->json('data');

            return [
                'success'        => true,
                'paid'           => $data['status'] === 'success',
                'amount'         => $data['amount'] / 100,   // convert kobo back to naira
                'reference'      => $data['reference'],
                'transaction_id' => (string) $data['id'],
                'channel'        => $data['channel'],
                'currency'       => $data['currency'],
                'paid_at'        => $data['paid_at'],
                'customer_email' => $data['customer']['email'] ?? null,
                'gateway_response' => $data,
            ];
        }

        Log::error('Paystack verify failed', [
            'reference' => $reference,
            'response'  => $response->json(),
        ]);

        return [
            'success' => false,
            'paid'    => false,
            'message' => $response->json('message') ?? 'Verification failed',
        ];
    }

    // ─────────────────────────────────────────
    // VERIFY WEBHOOK SIGNATURE
    // Paystack signs every webhook with your secret key
    // Always verify before processing
    // ─────────────────────────────────────────
    public function verifyWebhookSignature(string $payload, string $signature): bool
    {
        $expectedSignature = hash_hmac('sha512', $payload, $this->secretKey);
        return hash_equals($expectedSignature, $signature);
    }
}
