<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Withdrawal;
use App\Models\UserBalance;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;

class WithdrawalController extends Controller
{
    public function index(Request $request): View
    {
        $query = Withdrawal::with('user');

        if ($request->has('status')) {
            $query->where('status', $request->get('status'));
        }

        // Per page - default 10, allow 10, 20, 50, 100
        $perPage = $request->get('per_page', 10);
        if (!in_array($perPage, [10, 20, 50, 100])) {
            $perPage = 10;
        }

        $withdrawals = $query->latest()->paginate($perPage)->withQueryString();

        return view('admin.withdrawals.index', [
            'withdrawals' => $withdrawals,
            'pageTitle' => __('admin.withdrawals.title'),
            'title' => __('admin.withdrawals.title')
        ]);
    }

    public function update(Request $request, $id): RedirectResponse
    {
        $withdrawal = Withdrawal::findOrFail($id);
        $oldStatus = $withdrawal->status;

        $validated = $request->validate([
            'status' => 'required|in:pending,processing,completed,rejected',
            'reason' => $request->status === 'rejected' ? 'required|string|max:500' : 'nullable|string|max:500',
        ]);

        DB::transaction(function () use ($withdrawal, $validated, $oldStatus) {
            $withdrawal->update(['status' => $validated['status']]);

            $user = $withdrawal->user;
            $coinName = strtoupper($withdrawal->coin_name ?? 'USDT');

            // Get user balance for the specific coin
            $userBalance = UserBalance::where('user_id', $user->id)
                ->where('coin_name', $coinName)
                ->first();

            // If completed, unlock balance and deduct from user balance
            if ($validated['status'] === 'completed' && $oldStatus !== 'completed') {
                // Update legacy balance
                $user->decrement('locked_balance', $withdrawal->amount);
                $user->decrement('balance', $withdrawal->amount);
                
                // Update coin-specific balance
                if ($userBalance) {
                    $userBalance->decrement('locked_balance', $withdrawal->amount);
                    $userBalance->decrement('balance', $withdrawal->amount);
                }

                \App\Services\NotificationService::createWithdrawApproved($user, (float) $withdrawal->amount, $withdrawal->coin_name);
            }

            // If rejected, unlock balance (return to available balance)
            if ($validated['status'] === 'rejected' && $oldStatus !== 'rejected') {
                // Update legacy balance
                $user->decrement('locked_balance', $withdrawal->amount);
                
                // Update coin-specific balance
                if ($userBalance) {
                    $userBalance->decrement('locked_balance', $withdrawal->amount);
                }
            }

            // Log audit
            \App\Models\AuditLog::create([
                'admin_user_id' => session('admin.user_id'),
                'action' => 'withdrawal_update',
                'model_type' => Withdrawal::class,
                'model_id' => $withdrawal->id,
                'changes' => json_encode(['status' => $oldStatus . ' -> ' . $validated['status']]),
                'reason' => $validated['reason'] ?? null,
            ]);
        });

        return redirect()->back()->with('success', 'Withdrawal updated');
    }
}
