sintonia_webapp/app/Http/Controllers/UserController.php
2025-07-18 14:10:37 +02:00

103 lines
3.2 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Actions\Fortify\UpdateUserProfileInformation;
use App\Models\Show\Show;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Exception;
use Log;
class UserController extends Controller
{
public function index(Request $request)
{
$queryParams = collect($request->except('withShow'));
$userFilter = (new User())->searchFilter($queryParams);
if ($request->withShow) {
$userFilter = $userFilter->with('showDjs');
}
return response()->json($userFilter->get());
}
/**
* @throws \Exception
*/
public function store(Request $request)
{
try {
$showInfos = $request->show;
$showDaysRules = $request->showDaysRules;
$showDjs = $request->showDjs;
$show = Show::firstOrCreate($showInfos);
$this->manageShowDays($show, $showDaysRules);
$this->manageShowDjs($showDjs, $show);
} catch (Exception $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
return response()->json(['message' => 'Show created successfully']);
}
public function show(User $user)
{
$allowedRoles = ['admin', 'editor'];
$authenticatedUser = auth()->user();
if ( ! $authenticatedUser && ! in_array($authenticatedUser->type, $allowedRoles)) {
return response()->json(['message' => 'Forbidden'], 403);
}
return response()->json($user);
}
public function userProfile()
{
$user =auth()->user();
$user->role = $user->roles()->value('name');
return response()->json($user);
}
public function update(Request $request, User $user, UpdateUserProfileInformation $updater)
{
$authenticatedUser = auth()->user();
if ($authenticatedUser->id !== $user->id && !$authenticatedUser->hasPermissionTo('user.manageAll')) {
return response()->json(['message' => 'You do not have permission to edit other users.'], 403);
}
if ($authenticatedUser->id === $user->id && !$authenticatedUser->hasPermissionTo('users.manageOwn')) {
return response()->json(['message' => 'You do not have permission to edit your own profile.'], 403);
}
try {
$updater->update($user, $request->all());
$user->load('preferences');
return response()->json($user);
} catch (\Throwable $e) {
Log::error($e->getMessage());
if ($e instanceof \Illuminate\Validation\ValidationException) {
return response()->json(['message' => $e->getMessage(), 'errors' => $e->errors()], 422);
}
return response()->json(['message' => 'Failed to update user'], 500);
}
}
public function destroy(Request $request)
{
try {
$showIds = $request->input('showIds');
Show::destroy($showIds);
$responseMessage = 'Shows deleted';
} catch (Exception $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
return response()->json(['message' => $responseMessage]);
}
}