<?php

namespace App\Http\Controllers\Admin;

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

class WalletController extends Controller
{
    public function index(Request $request)
    {
        $query = User::where('role', '!=', 'admin')
            ->with('wallet')
            ->orderBy('first_name');

        if ($search = trim($request->input('q', ''))) {
            $query->where(function ($q) use ($search) {
                $q->where('first_name', 'like', "%{$search}%")
                  ->orWhere('last_name',  'like', "%{$search}%")
                  ->orWhere('mobile',     'like', "%{$search}%");
            });
        }

        $users = $query->paginate(25)->withQueryString();

        return view('admin.wallets.index', compact('users'));
    }

    public function show(User $user)
    {
        $wallet       = Wallet::forUser($user);
        $transactions = $wallet->transactions()->with('createdBy')->paginate(20);

        return view('admin.wallets.show', compact('user', 'wallet', 'transactions'));
    }

    public function adjust(Request $request, User $user)
    {
        $request->validate([
            'type'        => 'required|in:credit,debit',
            'amount'      => 'required|integer|min:1',
            'description' => 'required|string|max:200',
        ], [
            'type.required'        => 'نوع تراکنش الزامی است.',
            'amount.required'      => 'مبلغ الزامی است.',
            'amount.min'           => 'مبلغ باید بیشتر از صفر باشد.',
            'description.required' => 'توضیحات الزامی است.',
        ]);

        $wallet = Wallet::forUser($user);

        try {
            $amount = (int) $request->amount;

            if ($request->type === 'credit') {
                $wallet->credit($amount, $request->description, auth()->id());
                $msg = 'مبلغ ' . number_format($amount) . ' تومان به کیف پول افزوده شد.';
            } else {
                $wallet->debit($amount, $request->description, auth()->id());
                $msg = 'مبلغ ' . number_format($amount) . ' تومان از کیف پول کسر شد.';
            }

            return back()->with('success', $msg);
        } catch (\RuntimeException $e) {
            return back()->withErrors(['amount' => $e->getMessage()]);
        }
    }
}
