<?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 CheckoutController extends Controller
{
    public function store(Request $request)
    {
        \App\Services\LicenseGuard::assertLicensed();

        $request->validate([
            'public_key' => 'required|string',
            'amount' => 'required|numeric|min:10',
            'reference_id' => 'required|string',
            'gateway' => 'nullable|string|exists:gateways,name',
            'redirect_url' => 'nullable|url',
            'cancel_url' => 'nullable|url'
        ]);

        $apiKey = ApiKey::where('public_key', $request->public_key)->where('is_active', true)->first();

        if (!$apiKey) {
            return response()->json(['error' => 'Invalid or inactive API Key'], 401);
        }

        // Check for duplicate reference ID for this merchant
        $existing = Transaction::where('user_id', $apiKey->user_id)
                                ->where('reference_id', $request->reference_id)
                                ->first();
        if ($existing) {
            return response()->json(['error' => 'Duplicate reference_id'], 400);
        }

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

        return response()->json([
            'status' => 'success',
            'transaction_id' => $transaction->id,
            'checkout_url' => url('/pay/' . $transaction->payment_id), // Will be handled by a web route
        ]);
    }
}
