<?php

namespace App\Http\Controllers\Panel;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
use Spatie\Permission\Models\Role;

/** Sadece Master Admin: sistem kullanıcılarını yönetir (bayi hesapları DealerController üzerinden yönetilir). */
class UserController extends Controller
{
    public function index(): View
    {
        Gate::authorize('users.view');

        $users = User::with('roles', 'dealer')->latest()->paginate(20);

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

    public function create(): View
    {
        Gate::authorize('users.create');

        $roles = Role::all();

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

    public function store(Request $request): RedirectResponse
    {
        Gate::authorize('users.create');

        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8'],
            'role' => ['required', 'exists:roles,name'],
        ]);

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

        $user->assignRole($data['role']);

        return redirect()->route('panel.users.index')->with('success', 'Kullanıcı oluşturuldu.');
    }

    public function edit(User $user): View
    {
        Gate::authorize('users.update');

        $roles = Role::all();

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

    public function update(Request $request, User $user): RedirectResponse
    {
        Gate::authorize('users.update');

        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($user->id)],
            'password' => ['nullable', 'string', 'min:8'],
            'role' => ['required', 'exists:roles,name'],
            'status' => ['required', Rule::in(['active', 'passive'])],
        ]);

        $user->update(array_filter([
            'name' => $data['name'],
            'email' => $data['email'],
            'status' => $data['status'],
            'password' => ! empty($data['password']) ? Hash::make($data['password']) : null,
        ], fn ($v) => $v !== null));

        $user->syncRoles([$data['role']]);

        return redirect()->route('panel.users.index')->with('success', 'Kullanıcı güncellendi.');
    }

    public function destroy(User $user): RedirectResponse
    {
        Gate::authorize('users.delete');

        $user->delete();

        return redirect()->route('panel.users.index')->with('success', 'Kullanıcı silindi.');
    }
}
