319 lines
10 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreClientRequest;
use App\Http\Requests\UpdateClientRequest;
use App\Http\Resources\Client\ClientResource;
use App\Http\Resources\Client\ClientCollection;
use App\Repositories\ClientRepositoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
class ClientController extends Controller
{
public function __construct(
private readonly ClientRepositoryInterface $clientRepository
) {
}
/**
* Display a listing of clients.
*/
public function index(Request $request): ClientCollection|JsonResponse
{
try {
$perPage = $request->get('per_page', 15);
$filters = [
'search' => $request->get('search'),
'is_active' => $request->get('is_active'),
'group_id' => $request->get('group_id'),
'client_category_id' => $request->get('client_category_id'),
'sort_by' => $request->get('sort_by', 'created_at'),
'sort_direction' => $request->get('sort_direction', 'desc'),
];
// Remove null filters
$filters = array_filter($filters, function ($value) {
return $value !== null && $value !== '';
});
$clients = $this->clientRepository->paginate($perPage, $filters);
return new ClientCollection($clients);
} catch (\Exception $e) {
Log::error('Error fetching clients: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la récupération des clients.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
/**
* Store a newly created client.
*/
public function store(StoreClientRequest $request): ClientResource|JsonResponse
{
try {
$client = $this->clientRepository->create($request->validated());
return new ClientResource($client);
} catch (\Exception $e) {
Log::error('Error creating client: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'data' => $request->validated(),
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la création du client.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
/**
* Display the specified client.
*/
public function show(string $id): ClientResource|JsonResponse
{
try {
$client = $this->clientRepository->find($id);
if (!$client) {
return response()->json([
'message' => 'Client non trouvé.',
], 404);
}
return new ClientResource($client);
} catch (\Exception $e) {
Log::error('Error fetching client: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'client_id' => $id,
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la récupération du client.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
public function searchBy(Request $request): JsonResponse
{
try {
$name = $request->get('name', '');
if (empty($name)) {
return response()->json([
'message' => 'Le paramètre "name" est requis.',
], 400);
}
$clients = $this->clientRepository->searchByName($name);
return response()->json([
'data' => $clients,
'count' => $clients->count(),
'message' => $clients->count() > 0
? 'Clients trouvés avec succès.'
: 'Aucun client trouvé.',
], 200);
} catch (\Exception $e) {
Log::error('Error searching clients by name: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'search_term' => $name,
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la recherche des clients.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
/**
* Update the specified client.
*/
public function update(UpdateClientRequest $request, string $id): ClientResource|JsonResponse
{
try {
$updated = $this->clientRepository->update($id, $request->validated());
if (!$updated) {
return response()->json([
'message' => 'Client non trouvé ou échec de la mise à jour.',
], 404);
}
$client = $this->clientRepository->find($id);
return new ClientResource($client);
} catch (\Exception $e) {
Log::error('Error updating client: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'client_id' => $id,
'data' => $request->validated(),
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la mise à jour du client.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
/**
* Remove the specified client.
*/
public function destroy(string $id): JsonResponse
{
try {
$deleted = $this->clientRepository->delete($id);
if (!$deleted) {
return response()->json([
'message' => 'Client non trouvé ou échec de la suppression.',
], 404);
}
return response()->json([
'message' => 'Client supprimé avec succès.',
], 200);
} catch (\Exception $e) {
Log::error('Error deleting client: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'client_id' => $id,
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la suppression du client.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
/**
* Change client status (active/inactive).
*/
public function changeStatus(Request $request, string $id): ClientResource|JsonResponse
{
try {
$isActive = $request->input('is_active');
$updated = $this->clientRepository->update($id, ['is_active' => $isActive]);
if (!$updated) {
return response()->json([
'message' => 'Client non trouvé ou échec de la mise à jour.',
], 404);
}
$client = $this->clientRepository->find($id);
return new ClientResource($client);
} catch (\Exception $e) {
Log::error('Error changing client status: ' . $e->getMessage(), [
'exception' => $e,
'client_id' => $id,
]);
return response()->json(['message' => 'Erreur serveur'], 500);
}
}
/**
* Get children clients.
*/
public function getChildren(string $id): AnonymousResourceCollection|JsonResponse
{
try {
$client = $this->clientRepository->find($id);
if (!$client) {
return response()->json(['message' => 'Client not found'], 404);
}
// Assuming the relationship is defined in the model as 'children'
$children = $client->children;
return ClientResource::collection($children);
} catch (\Exception $e) {
Log::error('Error fetching children: ' . $e->getMessage(), [
'exception' => $e,
'client_id' => $id,
]);
return response()->json(['message' => 'Erreur serveur'], 500);
}
}
/**
* Add a child client.
*/
public function addChild(string $id, string $childId): JsonResponse
{
try {
$parent = $this->clientRepository->find($id);
$child = $this->clientRepository->find($childId);
if (!$parent || !$child) {
return response()->json(['message' => 'Parent or Child not found'], 404);
}
// Update child's parent_id
$this->clientRepository->update($childId, ['parent_id' => $id]);
return response()->json(['message' => 'Child added successfully'], 200);
} catch (\Exception $e) {
Log::error('Error adding child: ' . $e->getMessage(), [
'exception' => $e,
'parent_id' => $id,
'child_id' => $childId
]);
return response()->json(['message' => 'Erreur serveur'], 500);
}
}
/**
* Remove a child client.
*/
public function removeChild(string $id, string $childId): JsonResponse
{
try {
$child = $this->clientRepository->find($childId);
if (!$child) {
return response()->json(['message' => 'Child not found'], 404);
}
if ($child->parent_id != $id) {
return response()->json(['message' => 'Client is not a child of this parent'], 400);
}
// Remove parent_id
$this->clientRepository->update($childId, ['parent_id' => null]);
return response()->json(['message' => 'Child removed successfully'], 200);
} catch (\Exception $e) {
Log::error('Error removing child: ' . $e->getMessage(), [
'exception' => $e,
'parent_id' => $id,
'child_id' => $childId
]);
return response()->json(['message' => 'Erreur serveur'], 500);
}
}
}