<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use App\Models\Pricing;
use App\Models\User;
use App\Services\PaymentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PaymentGatewayController extends Controller
{
    /**
     * Initiate Automatic Online Payment for package or custom recharge.
     */
    public function initiate(Request $request): JsonResponse
    {
        $request->validate([
            'amount' => 'nullable|numeric|min:1',
            'package_id' => 'nullable|exists:pricings,id',
            'sender_types' => 'nullable|integer',
            'gateway' => 'nullable|string',
        ]);

        $user = $request->user();
        $amount = (float) $request->input('amount', 0);
        $packageId = $request->input('package_id') ? (int) $request->input('package_id') : null;
        $senderTypes = (int) $request->input('sender_types', 1);
        $gateway = $request->input('gateway', 'automatic');

        $result = PaymentService::initiateAutomaticPayment($user, $amount, $packageId, $senderTypes, $gateway);

        return response()->json([
            'status' => 2000,
            'success' => true,
            'message' => 'Online payment initiated successfully.',
            'data' => $result,
        ]);
    }

    /**
     * Verify and Complete Automatic Payment (instant package activation).
     */
    public function verify(Request $request): JsonResponse
    {
        $request->validate([
            'transaction_id' => 'required|string',
        ]);

        $trxId = $request->input('transaction_id');
        $payload = $request->except(['transaction_id']);

        $result = PaymentService::verifyAndCompleteAutomaticPayment($trxId, $payload);

        if (!$result['success']) {
            return response()->json([
                'status' => 4000,
                'success' => false,
                'message' => $result['message'],
            ], 400);
        }

        return response()->json([
            'status' => 2000,
            'success' => true,
            'message' => $result['message'],
            'data' => [
                'payment' => $result['payment'],
                'activated_package' => $result['activated_package'],
            ],
        ]);
    }

    /**
     * Webhook callback for Payment Gateways (e.g. bKash, SSLCommerz, Stripe).
     */
    public function callback(Request $request): JsonResponse
    {
        $trxId = $request->input('transaction_id', $request->input('tran_id', $request->input('trx_id')));

        if (!$trxId) {
            return response()->json(['status' => 400, 'message' => 'Transaction ID missing'], 400);
        }

        $result = PaymentService::verifyAndCompleteAutomaticPayment($trxId, $request->all());

        return response()->json($result);
    }
}
