<?php

namespace App\Http\Controllers\Admin;

use App\Enums\RequestStatus;
use App\Enums\TransactionCategory;
use App\Enums\TransactionSource;
use App\Enums\TransactionStatus;
use App\Enums\TransactionType;
use App\Http\Controllers\Controller;
use App\Http\Requests\ReviewWithdrawalRequest;
use App\Models\Transaction;
use App\Models\WithdrawalRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class AdminWithdrawalController extends Controller
{
    public function index()
    {
        try {
            $withdrawals = WithdrawalRequest::with(['user', 'account'])->latest()->paginate(20);

            return view('admin.withdrawals.index', compact('withdrawals'));
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return back()->with('alert', 'An error occurred.');
        }
    }

    public function approve(ReviewWithdrawalRequest $request, WithdrawalRequest $withdrawal)
    {
        try {
            DB::transaction(function () use ($withdrawal) {
                $withdrawal->update(['status' => RequestStatus::Approved]);

                $withdrawal->account->decrement('balance', $withdrawal->amount);

                Transaction::create([
                    'account_id' => $withdrawal->account_id,
                    'type' => TransactionType::Debit,
                    'amount' => $withdrawal->amount,
                    'balance_after' => $withdrawal->account->fresh()->balance,
                    'description' => 'Withdrawal approved',
                    'category' => TransactionCategory::Transfer,
                    'status' => TransactionStatus::Completed,
                    'source' => TransactionSource::Withdrawal,
                    'reference' => 'TXN-' . strtoupper(Str::random(12)),
                ]);
            });

            return back()->with('success', 'Withdrawal approved.');
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return back()->with('alert', 'An error occurred.');
        }
    }

    public function reject(ReviewWithdrawalRequest $request, WithdrawalRequest $withdrawal)
    {
        try {
            $withdrawal->update([
                'status' => RequestStatus::Rejected,
                'admin_note' => $request->admin_note,
            ]);

            return back()->with('success', 'Withdrawal rejected.');
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return back()->with('alert', 'An error occurred.');
        }
    }
}
