<?php

namespace App\Http\Controllers\Admin;

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

class UserAdminController extends Controller
{
    public function index()
    {
        $users = User::where('role', '!=', 'customer')->orderBy('id', 'asc')->get();
        $roles = config('motosolution.roles', []);

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'phone' => 'required|string|unique:users',
            'role' => 'required|string',
            'password' => 'required|min:8',
        ]);

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'],
            'role' => $validated['role'],
            'password' => Hash::make($validated['password']),
            'status' => 'active',
            'email_verified_at' => now(),
        ]);

        AuditLog::record('admin_created_staff_user', $user);

        return back()->with('success', "Staff account for {$user->name} ({$user->role}) created.");
    }

    public function updateRole(Request $request, string $id)
    {
        $user = User::findOrFail($id);

        $validated = $request->validate([
            'role' => 'required|string',
            'status' => 'required|in:active,suspended',
        ]);

        $user->update($validated);

        AuditLog::record('admin_updated_user_role', $user);

        return back()->with('success', "Role for {$user->name} updated to {$user->role}.");
    }
}
