<?php

namespace App\Http\Controllers;

use DB;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Wallet;
use App\Models\Transaction;
use Illuminate\Http\Request;
use App\Models\WithdrawalRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class WalletController extends Controller
{
    /**
     * Display user's wallet dashboard
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        $wallet = Wallet::firstOrCreate(
            ['user_id' => $user->id],
            [
                'balance' => 0,
                'pending_balance' => 0,
                'currency' => 'USD',
                'is_active' => true
            ]
        );

        // Get wallet statistics
        $stats = [
            'total_earned' => Transaction::where('user_id', $user->id)
                ->whereIn('type', ['credit', 'completed'])
                ->sum('amount'),
            
            'monthly_earned' => Transaction::where('user_id', $user->id)
                ->whereIn('type', ['credit', 'completed'])
                ->whereMonth('created_at', Carbon::now()->month)
                ->whereYear('created_at', Carbon::now()->year)
                ->sum('amount'),
                
            'total_withdrawn' => WithdrawalRequest::where('user_id', $user->id)
                ->whereIn('status', ['completed'])
                ->sum('amount')
        ];

        // Get recent transactions
        $recentTransactions = Transaction::where('user_id', $user->id)
            ->latest()
            ->take(5)
            ->get();
        
        // Get pending withdrawals
        $pendingWithdrawals = WithdrawalRequest::where('user_id', $user->id)
            ->whereIn('status', ['pending', 'approved'])
            ->latest()
            ->take(5)
            ->get();
        
        // Get most rewarded actions
        $topEarningActions = Transaction::where('user_id', $user->id)
            ->whereIn('type', ['credit', 'completed'])
            ->whereNotNull('reference_type')
            ->selectRaw('reference_type, SUM(amount) as total_amount, COUNT(*) as count')
            ->groupBy('reference_type')
            ->orderBy('total_amount', 'desc')
            ->take(5)
            ->get();

        // If request wants JSON, return the data as JSON
        if ($request->wantsJson()) {
            return response()->json([
                'wallet' => $wallet,
                'stats' => $stats,
                'recent_transactions' => $recentTransactions,
                'pending_withdrawals' => $pendingWithdrawals,
                'top_earning_actions' => $topEarningActions
            ]);
        }
        
        return view('front_end.pages.wallet.wallet', compact(
            'wallet', 
            'stats', 
            'recentTransactions', 
            'pendingWithdrawals', 
            'topEarningActions'
        ));
    }

    /**
     * Display transaction history
     */
    public function transactions(Request $request)
    {
        $user = Auth::user();
        
        $query = Transaction::where('user_id', $user->id);
        
        // Filter by type if provided
        if ($request->has('type') && in_array($request->type, ['credit', 'debit', 'pending', 'completed', 'cancelled'])) {
            $query->where('type', $request->type);
        }
        
        // Filter by date range if provided
        if ($request->has('from_date')) {
            $query->whereDate('created_at', '>=', $request->from_date);
        }
        
        if ($request->has('to_date')) {
            $query->whereDate('created_at', '<=', $request->to_date);
        }
        
        $transactions = $query->latest()->paginate(15);
        
        if ($request->wantsJson()) {
            return response()->json($transactions);
        }
        
        return view('front_end.pages.wallet.transactions', compact('transactions'));
    }

    /**
     * Request a withdrawal
     */
    public function requestWithdrawal(Request $request)
    {
        $user = Auth::user();
        $wallet = Wallet::where('user_id', $user->id)->first();
        
        if (!$wallet) {
            return redirect()->back()->with('error', 'Wallet not found.');
        }
        
        $validator = Validator::make($request->all(), [
            'amount' => ['required', 'numeric', 'min:10', 'max:' . $wallet->balance],
            'payment_method' => 'required|in:paypal,bank_transfer,crypto',
            'payment_details' => 'required|array',
            'note' => 'nullable|string|max:500'
        ]);
        
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
        
        // Start a database transaction
        DB::beginTransaction();
        
        try {
            // Deduct the funds from the wallet
            if (!$wallet->deductFunds(
                $request->amount, 
                'Withdrawal request', 
                'withdrawal_request', 
                null, 
                ['payment_method' => $request->payment_method]
            )) {
                return redirect()->back()->with('error', 'Insufficient funds.');
            }
            
            // Create withdrawal request
            $withdrawal = WithdrawalRequest::create([
                'user_id' => $user->id,
                'amount' => $request->amount,
                'status' => 'pending',
                'payment_method' => $request->payment_method,
                'payment_details' => $request->payment_details,
                'note' => $request->note
            ]);
            
            \DB::commit();
            
            return redirect()->back()->with('success', 'Withdrawal request submitted successfully.');
        } catch (\Exception $e) {
            \DB::rollBack();
            
            return redirect()->back()->with('error', 'An error occurred: ' . $e->getMessage());
        }
    }

    /**
     * Display user's withdrawal requests
     */
    public function withdrawals(Request $request)
    {
        $user = Auth::user();
        
        $withdrawals = WithdrawalRequest::where('user_id', $user->id)
            ->latest()
            ->paginate(10);
        
        if ($request->wantsJson()) {
            return response()->json($withdrawals);
        }
        
        return view('front_end.pages.walelt.withdrawals', compact('withdrawals'));
    }
} 