<?php

namespace App\Http\Controllers\Client;

use App\Enums\RecordStatus;
use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Services\TransactionLogger;
use Illuminate\Http\Request;

class DepositController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'network' => ['required', 'string', 'max:32'],
            'amount' => ['required', 'numeric', 'min:1'],
        ]);

        $walletKey = match (strtoupper(str_replace([' ', '/'], ['', '_'], $data['network']))) {
            'BTC' => 'wallet_btc',
            'ETH' => 'wallet_eth',
            'BSC' => 'wallet_bsc',
            'TRC20' => 'wallet_trc20',
            'POLYGON' => 'wallet_polygon',
            'SOLANA' => 'wallet_solana',
            'USDT_ERC20', 'USDTERC20' => 'wallet_usdt_erc20',
            'USDC' => 'wallet_usdc',
            default => null,
        };

        $walletAddress = $walletKey ? \App\Models\SiteSetting::get($walletKey, '') : '';

        if (empty($walletAddress)) {
            return back()->with('error', 'Deposit wallet not configured for this network.');
        }

        $deposit = Deposit::create([
            'user_id' => $request->user()->id,
            'network' => $data['network'],
            'wallet_address' => $walletAddress,
            'amount' => $data['amount'],
            'status' => RecordStatus::Pending,
        ]);

        TransactionLogger::fromDeposit($deposit);

        return redirect()->route('client.home.deposit')
            ->with('success', 'Deposit request submitted. Awaiting admin approval.');
    }
}
