<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Notification;
use App\Notifications\UserSetPasswordNotification;
use Illuminate\Support\Str;

class UserController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        // if not owner or admin, return error
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous ne pouvez pas créer un utilisateur.');
        }

        $validated = $request->validate([
            'firstname' => ['required', 'string', 'min:2'],
            'lastname' => ['required', 'string', 'min:2'],
            'email' => ['required', 'email', 'unique:users,email'],
            'role' => ['required', 'string', 'in:' . implode(',', array_column(User::ROLES, 'id'))],
        ]);

        $username = User::generateUniqueUsername($validated['firstname'] . ' ' . $validated['lastname']);

        $user = User::create([
            'firstname' => $validated['firstname'],
            'lastname' => $validated['lastname'],
            'email' => $validated['email'],
            'username' => $username,
            'slug' => (string) Str::orderedUuid(),
            'role' => $validated['role'],
            'status' => User::STATUS_INACTIVE,
            'password' => Str::password(12),
        ]);

        // Send set-password email with temporary signed link (valid 48h)
        $signedUrl = URL::temporarySignedRoute(
            'users.set-password', now()->addHours(48), ['user' => $user->username]
        );

        Notification::route('mail', $user->email)
            ->notify(new UserSetPasswordNotification($user, $signedUrl));

        return redirect()->route('users.show', $user)
            ->with('success', 'Utilisateur créé. Un email de définition du mot de passe a été envoyé.');
    }

    public function activate(User $user): RedirectResponse
    {
        // if not owner or admin, return error
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous ne pouvez pas activer cet utilisateur.');
        }
        
        $user->update(['status' => User::STATUS_ACTIVE]);
        return back()->with('success', 'Utilisateur activé.');
    }

    public function deactivate(User $user): RedirectResponse
    {
        // if not owner or admin, return error
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous ne pouvez pas désactiver cet utilisateur.');
        }

        $user->update(['status' => User::STATUS_INACTIVE]);
        return back()->with('success', 'Utilisateur suspendu.');
    }

    public function destroy(User $user): RedirectResponse
    {
        // if not owner or admin, return error
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous ne pouvez pas supprimer cet utilisateur.');
        }

        // Prevent deleting self
        if (Auth::user()->id === $user->id) {
            return back()->with('error', 'Vous ne pouvez pas supprimer votre propre compte.');
        }

        // Prevent deleting user with role owner
        if ($user->role === 'owner') {
            return back()->with('error', 'Vous ne pouvez pas supprimer le compte propriétaire.');
        }

        // Prevent deleting user with activity logs
        if ($user->activityLogs->count() > 0) {
            return back()->with('error', 'Vous ne pouvez pas supprimer un utilisateur avec des activités.');
        }

        $user->delete();
        return redirect()->route('users.index')->with('success', 'Utilisateur supprimé.');
    }
}


