<?php

namespace App\Http\Traits;

use App\Models\Department;
use App\Models\EmployeePosition;
use App\Models\EmployeeType;

/**
 * Trait UserDataFetcherTrait
 *
 * This trait provides methods for fetching user details such as department, position, and employee type.
 *
 * @package App\Http\Traits
 */
trait UserDataFetcherTrait
{
    /**
     * Get or create department ID from the database based on its name.
     *
     * @param string $departmentName The name of the department.
     *
     * @return int|null The department's ID or null if not found.
     */
    public function getDepartmentIdFromName($departmentName)
    {
        return $this->getOrCreateId($departmentName, 'name', Department::class);
    }

    /**
     * Get or create the position ID from the database based on its name.
     *
     * @param string $positionName The name of the position.
     *
     * @return int|null The position's ID or null if not found.
     */
    public function getOrCreatePositionIdByName($positionName)
    {
        return $this->getOrCreateId($positionName, 'name', EmployeePosition::class);
    }

    /**
     * Fetch employee type ID from the database.
     *
     * @param string $employeeTypeName The name of the employee type to fetch.
     *
     * @return int|null The employee type's ID or null if not found.
     */
    public function getOrCreateEmployeeTypeIdByName($employeeTypeName)
    {
        return $this->getOrCreateId($employeeTypeName, 'name', EmployeeType::class);
    }

    /**
     * Get or create data for a specific field in the database.
     *
     * @param string $inputData The input data containing the field value.
     * @param string $field     The name of the field in the database.
     * @param string $model     The model class to use for database operations.
     *
     * @return int|null The ID of the fetched or created record or null if not found.
     */
    private function getOrCreateId($inputData, $field, $model)
    {
        if (!empty($inputData)) {
            $slug = str_slug($inputData, '_');

            $item = $model::firstOrCreate(
                ['slug' => trim($slug)],
                [$field => $inputData]
            );

            return $item->id;
        }

        return null;
    }
}
