<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Core\Traits\CalculatesFees;
use App\Core\Traits\GeneratesReference;
use App\Models\BillService;
use App\Models\BillVariation;
use App\Models\Setting;
use App\Modules\ProviderIntegration\Interfaces\ProviderInterface;
use App\Modules\Transactions\Interfaces\TransactionServiceInterface;
use App\Modules\Wallet\Interfaces\WalletServiceInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ExamPinController extends Controller
{
    use GeneratesReference, CalculatesFees;
    public function __construct(
        protected ProviderInterface $provider,
        protected TransactionServiceInterface $transactionService,
        protected WalletServiceInterface $walletService
    ) {}

    public function index()
    {
        $types = BillService::active()->category('exam_pin')->get();
        $serviceCharges = $types->pluck('service_charge', 'code');
        $feeConfig = [
            'percentage' => (float) Setting::getValue('service_charge_percentage', 0),
            'default' => (float) Setting::getValue('default_service_charge', 0),
        ];
        return view('exampin.index', compact('types', 'serviceCharges', 'feeConfig'));
    }

    public function variations(string $type)
    {
        $service = BillService::where('code', $type)->active()->firstOrFail();
        $variations = BillVariation::where('bill_service_id', $service->id)->active()->orderBy('sort_order')->get();

        return response()->json(['variations' => $variations]);
    }

    public function validateProfile(Request $request)
    {
        $validated = $request->validate([
            'profile_id' => ['required', 'string'],
            'service_code' => ['required', 'string'],
            'variation_code' => ['required', 'string'],
        ]);

        $service = BillService::where('code', $validated['service_code'])->active()->firstOrFail();

        try {
            $response = $this->provider->validateCustomer(
                $service->code,
                $validated['profile_id'],
                $validated['variation_code']
            );

            $content = $response['content'] ?? $response;
            $name = $content['Customer_Name'] ?? $content['customer_name'] ?? $content['name'] ?? 'Verified';

            return response()->json(['valid' => true, 'customer_name' => $name]);
        } catch (\Exception $e) {
            return response()->json(['valid' => false, 'message' => $e->getMessage()], 422);
        }
    }

    public function purchase(Request $request)
    {
        $validated = $request->validate([
            'variation_code' => ['required', 'string'],
            'quantity' => ['required', 'integer', 'in:1'],
            'phone' => ['nullable', 'string', 'max:20'],
            'profile_id' => ['nullable', 'string'],
        ]);

        $user = $request->user();
        $variation = BillVariation::where('code', $validated['variation_code'])->firstOrFail();
        $service = $variation->billService;
        $amount = $validated['quantity'] * (float) $variation->amount;
        $fee = $this->calculateFee($amount, (float) $service->service_charge);
        $totalAmount = $amount + $fee;
        $reference = 'EXM-' . strtoupper(Str::random(8)) . '-' . now()->format('YmdHis');

        if (!$this->checkDailyTransactionLimit($user->id)) {
            $message = 'Daily transaction limit reached. Please try again tomorrow.';
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => $message], 422);
            }
            return back()->withErrors(['amount' => $message]);
        }

        $isJamb = $service->code === 'jamb';
        $billersCode = $isJamb ? ($validated['profile_id'] ?? '') : 'N/A';
        $customerNumber = $isJamb ? ($validated['profile_id'] ?? 'N/A') : 'N/A';

        try {
            DB::beginTransaction();

            if (!$this->walletService->canDebit($user->id, $totalAmount)) {
                DB::rollBack();
                if ($request->ajax()) {
                    return response()->json(['success' => false, 'message' => 'Insufficient wallet balance'], 422);
                }
                return back()->withErrors(['amount' => 'Insufficient wallet balance']);
            }

            $transaction = $this->transactionService->createTransaction([
                'user_id' => $user->id,
                'reference' => $reference,
                'bill_service_id' => $service->id,
                'bill_variation_id' => $variation->id,
                'type' => 'exam_pin',
                'service_name' => $service->name . ' - ' . $variation->name,
                'customer_number' => $customerNumber,
                'amount' => $amount,
                'fee' => $fee,
                'total_amount' => $totalAmount,
                'ip_address' => $request->ip(),
                'device' => $request->userAgent(),
            ]);

            $this->walletService->debitWallet($user->id, $totalAmount, "Exam PIN purchase - {$service->name} x{$validated['quantity']}", $reference, 'transaction', $transaction->id);
            $this->transactionService->markProcessing($reference);
            DB::commit();

            $requestId = self::generateVTPassRequestId();

            try {
                $response = $this->provider->purchaseExamPin(
                    $service->code,
                    $validated['variation_code'],
                    $billersCode,
                    $validated['phone'] ?? $user->phone ?? '',
                    $validated['quantity'],
                    $requestId
                );

                if (isset($response['code']) && $response['code'] === '000') {
                    $tokenData = [
                        'tokens' => $response['tokens'] ?? ($response['purchased_code'] ? [$response['purchased_code']] : []),
                        'cards' => $response['cards'] ?? [],
                        'pin' => $response['Pin'] ?? $response['purchased_code'] ?? null,
                        'response_description' => $response['response_description'] ?? null,
                        'request_id' => $response['requestId'] ?? null,
                        'amount' => $response['amount'] ?? null,
                        'transaction_date' => $response['transaction_date'] ?? null,
                    ];
                    $this->transactionService->markSuccessful($reference, $response, $tokenData);
                } else {
                    $this->transactionService->markFailed($reference, $response['response_description'] ?? 'Failed', $response);
                    $this->walletService->refundWallet($user->id, $totalAmount, "Refund for failed exam PIN purchase {$reference}", 'RFD-' . strtoupper(Str::random(8)));
                }
            } catch (\Exception $e) {
                $this->transactionService->markFailed($reference, $e->getMessage(), []);
                $this->walletService->refundWallet($user->id, $totalAmount, "Refund for failed exam PIN purchase {$reference}", 'RFD-' . strtoupper(Str::random(8)));
            }

            if ($request->ajax()) {
                return response()->json(['success' => true, 'message' => 'Exam PIN purchase submitted!', 'redirect' => route('transactions.show', $reference)]);
            }
            return redirect()->route('transactions.show', $reference)->with('success', 'Exam PIN purchase submitted!');
        } catch (\Exception $e) {
            DB::rollBack();
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
            }
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }
}
