<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\BalanceAdjustment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class BalanceAdjustController extends Controller
{
    /**
     * Search + form page
     */
    public function index(Request $request)
    {
        $query = $request->input('q'); // phone / email / id
        $user  = null;

        if ($query) {
            $user = User::query()
                ->when(is_numeric($query), function ($q) use ($query) {
                    // যদি pure number হয় তবে phone বা id ধরে খুঁজব
                    $q->where('phone', $query)
                      ->orWhere('id', $query);
                }, function ($q) use ($query) {
                    // নাহলে email বা name ধরে চেষ্টা
                    $q->where('email', $query)
                      ->orWhere('name', 'like', "%{$query}%");
                })
                ->first();
        }

        return view('backend.balance.adjust', compact('query', 'user'));
    }

    /**
     * Apply credit / debit to user balance
     */
    public function apply(Request $request, User $user)
    {
        $data = $request->validate([
            'type'   => ['required', 'in:credit,debit'],
            'amount' => ['required', 'integer', 'min:1'],
            'reason' => ['nullable', 'string', 'max:255'],
        ]);

        $before = $user->balance;

        if ($data['type'] === 'debit' && $data['amount'] > $before) {
            return back()->withErrors([
                'amount' => 'User-এর ব্যালেন্সের চেয়ে বেশি টাকা minus করা যাবে না।',
            ])->withInput();
        }

        $delta = $data['type'] === 'credit'
            ? $data['amount']
            : -$data['amount'];

        $user->balance = $before + $delta;
        $user->save();

        // log রাখি (optional কিন্তু strongly recommended)
        BalanceAdjustment::create([
            'user_id'        => $user->id,
            'admin_id'       => Auth::id(),
            'type'           => $data['type'],
            'amount'         => $data['amount'],
            'before_balance' => $before,
            'after_balance'  => $user->balance,
            'reason'         => $data['reason'] ?? null,
        ]);

        $msg = $data['type'] === 'credit'
            ? 'Balance সফলভাবে যোগ হয়েছে।'
            : 'Balance থেকে সফলভাবে কেটে নেওয়া হয়েছে।';

        // search এ আবার একই user যেন দেখায়
        return redirect()
            ->route('admin.balance.adjust.index', ['q' => $user->phone ?? $user->id])
            ->with('success', $msg);
    }
}
