<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Site;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        $users = User::with('site')->orderBy('name')->get();

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

    public function create()
    {
        $sites = Site::orderBy('name')->get();

        return view('users.create', compact('sites'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:8',
            'role' => 'required|in:admin,hr,security',
            'site_id' => 'nullable|exists:sites,id',
        ]);

        $user = User::create($data);

        AuditLog::record($request->user()->id, 'user.create', 'User', $user->id, null, ['email' => $user->email, 'role' => $user->role]);

        return redirect()->route('users.index')->with('status', 'User created.');
    }

    public function edit(User $user)
    {
        $sites = Site::orderBy('name')->get();

        return view('users.edit', compact('user', 'sites'));
    }

    public function update(Request $request, User $user)
    {
        $data = $request->validate([
            'name' => 'required|string',
            'email' => 'required|email|unique:users,email,'.$user->id,
            'password' => 'nullable|string|min:8',
            'role' => 'required|in:admin,hr,security',
            'site_id' => 'nullable|exists:sites,id',
        ]);

        if (empty($data['password'])) {
            unset($data['password']);
        }

        $before = $user->only(['name', 'email', 'role', 'site_id']);
        $user->update($data);

        AuditLog::record($request->user()->id, 'user.update', 'User', $user->id, $before, $user->fresh()->only(['name', 'email', 'role', 'site_id']));

        return redirect()->route('users.index')->with('status', 'User updated.');
    }

    public function destroy(Request $request, User $user)
    {
        if ($user->id === $request->user()->id) {
            return back()->withErrors(['user' => 'You cannot delete your own account.']);
        }

        $before = $user->only(['name', 'email', 'role']);
        $user->delete();

        AuditLog::record($request->user()->id, 'user.delete', 'User', $user->id, $before, null);

        return redirect()->route('users.index')->with('status', 'User removed.');
    }
}
