<?php

namespace App\Http\Controllers\V3;

use App\Facades\DataTable\DataTableFacade;
use App\Http\Controllers\Controller;
use App\Http\Requests\V3\Rahdaran\StoreRequest;
use App\Http\Requests\V3\Rahdaran\UpdateRequest;
use App\Http\Traits\ApiResponse;
use App\Models\Rahdaran;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RahdaranController extends Controller
{
    use ApiResponse;

    public function index(Request $request): JsonResponse
    {
        return response()->json(DataTableFacade::run(
            Rahdaran::query(),
            $request,
            allowedFilters: ['*'],
            allowedSortings: ['*'])
        );
    }

    public function store(StoreRequest $request): JsonResponse
    {
        Rahdaran::query()->create([
            'name' =>$request->name,
            'code' =>$request->code,
        ]);
        return $this->successResponse();
    }

    public function show(Rahdaran $rahdaran): JsonResponse
    {
        return $this->successResponse($rahdaran);
    }

    public function update(UpdateRequest $request, Rahdaran $rahdaran): JsonResponse
    {
        $rahdaran->update([
            'name' =>$request->name,
            'code' =>$request->code,
        ]);
        return $this->successResponse();
    }

    public function destroy(Rahdaran $rahdaran): JsonResponse
    {
        $rahdaran->delete();
        return $this->successResponse();
    }

    public function list(): JsonResponse
    {
        return $this->successResponse(Rahdaran::all());
    }

    public function search(Request $request): JsonResponse
    {
        if ($request->has('code')) {
            $matchedSearchedRahdaran = Rahdaran::query()
                ->where('code', 'LIKE', "%{$request->code}%")
                ->get();
        }
        else {
            $matchedSearchedRahdaran = Rahdaran::query()
                ->where('name', 'LIKE', "%{$request->name}%")
                ->get();
        }

        return $this->successResponse($matchedSearchedRahdaran);
    }
}
