<?php

namespace App\Modules\Customization\CustomFields\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Customization\CustomFields\DTOs\CustomFieldWriteData;
use App\Modules\Customization\CustomFields\Models\CustomField;
use App\Modules\Customization\CustomFields\Requests\StoreCustomFieldRequest;
use App\Modules\Customization\CustomFields\Requests\UpdateCustomFieldRequest;
use App\Modules\Customization\CustomFields\Services\CustomFieldService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CustomFieldPageController extends Controller
{
    private const MODULE = 'hr';

    private const ENTITY = 'employees';

    public function __construct(
        private readonly CustomFieldService $service,
    ) {}

    public function index(Request $request): View
    {
        $tenant = $request->user()?->tenant;
        abort_if($tenant === null, 403);

        return view('pages.settings.custom-fields.index', [
            'fields' => $this->service->listForTenant((int) $tenant->id, self::MODULE, self::ENTITY),
        ]);
    }

    public function create(Request $request): View
    {
        $tenant = $request->user()?->tenant;
        abort_if($tenant === null, 403);

        return view('pages.settings.custom-fields.create', [
            'module' => self::MODULE,
            'entity' => self::ENTITY,
        ]);
    }

    public function store(StoreCustomFieldRequest $request): RedirectResponse
    {
        $tenant = $request->user()?->tenant;
        abort_if($tenant === null, 403);
        $this->service->store($tenant, CustomFieldWriteData::fromValidated($request->validated()));

        return redirect()->route('settings.custom-fields.index')
            ->with('status', __('custom_fields.flash.created'));
    }

    public function edit(Request $request, CustomField $customField): View
    {
        $tenant = $request->user()?->tenant;
        abort_if($tenant === null || (int) $customField->tenant_id !== (int) $tenant->id, 403);

        return view('pages.settings.custom-fields.edit', [
            'field' => $customField->load('options'),
            'module' => self::MODULE,
            'entity' => self::ENTITY,
        ]);
    }

    public function update(UpdateCustomFieldRequest $request, CustomField $customField): RedirectResponse
    {
        $this->service->update($customField, CustomFieldWriteData::fromValidated($request->validated()));

        return redirect()->route('settings.custom-fields.index')
            ->with('status', __('custom_fields.flash.updated'));
    }

    public function deactivate(CustomField $customField): RedirectResponse
    {
        $this->service->deactivate($customField);

        return redirect()->route('settings.custom-fields.index')
            ->with('status', __('custom_fields.flash.deactivated'));
    }

}
