<?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\Database\QueryException;
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,
            'mobile' =>$request->mobile,
        ]);
        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,
            'mobile' =>$request->mobile,
        ]);
        return $this->successResponse();
    }

    public function destroy(Rahdaran $rahdaran): JsonResponse
    {
        try {
            $rahdaran->delete();
            return $this->successResponse();
        }
        catch (QueryException $exception) {
            return $this->errorResponse('امکان حذف وجود ندارد');
        }
    }

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

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

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