<?php

namespace App\Http\Controllers\Dashboard\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserBalanceManagementController extends Controller
{
    public function index($uuid)
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Users', 'url' => route('admin.user.index')],
            ['label' => 'User Details', 'url' => route('admin.user.show', $uuid)],
            ['label' => 'Balance Management', 'active' => true],
        ];

        $user = User::where('uuid', $uuid)->firstOrFail();

        $userPlans = $user->userPlans()->with(['plan'])->get();

        $data = [
            'title' => 'Balance Management for ' . $user->name,
            'user' => $user,
            'breadcrumbs' => $breadcrumbs,
            'userPlans' => $userPlans,
        ];

        return view('dashboard.admin.user.balance_management.index', $data);
    }

    /**
     * Set the selected balance type on the user's account to a new value.
     */
    public function store(Request $request, string $uuid)
    {
        $validated = $request->validate([
            'balance_type' => ['required', 'in:balance,profit_balance,demo_balance'],
            'amount'       => ['required', 'numeric', 'min:0'],
        ]);

        try {
            $user = User::where('uuid', $uuid)->firstOrFail();

            $type       = $validated['balance_type'];
            $newBalance = $validated['amount'];

            DB::transaction(function () use ($user, $type, $newBalance) {
                // Lock the row to avoid race conditions with concurrent updates
                $user = User::whereKey($user->id)->lockForUpdate()->first();

                $user->{$type} = $newBalance;
                $user->save();
            });

            return redirect()
                ->back()
                ->with('success', ucfirst(str_replace('_', ' ', $type)) . ' updated successfully.');
        } catch (\Throwable $e) {
            Log::error('Error updating user balance: ' . $e->getMessage());

            return redirect()
                ->back()
                ->with('error', 'An error occurred while updating the balance.');
        }
    }
}
