<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Transaction;
class AdminTransactionController extends Controller
{
     public function allTransactions()
    {
        $transactions = Transaction::with(['user', 'paymentMethod'])
                        ->latest()
                        ->paginate(10);
        
        return view('admin.transactions.index', compact('transactions'));
    }

    public function pendingTransactions()
    {
        $transactions = Transaction::with(['user', 'paymentMethod'])
                        ->where('status', 'pending')
                        ->latest()
                        ->paginate(10);
        
        return view('admin.transactions.pending', compact('transactions'));
    }

    public function approvedTransactions()
    {
        $transactions = Transaction::with(['user', 'paymentMethod'])
                        ->where('status', 'approved')
                        ->latest()
                        ->paginate(10);
        
        return view('admin.transactions.approved', compact('transactions'));
    }

    public function rejectedTransactions()
    {
        $transactions = Transaction::with(['user', 'paymentMethod'])
                        ->where('status', 'rejected')
                        ->latest()
                        ->paginate(10);
        
        return view('admin.transactions.rejected', compact('transactions'));
    }

 // app/Http/Controllers/Admin/AdminTransactionController.php

public function updateStatus(Request $request, Transaction $transaction)
{
    $request->validate(['status' => 'required|in:pending,approved,rejected']);
    
    try {
        $previousStatus = $transaction->status;
        $newStatus = $request->status;
        
        // Update transaction status
        $transaction->update(['status' => $newStatus]);
        
        // Handle balance adjustment for deposits
        if ($transaction->type === 'deposit') {
            $user = $transaction->user;
            
            if ($previousStatus !== 'approved' && $newStatus === 'approved') {
                // Approving a deposit - add to balance
                $user->increment('balance', $transaction->amount);
                
                // Add referral bonus if applicable
                $user->addReferralBonus($transaction->amount);
            } 
            elseif ($previousStatus === 'approved' && $newStatus !== 'approved') {
                // Reverting approval - subtract from balance
                $user->decrement('balance', $transaction->amount);
                
                // Remove referral bonus if already given
                $this->removeReferralBonus($transaction);
            }
        }
        
        return back()->with('success', 'Status updated successfully');
        
    } catch (\Exception $e) {
        return back()->with('error', 'Error: '.$e->getMessage());
    }
}

protected function removeReferralBonus(Transaction $transaction)
{
    $user = $transaction->user;
    
    if ($user->referred_by) {
        $referrer = User::find($user->referred_by);
        
        if ($referrer) {
            $bonusAmount = $transaction->amount * 0.07;
            
            // Deduct bonus from referrer's balance
            $referrer->decrement('balance', $bonusAmount);
            
            // Find and delete the bonus transaction
            Transaction::where([
                'user_id' => $referrer->id,
                'type' => 'referral_bonus',
            ])
            ->where('notes', 'like', "%user #{$user->id}%")
            ->delete();
        }
    }
}

     protected function addReferralBonus(Transaction $transaction)
    {
        $user = $transaction->user;
        
        // Check if user was referred by someone
        if ($user->referred_by) {
            $referrer = User::find($user->referred_by);
            
            if ($referrer) {
                $bonusAmount = $transaction->amount * 0.07; // 7% bonus
                
                // Add bonus to referrer's balance
                $referrer->increment('balance', $bonusAmount);
                
                // Create bonus transaction record
                Transaction::create([
                    'user_id' => $referrer->id,
                    'type' => 'referral_bonus',
                    'amount' => $bonusAmount,
                    'method' => 'referral',
                    'status' => 'approved',
                    'transaction_id' => 'REF-'.uniqid(),
                    'notes' => "Referral bonus from user #{$user->id}'s deposit"
                ]);
            }
        }
    }

    /**
     * Remove referral bonus if deposit approval is reverted
     */
   
    public function destroy(Transaction $transaction)
    {
        try {
            if ($transaction->type === 'deposit' && $transaction->status === 'approved') {
                $transaction->user->decrement('balance', $transaction->amount);
            }

            $transaction->delete();

            return back()->with([
                'message' => 'Transaction deleted successfully!',
                'alert-type' => 'success'
            ]);
        } catch (\Exception $e) {
            return back()->with([
                'message' => "Error deleting transaction: " . $e->getMessage(),
                'alert-type' => 'error'
            ]);
        }
    }
}
