<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Filiale;
use App\Models\User;
use App\Support\ActivityLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class FilialeUserController extends Controller
{
    public function index(Filiale $filiale): View
    {
        $users = $filiale->users()->orderBy('name')->get();

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

    public function create(Filiale $filiale): View
    {
        return view('admin.filiales.users.create', compact('filiale'));
    }

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

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'role' => 'filiale',
            'filiale_id' => $filiale->id,
            'is_active' => $request->boolean('is_active', true),
        ]);

        ActivityLogger::log('filiale.user.created', $user, $filiale->name.' — '.$user->email);

        return redirect()->route('admin.filiales.users.index', $filiale)
            ->with('success', 'Compte créé avec succès.');
    }

    public function edit(Filiale $filiale, User $user): View
    {
        $this->ensureBelongsToFiliale($filiale, $user);

        return view('admin.filiales.users.edit', compact('filiale', 'user'));
    }

    public function update(Request $request, Filiale $filiale, User $user): RedirectResponse
    {
        $this->ensureBelongsToFiliale($filiale, $user);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', Rule::unique('users', 'email')->ignore($user->id)],
            'password' => ['nullable', 'string', 'min:8', 'confirmed'],
            'is_active' => ['boolean'],
        ]);

        $isActive = $request->boolean('is_active');

        // Empêche de désactiver le dernier compte actif de la filiale.
        if (! $isActive && $this->isLastActiveUser($filiale, $user)) {
            return back()->withErrors(['is_active' => 'Impossible de désactiver le dernier compte actif de la filiale.']);
        }

        $data = [
            'name' => $validated['name'],
            'email' => $validated['email'],
            'is_active' => $isActive,
        ];

        if (! empty($validated['password'])) {
            $data['password'] = Hash::make($validated['password']);
        }

        $user->update($data);

        ActivityLogger::log('filiale.user.updated', $user, $filiale->name.' — '.$user->email);

        return redirect()->route('admin.filiales.users.index', $filiale)
            ->with('success', 'Compte mis à jour.');
    }

    public function destroy(Filiale $filiale, User $user): RedirectResponse
    {
        $this->ensureBelongsToFiliale($filiale, $user);

        if ($filiale->users()->count() <= 1) {
            return back()->withErrors(['user' => 'Impossible de supprimer le dernier compte de la filiale.']);
        }

        $email = $user->email;
        $user->delete();

        ActivityLogger::log('filiale.user.deleted', null, $filiale->name.' — '.$email);

        return redirect()->route('admin.filiales.users.index', $filiale)
            ->with('success', 'Compte supprimé.');
    }

    private function ensureBelongsToFiliale(Filiale $filiale, User $user): void
    {
        abort_unless($user->filiale_id === $filiale->id, 404);
    }

    private function isLastActiveUser(Filiale $filiale, User $user): bool
    {
        $activeCount = $filiale->users()->where('is_active', true)->count();

        return $activeCount <= 1 && $user->is_active;
    }
}
