<?php

namespace App\Http\Controllers;

use App\Mail\OrderConfirmedMail;
use App\Mail\OrderInternalNotificationMail;
use App\Mail\OrderOnboardingMail;
use App\Models\Order;
use App\Services\Card2CryptoService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class WebhookController extends Controller
{
    public function card2crypto(Request $request)
    {
        $payload   = $request->getContent();
        $signature = $request->header('X-Card2Crypto-Signature', '');

        $service = new Card2CryptoService();

        if (! $service->verifyWebhookSignature($payload, $signature)) {
            Log::warning('Card2Crypto webhook: invalid signature');
            return response()->json(['error' => 'Invalid signature'], 403);
        }

        $data   = json_decode($payload, true);
        $status = $data['status'] ?? null;
        $ref    = $data['merchant_order_id'] ?? $data['order_id'] ?? null;

        if (! $ref) {
            return response()->json(['error' => 'Missing order reference'], 422);
        }

        $order = Order::where('order_number', $ref)->first();

        if (! $order) {
            return response()->json(['error' => 'Order not found'], 404);
        }

        if (in_array($status, ['paid', 'completed', 'success'], true) && $order->status !== 'paid') {
            $order->update([
                'status'       => 'paid',
                'payment_ref'  => $data['payment_id'] ?? $data['transaction_id'] ?? null,
                'payment_data' => $data,
            ]);

            Mail::to($order->email)->send(new OrderConfirmedMail($order));
            Mail::to($order->email)->send(new OrderOnboardingMail($order));
            Mail::to(env('ORDERS_EMAIL', 'orders@trollmasters.ai'))
                ->send(new OrderInternalNotificationMail($order));
        } elseif (in_array($status, ['failed', 'cancelled'], true)) {
            $order->update(['status' => 'failed']);
        }

        return response()->json(['received' => true]);
    }
}
