<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ApiKey;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class UddoktaPayCompatibleController extends Controller
{
    private function getApiKey(Request $request)
    {
        $key = $request->header('RT-UDDOKTAPAY-API-KEY');
        if (!$key) {
            return null;
        }
        return ApiKey::where('public_key', $key)->where('is_active', true)->first();
    }

    public function checkoutV2(Request $request)
    {
        \App\Services\LicenseGuard::assertLicensed();

        $apiKey = $this->getApiKey($request);

        if (!$apiKey) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid API Key'
            ], 401);
        }

        $request->validate([
            'full_name' => 'nullable|string',
            'email' => 'nullable|email',
            'amount' => 'required|numeric|min:10',
            'metadata' => 'nullable|array',
            'redirect_url' => 'required|url',
            'cancel_url' => 'nullable|url',
            'webhook_url' => 'nullable|url'
        ]);

        // Generate a reference ID if the merchant didn't provide one via metadata or simply use a random string
        // Many plugins send order_id inside metadata. Let's try to extract it, or fallback to random.
        $metadata = $request->input('metadata', []);
        $referenceId = $metadata['order_id'] ?? Str::uuid()->toString();

        $transaction = Transaction::create([
            'user_id' => $apiKey->user_id,
            'reference_id' => $referenceId,
            'amount' => $request->amount,
            'currency' => 'BDT',
            'status' => 'PENDING',
            'redirect_url' => $request->redirect_url,
            'cancel_url' => $request->cancel_url,
            'metadata' => $metadata
        ]);

        return response()->json([
            'status' => true,
            'message' => 'Payment created',
            'payment_url' => url('/pay/' . $transaction->payment_id)
        ]);
    }

    public function verifyPayment(Request $request)
    {
        \App\Services\LicenseGuard::assertLicensed();

        $apiKey = $this->getApiKey($request);

        if (!$apiKey) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid API Key'
            ], 401);
        }

        $request->validate([
            'invoice_id' => 'required'
        ]);

        $invoiceId = $request->input('invoice_id');

        // The invoice_id from UddoktaPay is usually our transaction_id
        $transaction = Transaction::where('user_id', $apiKey->user_id)
                                  ->where('id', $invoiceId)
                                  ->first();

        // If not found by ID, try reference_id
        if (!$transaction) {
            $transaction = Transaction::where('user_id', $apiKey->user_id)
                                      ->where('reference_id', $invoiceId)
                                      ->first();
        }

        if (!$transaction) {
            return response()->json([
                'status' => false,
                'message' => 'Invoice not found'
            ], 404);
        }

        $statusMapping = [
            'SUCCESS' => 'COMPLETED',
            'PENDING' => 'PENDING',
            'FAILED' => 'FAILED'
        ];

        return response()->json([
            'status' => $statusMapping[$transaction->status] ?? $transaction->status,
            'message' => 'Payment verified',
            'full_name' => 'Customer',
            'email' => 'customer@example.com',
            'amount' => number_format((float)$transaction->amount, 2, '.', ''),
            'invoice_id' => (string) $transaction->id,
            'metadata' => $transaction->metadata,
        ]);
    }
}
