<?php

namespace App\Http\Controllers\Api\Companies;

use App\Http\Controllers\Controller;
use App\Models\Companies\Company;
use App\Models\Companies\CompanyMember;
use App\Models\Companies\Department;
use App\Models\User;
use App\Services\Filters\FiltersService;
use App\Transformers\Companies\CompanyMemberTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MembersController extends Controller {
    protected CompanyMember $model;

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

    public function index(Request $request): JsonResponse {
        $filters = collect($request->has('filters') ? json_decode($request->get('filters'), true) : [])->filter(function($val) {return $val;});
        $query = $this->model->query();
        $service = FiltersService::getService('companyMembers');
        $service->applyFilters($query, $filters);
        $paginator = $query->paginate(2);
        return fractal($paginator, new CompanyMemberTransformer())->respond();
    }

    public function show($id): JsonResponse {
        $model = $this->model->byUuid($id)->firstOrFail();
        return fractal($model, new CompanyMemberTransformer())->respond();
    }

    public function store(Request $request): JsonResponse {
        $this->validate($request, [
            'name' => 'required',
            'position' => 'required',
            'company' => 'required|exists:companies,uuid',
        ]);
        $user = User::getByData($request->only('name', 'email', 'phone'));
        $company = Company::byUuid($request->get('company'))->first();
        $department = Department::byUuid($request->get('department'));
        $model = $company->addMember($user, $request->get('position'), $department->id ?? null, $request->get('rank'));
        return fractal($model, new CompanyMemberTransformer())->respond(201);
    }

    public function update(Request $request, $uuid): JsonResponse	{
        $this->validate($request, [
            'name' => 'required'
        ]);

        $model = $this->model->byUuid($uuid)->firstOrFail();
        foreach (['name', 'phone'] as $key) {
            if ($request->has($key)) {
                $model->user->update([$key => $request->get($key)]);
            }
        }

        $model->update($request->all());
        return fractal($model->fresh(), new CompanyMemberTransformer())->respond();
    }

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