<?php

namespace Modules\AuthorizeNetGateway\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
// ... other necessary models (Subscription, User, etc.)

class AuthorizeNetWebhookController extends Controller
{
    public function handle(Request $request)
    {
        $signatureKey = setting('authorizenet_signature_key');
        $payload = $request->getContent();
        $receivedSignature = $request->header('X-ANET-Signature');

        if (!$signatureKey) {
            Log::error('Authorize.Net Webhook: Signature key not configured.');
            return response()->json(['status' => 'error', 'message' => 'Configuration error'], 500);
        }

        // Verify signature
        $computedSignature = hash_hmac('sha512', $payload, hex2bin($signatureKey)); // Or just $signatureKey if it's not hex

        // Note: Authorize.Net's signature format might be "sha512=" prefix. Adjust as needed.
        // Example: $receivedSignature = str_replace('sha512=', '', $receivedSignature);

        if (!hash_equals(strtoupper($computedSignature), strtoupper($receivedSignature))) {
             Log::warning("Authorize.Net Webhook: Invalid signature. Received: {$receivedSignature}, Computed: {$computedSignature}");
             return response()->json(['status' => 'error', 'message' => 'Invalid signature'], 403);
        }

        $event = json_decode($payload, true);
        Log::info('Authorize.Net Webhook Received:', $event);

        $eventType = $event['eventType'] ?? null;
        $payloadData = $event['payload'] ?? null;

        switch ($eventType) {
            case 'net.authorize.payment.authcapture.created':
            case 'net.authorize.payment.capture.created':
                // Handle successful one-time payment
                // $transactionId = $payloadData['id'];
                // Potentially update an order or subscription status
                break;
            case 'net.authorize.customer.subscription.created':
            case 'net.authorize.customer.subscription.updated':
            case 'net.authorize.customer.subscription.cancelled':
            case 'net.authorize.customer.subscription.expiring':
            case 'net.authorize.customer.subscription.suspended':
            case 'net.authorize.customer.subscription.terminated':
                // Handle subscription events
                // $subscriptionId = $payloadData['id']; (This is Authorize.Net's subscription ID)
                // Find your local subscription record and update its status, ends_at, etc.
                break;
            // Add more cases as needed
            default:
                Log::info("Authorize.Net Webhook: Unhandled event type '{$eventType}'");
        }

        return response()->json(['status' => 'success'], 200);
    }
}

