<?php

namespace App\Http\Controllers;

use App\Enums\RequestStatus;
use App\Enums\RoutingNumberType;
use App\Http\Requests\DepositStoreRequest;
use App\Models\DepositRequest;
use App\Models\PaymentMethod;
use Illuminate\Support\Facades\Log;

class DepositController extends Controller
{
    public function show()
    {
        try {
            $user = auth()->user();
            $accounts = $user->accounts()->with(['routingNumbers'])->get();

            $accountRoutingData = $accounts->mapWithKeys(function ($account) use ($user) {
                $domesticWire = $account->routingNumbers
                    ->firstWhere('type', RoutingNumberType::DomesticWire);

                return [$account->id => [
                    'account_name' => $user->first_name . ' ' . $user->last_name,
                    'account_number' => $account->account_number,
                    'routing_number' => $domesticWire?->routing_number,
                ]];
            });

            return view('deposit.index', [
                'accounts' => $accounts,
                'paymentMethods' => PaymentMethod::where('is_active', true)->get(),
                'accountRoutingData' => $accountRoutingData,
                'activePage' => 'accounts',
            ]);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return back()->with('alert', 'An error occurred.');
        }
    }

    public function store(DepositStoreRequest $request)
    {
        try {
            $proofPath = $request->file('proof')->store('proofs', 'public');

            DepositRequest::create([
                'user_id' => auth()->id(),
                'account_id' => $request->account_id,
                'payment_method_id' => $request->payment_method_id,
                'amount' => $request->amount,
                'proof_path' => $proofPath,
                'status' => RequestStatus::Pending,
            ]);

            return redirect()->route('deposit')->with('success', 'Deposit request submitted. Awaiting admin approval.');
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return back()->with('alert', 'An error occurred.');
        }
    }
}
