<?php

namespace App\Http\Controllers\FrontUser;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\WalletTransaction;
use App\Models\Call;
use Illuminate\Support\Carbon;

class WalletController extends Controller
{
    public function index()
    {
        $userId = Auth::id();
        
        // Get wallet balance
        $currentBalance = Auth::user()->wallet_balance ?? 0;
        
        // Get total added (credit transactions)
        $totalAdded = WalletTransaction::where('user_id', $userId)
            ->where('type', 'credit')
            ->where('status', 'completed')
            ->sum('amount');
        
        // Get total spent (debit transactions)
        $totalSpent = WalletTransaction::where('user_id', $userId)
            ->where('type', 'debit')
            ->where('status', 'completed')
            ->sum('amount');
        
        // Get this month's additions
        $thisMonthAdded = WalletTransaction::where('user_id', $userId)
            ->where('type', 'credit')
            ->where('status', 'completed')
            ->whereMonth('created_at', Carbon::now()->month)
            ->sum('amount');
        
        // Get this month's spending
        $thisMonthSpent = WalletTransaction::where('user_id', $userId)
            ->where('type', 'debit')
            ->where('status', 'completed')
            ->whereMonth('created_at', Carbon::now()->month)
            ->sum('amount');
        
        // Get last transaction amount
        $lastTransaction = WalletTransaction::where('user_id', $userId)
            ->where('type', 'credit')
            ->where('status', 'completed')
            ->latest()
            ->first();
        
        // Get recent transactions
        $recentTransactions = WalletTransaction::where('user_id', $userId)
            ->latest()
            ->take(5)
            ->get();
        
        // Get call statistics
        $totalCalls = Call::where('user_id', $userId)->count();
        $thisMonthCalls = Call::where('user_id', $userId)
            ->whereMonth('date_time', Carbon::now()->month)
            ->count();
        
        return view('FrontUser.wallet.index', compact(
            'currentBalance',
            'totalAdded',
            'totalSpent',
            'thisMonthAdded',
            'thisMonthSpent',
            'lastTransaction',
            'recentTransactions',
            'totalCalls',
            'thisMonthCalls'
        ));
    }

    public function addFunds(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:100|max:100000',
            'payment_method' => 'required|in:razorpay,stripe,paypal,bank_transfer'
        ]);

        $userId = Auth::id();
        $amount = $request->amount;
        $paymentMethod = $request->payment_method;

        // Create pending transaction
        $transaction = WalletTransaction::create([
            'user_id' => $userId,
            'type' => 'credit',
            'amount' => $amount,
            'status' => 'pending',
            'payment_method' => $paymentMethod,
            'description' => 'Wallet Top-up via ' . ucfirst($paymentMethod),
            'reference_id' => 'TXN_' . time() . '_' . $userId
        ]);

        // Process payment based on method
        switch ($paymentMethod) {
            case 'razorpay':
                return $this->processRazorpayPayment($transaction);
            case 'stripe':
                return $this->processStripePayment($transaction);
            case 'paypal':
                return $this->processPaypalPayment($transaction);
            case 'bank_transfer':
                return $this->processBankTransfer($transaction);
        }
    }

    private function processRazorpayPayment($transaction)
    {
        // Simulate Razorpay payment processing
        $transaction->update([
            'status' => 'completed',
            'completed_at' => now()
        ]);

        // Update user wallet balance
        $user = Auth::user();
        $user->increment('wallet_balance', $transaction->amount);

        return response()->json([
            'success' => true,
            'message' => 'Payment successful! ₹' . $transaction->amount . ' added to your wallet.',
            'transaction_id' => $transaction->reference_id
        ]);
    }

    private function processStripePayment($transaction)
    {
        // Simulate Stripe payment processing
        $transaction->update([
            'status' => 'completed',
            'completed_at' => now()
        ]);

        $user = Auth::user();
        $user->increment('wallet_balance', $transaction->amount);

        return response()->json([
            'success' => true,
            'message' => 'Payment successful! ₹' . $transaction->amount . ' added to your wallet.',
            'transaction_id' => $transaction->reference_id
        ]);
    }

    private function processPaypalPayment($transaction)
    {
        // Simulate PayPal payment processing
        $transaction->update([
            'status' => 'completed',
            'completed_at' => now()
        ]);

        $user = Auth::user();
        $user->increment('wallet_balance', $transaction->amount);

        return response()->json([
            'success' => true,
            'message' => 'Payment successful! ₹' . $transaction->amount . ' added to your wallet.',
            'transaction_id' => $transaction->reference_id
        ]);
    }

    private function processBankTransfer($transaction)
    {
        // Bank transfer requires manual verification
        $transaction->update([
            'status' => 'pending_verification',
            'description' => 'Bank Transfer - Awaiting verification'
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Bank transfer initiated. Your wallet will be credited after verification (1-2 business days).',
            'transaction_id' => $transaction->reference_id
        ]);
    }

    public function withdrawFunds(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:100|max:50000',
            'bank_account' => 'required|string|min:10|max:20'
        ]);

        $userId = Auth::id();
        $user = Auth::user();
        $amount = $request->amount;

        if ($user->wallet_balance < $amount) {
            return response()->json([
                'success' => false,
                'message' => 'Insufficient wallet balance.'
            ], 400);
        }

        // Create withdrawal transaction
        $transaction = WalletTransaction::create([
            'user_id' => $userId,
            'type' => 'debit',
            'amount' => $amount,
            'status' => 'pending',
            'payment_method' => 'bank_transfer',
            'description' => 'Withdrawal to Bank Account: ' . $request->bank_account,
            'reference_id' => 'WTH_' . time() . '_' . $userId
        ]);

        // Deduct from wallet balance
        $user->decrement('wallet_balance', $amount);

        return response()->json([
            'success' => true,
            'message' => 'Withdrawal request submitted. Amount will be transferred within 1-2 business days.',
            'transaction_id' => $transaction->reference_id
        ]);
    }

    public function getPaymentMethods()
    {
        return response()->json([
            'methods' => [
                [
                    'id' => 'razorpay',
                    'name' => 'Razorpay',
                    'icon' => 'fas fa-credit-card',
                    'description' => 'Credit/Debit Cards, UPI, Net Banking',
                    'processing_fee' => '2.5%',
                    'processing_time' => 'Instant'
                ],
                [
                    'id' => 'stripe',
                    'name' => 'Stripe',
                    'icon' => 'fab fa-stripe',
                    'description' => 'International Cards, Apple Pay, Google Pay',
                    'processing_fee' => '2.9%',
                    'processing_time' => 'Instant'
                ],
                [
                    'id' => 'paypal',
                    'name' => 'PayPal',
                    'icon' => 'fab fa-paypal',
                    'description' => 'PayPal Balance, Cards, Bank Account',
                    'processing_fee' => '3.4%',
                    'processing_time' => 'Instant'
                ],
                [
                    'id' => 'bank_transfer',
                    'name' => 'Bank Transfer',
                    'icon' => 'fas fa-university',
                    'description' => 'Direct Bank Transfer',
                    'processing_fee' => 'Free',
                    'processing_time' => '1-2 Business Days'
                ]
            ]
        ]);
    }

    public function transactions()
    {
        $userId = Auth::id();
        
        $transactions = WalletTransaction::where('user_id', $userId)
            ->latest()
            ->paginate(20);
        
        return view('FrontUser.wallet.transactions', compact('transactions'));
    }
}