<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use App\Models\VtuWallet;
use App\Models\VtuWalletTopup;
use App\Models\VtuWalletTransaction;
use App\Services\ActivityLogger;
use App\Services\NumberGenerator;
use App\Services\VtuWalletService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use InvalidArgumentException;

class VtuWalletController extends Controller
{
    public function index(VtuWalletService $wallets): View
    {
        $walletCollection = VtuWallet::withoutGlobalScopes()
            ->with('tenant')
            ->orderByDesc('balance')
            ->get();

        return view('super.vtu-wallet.index', [
            'tenants' => Tenant::query()->orderBy('name')->get(['id', 'name', 'email']),
            'wallets' => $walletCollection,
            'walletTotals' => $wallets->totals($walletCollection),
            'pendingTopupsCount' => VtuWalletTopup::withoutGlobalScopes()
                ->where('status', VtuWalletTopup::STATUS_PENDING)
                ->count(),
            'topups' => VtuWalletTopup::withoutGlobalScopes()
                ->with(['tenant', 'creator', 'approver'])
                ->latest()
                ->paginate(15, ['*'], 'topups_page'),
            'transactions' => VtuWalletTransaction::withoutGlobalScopes()
                ->with(['tenant', 'topup', 'billPayment', 'creator'])
                ->latest()
                ->paginate(15, ['*'], 'ledger_page'),
        ]);
    }

    public function credit(Request $request, VtuWalletService $wallets): RedirectResponse
    {
        $validated = $request->validate([
            'tenant_id' => ['required', 'exists:tenants,id'],
            'amount' => ['required', 'numeric', 'min:100', 'max:100000000'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ]);

        $tenant = Tenant::query()->findOrFail($validated['tenant_id']);

        $topup = VtuWalletTopup::withoutGlobalScopes()->create([
            'tenant_id' => $tenant->id,
            'created_by' => $request->user()->id,
            'amount' => round((float) $validated['amount'], 2),
            'currency' => $tenant->settings['currency'] ?? 'NGN',
            'payment_channel' => 'admin_credit',
            'status' => VtuWalletTopup::STATUS_PENDING,
            'reference' => NumberGenerator::reference('VTUCR'),
            'notes' => $validated['notes'] ?? 'Super admin VTU wallet credit.',
        ]);

        $wallets->approveTopup($topup, $request->user()->id, 'admin_credit');

        return back()->with('status', 'VTU wallet credited for '.$tenant->name.'.');
    }

    public function approve(VtuWalletTopup $topup, VtuWalletService $wallets): RedirectResponse
    {
        try {
            $wallets->approveTopup($topup, auth()->id(), $topup->payment_channel ?: 'manual');
        } catch (InvalidArgumentException $exception) {
            return back()->with('warning', $exception->getMessage());
        }

        return back()->with('status', 'VTU wallet payment approved and tenant wallet credited.');
    }

    public function reject(Request $request, VtuWalletTopup $topup): RedirectResponse
    {
        $validated = $request->validate(['rejected_reason' => ['required', 'string', 'max:1000']]);

        if ($topup->status !== VtuWalletTopup::STATUS_PENDING) {
            return back()->with('warning', 'Only pending VTU wallet payments can be rejected.');
        }

        $topup->update([
            'status' => VtuWalletTopup::STATUS_REJECTED,
            'rejected_reason' => $validated['rejected_reason'],
            'processed_at' => now(),
        ]);

        ActivityLogger::log('vtu_wallet_topup_rejected', 'VTU wallet payment '.$topup->reference.' rejected.', $topup);

        return back()->with('status', 'VTU wallet payment rejected.');
    }
}
