<?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Date;
use App\NotifyMe;
use Exception;
use Illuminate\Http\Request;

class WebhookController extends Controller
{
    use NotifyMe;

    public function oxapay(Request $request): ResponseFactory|Response
    {
        // Get the request data
        $postData = $request->getContent();
        $data = json_decode($postData, true);

        // Validate request data
        if (! $data || ! isset($data['type']) || ! in_array($data['type'], ['invoice', 'payment_link', 'payout'])) {
            Log::warning('Invalid Oxapay webhook data', ['data' => $data]);

            return response('Invalid data.type', 400);
        }

        // Determine API secret key based on type
        $apiSecretKey = $data['type'] === 'invoice'
            ? config('services.oxapay.merchant_api_key')
            : config('services.oxapay.payout_api_key');

        // Validate HMAC signature
        $hmacHeader = $request->header('HMAC');
        $calculatedHmac = hash_hmac('sha512', $postData, (string) $apiSecretKey);

        if (hash_equals($calculatedHmac, $hmacHeader)) {
            // HMAC signature is valid
            try {
                if ($data['type'] === 'invoice' || $data['type'] === 'payment_link') {
                    // Process invoice payment data
                    $email = $data['email'] ?? 'Unknown';
                    $amount = $data['amount'] ?? 'Unknown';
                    $currency = $data['currency'] ?? 'Unknown';
                    $trackId = $data['track_id'] ?? 'Unknown';
                    $orderId = $data['order_id'] ?? 'N/A';
                    $date = isset($data['date']) ? Date::createFromTimestamp($data['date'])->toDateTimeString() : now()->toDateTimeString();

                    Log::info('Received Oxapay invoice payment callback', [
                        'track_id' => $trackId,
                        'email' => $email,
                        'amount' => $amount,
                        'currency' => $currency,
                        'order_id' => $orderId,
                        'date' => $date,
                    ]);

                    $message = "✅ Oxapay Invoice Payment Success\n".
                        "Track ID: {$trackId}\n".
                        "Email: {$email}\n".
                        "Amount: {$amount} {$currency}\n".
                        "Order ID: {$orderId}\n".
                        "Time: {$date}";
                    self::sendTelegramNotification($message);
                } elseif ($data['type'] === 'payout') {
                    // Process payout data
                    $trackId = $data['track_id'] ?? 'Unknown';
                    $amount = $data['amount'] ?? 'Unknown';
                    $currency = $data['currency'] ?? 'Unknown';
                    $network = $data['network'] ?? 'Unknown';
                    $address = $data['address'] ?? 'Unknown';
                    $txHash = $data['tx_hash'] ?? 'Unknown';
                    $description = $data['description'] ?? 'N/A';
                    $date = isset($data['date']) ? Date::createFromTimestamp($data['date'])->toDateTimeString() : now()->toDateTimeString();

                    Log::info('Received Oxapay payout callback', [
                        'track_id' => $trackId,
                        'status' => $data['status'] ?? 'Unknown',
                        'amount' => $amount,
                        'currency' => $currency,
                        'network' => $network,
                        'address' => $address,
                        'tx_hash' => $txHash,
                        'description' => $description,
                        'date' => $date,
                    ]);

                    $message = "📤 Oxapay Payout Confirmed\n".
                        "Track ID: {$trackId}\n".
                        "Amount: {$amount} {$currency}\n".
                        "Network: {$network}\n".
                        "Address: {$address}\n".
                        "Transaction Hash: {$txHash}\n".
                        "Description: {$description}\n".
                        "Date: {$date}";
                    self::sendTelegramNotification($message);
                }

                return response('OK', 200);
            } catch (Exception $e) {
                Log::error('Oxapay webhook processing error', ['error' => $e->getMessage(), 'data' => $data]);
                self::sendTelegramNotification("
                    Failed to process Oxapay webhook\n
                    Type: {$data['type']}\n
                    Email/Track ID: ".($data['type'] === 'invoice' ? ($data['email'] ?? 'Unknown') : ($data['track_id'] ?? 'Unknown'))."\n
                    Error: {$e->getMessage()}
                ");

                return response('Processing error', 400);
            }
        } else {
            Log::warning('Invalid Oxapay HMAC signature', ['hmac_header' => $hmacHeader, 'calculated_hmac' => $calculatedHmac]);

            return response('Invalid HMAC signature', 400);
        }
    }
}
