<?php

namespace App\Http\Controllers\Api\Companies;

use App\Http\Controllers\Controller;
use App\Models\Companies\Company;
use App\Services\DaDataService;
use App\Transformers\Companies\CompanyTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CompaniesController extends Controller {
    protected Company $model;

    public function __construct(Company $model) {
        $this->model = $model;
    }

    public function index(Request $request): JsonResponse {
        $filters = collect(json_decode($request->get('filters'), true) ?? []);
        $query = $this->model->query()->orderBy('updated_at', 'desc');
        if ($val = $filters->get('search')) {
            $query->where(function($query) use($val) {
                $query->where('name', 'like', "%{$val}%")->orWhere('full_name', 'like', "%{$val}%")->orWhere('inn', 'like', "%{$val}%");
            });
        }
        if ($val = $filters->get('type')) $query->whereHas('types', function($query) use($val) {
            $query->where(['name' => $val]);
        });
        $paginator = $query->paginate(config('app.pagination_limit'));
        return fractal($paginator, new CompanyTransformer())->respond();
    }

    public function show($id): JsonResponse {
        $query = ($id === 'main') ? $this->model->where(['is_main' => 1]) : $this->model->byUuid($id);
        return fractal($query->firstOrFail(), new CompanyTransformer())->respond();
    }

    public function store(Request $request): JsonResponse {
        $this->validate($request, [
            'inn' => 'required',
            'name' => 'required',
            'address' => 'required',
        ]);
        $model = $this->model->getByData($request->all());
        return fractal($model, new CompanyTransformer())->respond(201);
    }

    public function update(Request $request, $uuid): JsonResponse	{
        $model = $this->model->byUuid($uuid)->firstOrFail();
        $this->validate($request, [
            'name' => 'required',
            'address' => 'required',
        ]);
        $model->update(['name' => $request->get('name')]);
        $address = [
            'full' => $request->get('address')
        ];
        $model->legalAddress->update($address);
        $model->actualAddress->update($address);
        foreach(['phone', 'email'] as $key) {
            if ($request->has($key)) {
                $model->$key->update(['value' => $request->get($key)]);
            }
        }

        return fractal($model->fresh(), new CompanyTransformer())->respond();
    }

    public function destroy(Request $request, $uuid): JsonResponse {
        $model = $this->model->byUuid($uuid)->firstOrFail();
        $model->delete();
        return response()->json(null, 204);
    }



    public function getDataByInn(Request $request, $inn) {
        return (new DaDataService($inn))->getCompanyData();
    }
}
