<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class UserManageController extends Controller
{
    /** User list with filter + search */
    public function index(Request $request)
    {
        $status = $request->input('status');  // active / blocked / null
        $q      = $request->input('q');       // search (name/phone/email/id)

        $users = User::query()
            ->when($status, function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->when($q, function ($query) use ($q) {
                $query->where(function ($sub) use ($q) {
                    $sub->where('name', 'like', "%{$q}%")
                        ->orWhere('phone', 'like', "%{$q}%")
                        ->orWhere('email', 'like', "%{$q}%")
                        ->orWhere('id', $q);
                });
            })
            ->orderByDesc('id')
            ->paginate(20)
            ->withQueryString();

        return view('backend.users.index', compact('users', 'status', 'q'));
    }

    /** Edit form */
    public function edit(User $user)
    {
        return view('backend.users.edit', compact('user'));
    }

    /** Update basic info */
    public function update(Request $request, User $user)
    {
        $data = $request->validate([
            'name'         => ['required', 'string', 'max:191'],
            'country_code' => ['required', 'string', 'max:6'],
            'phone'        => ['required', 'string', 'max:20', 'unique:users,phone,' . $user->id],
            'email'        => ['nullable', 'email', 'max:191', 'unique:users,email,' . $user->id],
            'role'         => ['required', 'string', 'max:20'],
            'loan_limit'   => ['required', 'integer', 'min:0'],
            'status'       => ['required', 'in:active,blocked'],
            'avatar'       => ['nullable', 'image', 'max:2048'],
        ]);

        // avatar upload
        if ($request->hasFile('avatar')) {
            if ($user->avatar) {
                Storage::disk('public')->delete($user->avatar);
            }
            $data['avatar'] = $request->file('avatar')->store('avatars', 'public');
        }

        $user->update($data);

        return redirect()
            ->route('admin.users.edit', $user)
            ->with('success', 'User information updated successfully.');
    }

    /** Toggle active / blocked */
    public function toggleStatus(User $user)
    {
        $user->status = $user->status === 'active' ? 'blocked' : 'active';
        $user->save();

        return back()->with('success', 'User status updated to: ' . $user->status);
    }

    /** Update password */
    public function updatePassword(Request $request, User $user)
    {
        $data = $request->validate([
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $user->password = Hash::make($data['password']);
        $user->save();

        return back()->with('success', 'Password updated successfully.');
    }

    /** Delete user */
    public function destroy(User $user)
    {
        // Optional: নিজের account delete না করার guard
        if (auth()->id() === $user->id) {
            return back()->with('error', "You can't delete your own account.");
        }

        if ($user->avatar) {
            Storage::disk('public')->delete($user->avatar);
        }

        $user->delete();

        return redirect()
            ->route('admin.users.index')
            ->with('success', 'User deleted successfully.');
    }
}
