<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Wallet;
use App\Models\Transaction;

class WalletController extends Controller
{
    public function getBalance(Request $request)
    {
        $wallet = Wallet::firstOrCreate(['user_id' => $request->user()->id], ['balance' => 0.00]);
        return response()->json(['success' => true, 'balance' => collect([$wallet])->first()->balance]);
    }

    public function getHistory(Request $request)
    {
        $wallet = Wallet::where('user_id', $request->user()->id)->first();
        if (!$wallet) return response()->json(['success' => true, 'transactions' => []]);
        $history = Transaction::where('wallet_id', $wallet->id)->orderBy('created_at', 'desc')->get();
        return response()->json(['success' => true, 'transactions' => $history]);
    }

    public function fund(Request $request)
    {
        $request->validate(['amount' => 'required|numeric|min:100']);
        $wallet = Wallet::firstOrCreate(['user_id' => $request->user()->id], ['balance' => 0.00]);
        $wallet->balance += $request->amount;
        $wallet->save();
        Transaction::create(['wallet_id' => $wallet->id, 'type' => 'credit', 'amount' => $request->amount, 'description' => 'Wallet Funding', 'status' => 'successful']);
        return response()->json(['success' => true, 'message' => 'Wallet funded successfully', 'balance' => $wallet->balance]);
    }

    public function withdraw(Request $request)
    {
        $request->validate(['amount' => 'required|numeric|min:500']);
        $wallet = Wallet::where('user_id', $request->user()->id)->first();
        if (!$wallet || $wallet->balance < $request->amount) {
            return response()->json(['success' => false, 'message' => 'Insufficient balance']);
        }
        $wallet->balance -= $request->amount;
        $wallet->save();
        Transaction::create(['wallet_id' => $wallet->id, 'type' => 'debit', 'amount' => $request->amount, 'description' => 'Bank Withdrawal', 'status' => 'pending']);
        return response()->json(['success' => true, 'message' => 'Withdrawal request submitted successfully.', 'balance' => $wallet->balance]);
    }
}
