<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Offers\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maestro\Core\Http\Controllers\Controller;
use Maestro\Core\Modules\Offers\Http\Requests\StoreOfferCatalogItemRequest;
use Maestro\Core\Modules\Offers\Http\Requests\UpdateOfferCatalogItemRequest;
use Maestro\Core\Modules\Offers\Http\Resources\OfferCatalogItemResource;
use Maestro\Core\Modules\Offers\Models\OfferServiceCatalogItem;

final class OfferCatalogController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        abort_unless($request->user()?->can('offers.view'), 403);

        $query = OfferServiceCatalogItem::query()->orderBy('name');

        if (! $request->boolean('include_inactive')) {
            $query->where('is_active', true);
        }

        $search = trim((string) $request->input('search', ''));

        if ($search !== '') {
            $like = '%'.addcslashes($search, '%_\\').'%';
            $query->where('name', 'like', $like);
        }

        $perPage = min(max(request()->integer('per_page', 50), 1), 200);

        return OfferCatalogItemResource::collection($query->paginate($perPage))->response();
    }

    public function store(StoreOfferCatalogItemRequest $request): JsonResponse
    {
        abort_unless($request->user()?->can('offers.catalog.manage'), 403);

        $validated = $request->validated();

        $item = OfferServiceCatalogItem::query()->create([
            ...$validated,
            'is_active' => $request->boolean('is_active', true),
        ]);

        return response()->json([
            'data' => new OfferCatalogItemResource($item->fresh()),
        ], 201);
    }

    public function show(Request $request, OfferServiceCatalogItem $catalogItem): JsonResponse
    {
        abort_unless($request->user()?->can('offers.view'), 403);

        return response()->json(['data' => new OfferCatalogItemResource($catalogItem)]);
    }

    public function update(UpdateOfferCatalogItemRequest $request, OfferServiceCatalogItem $catalogItem): JsonResponse
    {
        abort_unless($request->user()?->can('offers.catalog.manage'), 403);

        $validated = $request->validated();

        $catalogItem->fill($validated);
        if ($request->has('is_active')) {
            $catalogItem->is_active = $request->boolean('is_active');
        }
        $catalogItem->save();

        return response()->json([
            'data' => new OfferCatalogItemResource($catalogItem->fresh()),
        ]);
    }

    public function destroy(Request $request, OfferServiceCatalogItem $catalogItem): JsonResponse
    {
        abort_unless($request->user()?->can('offers.catalog.manage'), 403);
        $catalogItem->delete();

        return response()->json(['message' => 'Deleted.']);
    }
}
