<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Wallet;
use App\Models\Transaction;
use App\Models\WithdrawalRequest;
use App\Models\WithdrawRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WithdrawalController extends Controller
{
    /**
     * Display a listing of the withdrawal requests.
     */
    public function index(Request $request)
    {
        $query = WithdrawRequest::with('user');
        $withdrawRequests = $query->latest()->paginate(15);
        
        return view('admin.pages.withdraw-requests.index', compact('withdrawRequests'));
    }

    /**
     * Show the withdrawal request details.
     */
    public function show(WithdrawalRequest $withdrawal)
    {
        $withdrawal->load('user');
        return view('admin.withdrawals.show', compact('withdrawal'));
    }

    /**
     * Approve a withdrawal request.
     */
    public function approve(Request $request, WithdrawalRequest $withdrawal)
    {
        if ($withdrawal->status !== 'pending') {
            return redirect()->back()
                ->with('error', 'This withdrawal request has already been processed.');
        }

        $withdrawal->status = 'approved';
        $withdrawal->admin_note = $request->admin_note;
        $withdrawal->save();

        return redirect()->route('admin.withdrawals.index')
            ->with('success', 'Withdrawal request approved successfully.');
    }

    /**
     * Mark a withdrawal request as completed.
     */
    public function complete(Request $request, WithdrawalRequest $withdrawal)
    {
        if ($withdrawal->status !== 'approved') {
            return redirect()->back()
                ->with('error', 'Only approved withdrawal requests can be marked as completed.');
        }

        DB::beginTransaction();
        
        try {
            $withdrawal->status = 'completed';
            $withdrawal->processed_at = now();
            $withdrawal->admin_note = $request->admin_note;
            $withdrawal->save();
            
            // Create a transaction record
            Transaction::create([
                'user_id' => $withdrawal->user_id,
                'wallet_id' => Wallet::where('user_id', $withdrawal->user_id)->first()->id,
                'type' => 'debit',
                'amount' => $withdrawal->amount,
                'description' => 'Withdrawal completed',
                'reference_type' => 'withdrawal',
                'reference_id' => $withdrawal->id,
                'processed_at' => now()
            ]);
            
            DB::commit();
            
            return redirect()->route('admin.withdrawals.index')
                ->with('success', 'Withdrawal request marked as completed successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            
            return redirect()->back()
                ->with('error', 'An error occurred while completing the withdrawal: ' . $e->getMessage());
        }
    }

    /**
     * Reject a withdrawal request.
     */
    public function reject(Request $request, WithdrawalRequest $withdrawal)
    {
        if ($withdrawal->status !== 'pending') {
            return redirect()->back()
                ->with('error', 'Only pending withdrawal requests can be rejected.');
        }

        DB::beginTransaction();
        
        try {
            $withdrawal->status = 'rejected';
            $withdrawal->admin_note = $request->admin_note;
            $withdrawal->save();
            
            // Return funds to user's wallet
            $wallet = Wallet::where('user_id', $withdrawal->user_id)->first();
            $wallet->balance += $withdrawal->amount;
            $wallet->save();
            
            // Create a transaction record
            Transaction::create([
                'user_id' => $withdrawal->user_id,
                'wallet_id' => $wallet->id,
                'type' => 'credit',
                'amount' => $withdrawal->amount,
                'description' => 'Withdrawal request rejected, funds returned',
                'reference_type' => 'withdrawal_rejected',
                'reference_id' => $withdrawal->id,
                'processed_at' => now()
            ]);
            
            DB::commit();
            
            return redirect()->route('admin.withdrawals.index')
                ->with('success', 'Withdrawal request rejected and funds returned to user.');
        } catch (\Exception $e) {
            DB::rollBack();
            
            return redirect()->back()
                ->with('error', 'An error occurred while rejecting the withdrawal: ' . $e->getMessage());
        }
    }
} 