<?php

namespace App\Http\Controllers\Backoffice;

use App\Facades\Backoffice\BackendUserService;
use App\Facades\CompanyProfilesService;
use App\Http\Controllers\Controller;
use App\Http\Requests\Backoffice\CompanyProfileCreateUpdateRequest;
use App\Http\Requests\Backoffice\CompanyProfileListRequest;
use App\Http\Requests\Backoffice\CompanyProfileJobOfferRequest;
use App\Http\Requests\Backoffice\CompanyProfileOfficeRequest;
use App\Http\Requests\Backoffice\CompanyProfileProjectRequest;
use App\Http\Resources\Backoffice\CompanyProfiles\CompanyProfileDetailResource;
use App\Http\Resources\Backoffice\CompanyProfiles\CompanyProfileJobOfferResource;
use App\Http\Resources\Backoffice\CompanyProfiles\CompanyProfileProjectResource;
use App\Http\Resources\Backoffice\CompanyProfiles\CompanyProfileResource;
use App\Exceptions\ApiHttpException;
use App\Http\Requests\Backoffice\AdminContentAutoComplete;
use App\Http\Resources\Offices\OfficeResource;
use App\Models\CompanyProfile;
use Illuminate\Support\Facades\Session;
use Inertia\Inertia;

class CompanyProfilesController extends Controller
{
    protected function authorizeManage(): void
    {
        $loggedUser = BackendUserService::getLoggedUser();
        if (!$loggedUser->hasPermission('accounts.manage')) {
            abort(403);
        }
    }

    public function getIndex()
    {
        $this->authorizeManage();

        $loggedUser = BackendUserService::getLoggedUser();

        return Inertia::render('Backoffice/CompanyProfiles/ListCompanyProfiles', [
            'data' => [
                'user' => $loggedUser,
            ],
        ]);
    }

    public function postList(CompanyProfileListRequest $request)
    {
        $this->authorizeManage();

        $data = $request->validated();

        $list = CompanyProfilesService::getBackofficeProfiles($data);

        return CompanyProfileResource::collection($list);
    }

    public function getCreate()
    {
        $this->authorizeManage();

        return Inertia::render('Backoffice/CompanyProfiles/CreateCompanyProfile', [
            'message' => Session::get('message'),
            'errorMessage' => Session::get('errorMessage'),
        ]);
    }

    public function postCreate(CompanyProfileCreateUpdateRequest $request)
    {
        $this->authorizeManage();

        $data = $request->validated();

        $profile = CompanyProfilesService::createBackofficeProfile($data);

        return new CompanyProfileDetailResource($profile);
    }

    public function getEdit($profileId)
    {
        $this->authorizeManage();

        try {
            $profile = CompanyProfilesService::getBackofficeProfile((int) $profileId);
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return Inertia::render('Backoffice/CompanyProfiles/EditCompanyProfile', [
            'data' => new CompanyProfileDetailResource($profile),
            'message' => Session::get('message'),
            'errorMessage' => Session::get('errorMessage'),
        ]);
    }

    public function getCompanyProfile($profileId)
    {
        $this->authorizeManage();

        try {
            $profile = CompanyProfilesService::getBackofficeProfile((int) $profileId);
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return new CompanyProfileDetailResource($profile);
    }

    public function getCompanyProfileByAccount($accountId)
    {
        $this->authorizeManage();

        $profile = CompanyProfilesService::getBackofficeProfileByAccount((int) $accountId);

        return new CompanyProfileDetailResource($profile);
    }

    public function updateCompanyProfile($profileId, CompanyProfileCreateUpdateRequest $request)
    {
        $this->authorizeManage();

        $data = $request->validated();

        try {
            $profile = CompanyProfilesService::updateBackofficeProfile((int) $profileId, $data);
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return new CompanyProfileDetailResource($profile);
    }

    public function getOffices($profileId)
    {
        $this->authorizeManage();

        try {
            $offices = CompanyProfilesService::getBackofficeOffices((int) $profileId);
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return OfficeResource::collection($offices);
    }

    public function createOffice($profileId, CompanyProfileOfficeRequest $request)
    {
        $this->authorizeManage();

        try {
            $office = CompanyProfilesService::createBackofficeOffice((int) $profileId, $request->validated());
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return new OfficeResource($office);
    }

    public function updateOffice($profileId, $officeId, CompanyProfileOfficeRequest $request)
    {
        $this->authorizeManage();

        try {
            $office = CompanyProfilesService::updateBackofficeOffice((int) $profileId, (int) $officeId, $request->validated());
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return new OfficeResource($office);
    }

    public function deleteOffice($profileId, $officeId)
    {
        $this->authorizeManage();

        try {
            $success = CompanyProfilesService::deleteBackofficeOffice((int) $profileId, (int) $officeId);
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return response()->json(['success' => $success]);
    }

    public function postCompanyProfileAutoComplete(AdminContentAutoComplete $request)
    {
        $data = $request->validated();
        $searchTerm = urldecode($data['searchTerm']);
        $exactId = !empty($data['id']) ? $data['id'] : null;

        $query = CompanyProfile::select('id', 'name as title');

        if (!empty($searchTerm)) {
            $query->where('name', 'like', "%$searchTerm%");
        }

        if (!is_null($exactId)) {
            $query->where('id', $exactId);
        }

        $query->orderBy('name', 'ASC');

        $accounts = $query->limit(5)->get();

        return response()->json($accounts, 200);
    }

    public function getJobOffers($profileId)
    {
        $this->authorizeManage();

        try {
            $jobOffers = CompanyProfilesService::getBackofficeJobOffers((int) $profileId);
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return CompanyProfileJobOfferResource::collection($jobOffers);
    }

    public function createJobOffer($profileId, CompanyProfileJobOfferRequest $request)
    {
        $this->authorizeManage();

        try {
            $jobOffer = CompanyProfilesService::createBackofficeJobOffer((int) $profileId, $request->validated());
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return new CompanyProfileJobOfferResource($jobOffer);
    }

    public function updateJobOffer($profileId, $jobOfferId, CompanyProfileJobOfferRequest $request)
    {
        $this->authorizeManage();

        try {
            $jobOffer = CompanyProfilesService::updateBackofficeJobOffer((int) $profileId, (int) $jobOfferId, $request->validated());
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return new CompanyProfileJobOfferResource($jobOffer);
    }

    public function deleteJobOffer($profileId, $jobOfferId)
    {
        $this->authorizeManage();

        try {
            $success = CompanyProfilesService::deleteBackofficeJobOffer((int) $profileId, (int) $jobOfferId);
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return response()->json(['success' => $success]);
    }

    public function getProjects($profileId)
    {
        $this->authorizeManage();

        try {
            $projects = CompanyProfilesService::getBackofficeProjects((int) $profileId);
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return CompanyProfileProjectResource::collection($projects);
    }

    public function createProject($profileId, CompanyProfileProjectRequest $request)
    {
        $this->authorizeManage();

        try {
            $project = CompanyProfilesService::createBackofficeProject((int) $profileId, $request->validated());
        } catch (ApiHttpException $e) {
            abort($e->getCode() === 422 ? 422 : 404, $e->getMessage());
        }

        return new CompanyProfileProjectResource($project);
    }

    public function updateProject($profileId, $projectId, CompanyProfileProjectRequest $request)
    {
        $this->authorizeManage();

        try {
            $project = CompanyProfilesService::updateBackofficeProject((int) $profileId, (int) $projectId, $request->validated());
        } catch (ApiHttpException $e) {
            abort($e->getCode() === 422 ? 422 : 404, $e->getMessage());
        }

        return new CompanyProfileProjectResource($project);
    }

    public function deleteProject($profileId, $projectId)
    {
        $this->authorizeManage();

        try {
            $success = CompanyProfilesService::deleteBackofficeProject((int) $profileId, (int) $projectId);
        } catch (ApiHttpException $e) {
            abort(404);
        }

        return response()->json(['success' => $success]);
    }
}
