<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class AgentBalanceController extends Controller
{
    public function index($id)
    {
        $agent = User::findOrFail($id);
        return view('admin.agents.balance-update', compact('agent'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'amount' => 'required|numeric|min:1',
            'mode' => 'required|in:deposit,withdraw'
        ]);
        $agent = User::agents()->findOrFail($id);

        if ($request->mode === 'deposit') {
            $agent->balance = $agent->balance + $request->amount;
            $agent->save();
        } else {
            if ($agent->balance < $request->amount) {
                return back()
                    ->withErrors(['amount' => 'The agent balance is insufficient'])
                    ->withInput();
            }
            $agent->balance = $agent->balance - $request->amount;
            $agent->save();
        }
        $purpose = $request->mode === 'deposit' ?
            'admin_deposit' : 'admin_withdrawal';
        $agent->transactions()->create([
            'user_id' => $agent->id,
            'type' => $request->mode,
            'amount' => $request->amount,
            'purpose' => $purpose,
        ]);

        return redirect()->route('agents.index')
            ->with('success', 'Agent balance is updated succssfully.');
    }
}
