<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Wallet;
use App\Models\WalletTransaction;
use Illuminate\Support\Facades\DB;

class WalletController extends Controller
{
    public function show(Request $request)
    {
        $user = $request->user();
        
        $wallet = Wallet::firstOrCreate(
            ['user_id' => $user->id],
            ['balance' => 0]
        );

        return response()->json([
            'status' => 'success',
            'data' => [
                'balance' => $wallet->balance,
                'transactions' => $wallet->transactions()->latest()->take(20)->get()
            ]
        ]);
    }

    public function deposit(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:1',
            'payment_method' => 'required|string',
            'transaction_id' => 'required|string'
        ]);

        $user = $request->user();

        try {
            DB::beginTransaction();

            $wallet = Wallet::firstOrCreate(
                ['user_id' => $user->id],
                ['balance' => 0]
            );

            $wallet->increment('balance', $request->amount);

            $wallet->transactions()->create([
                'amount' => $request->amount,
                'type' => 'credit',
                'description' => 'Deposit via ' . $request->payment_method,
                'reference_id' => $request->transaction_id,
                'status' => 'completed'
            ]);

            DB::commit();

            return response()->json([
                'status' => 'success',
                'message' => 'Deposit successful',
                'data' => [
                    'balance' => $wallet->balance
                ]
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'status' => 'error',
                'message' => 'Deposit failed: ' . $e->getMessage()
            ], 500);
        }
    }
}
