<?php

namespace App\Repositories;

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

class ActiveDirectory
{
    protected $charactersToBeReplaced = ['?' => '•'];

    public function getLocationId($item, $dbField, $fileHeader)
    {
        $location = null;
        if (!empty($item->$fileHeader)) {
            $locationName = mb_convert_encoding($item->$fileHeader, "gbk", "utf-8");
            foreach ($this->charactersToBeReplaced as $key => $value) {
                $locationName = str_replace($key, $value, $locationName);
            }

            $location = Location::where('room_name', trim($locationName))->first();
        }
        $locationId = $location ? $location->id : null;
        return $locationId;
    }

    public function getPositionId($item, $dbField, $fileHeader)
    {
        $position = null;
        if (!empty($item->$fileHeader)) {
            $slug = str_slug($item->$fileHeader, '_');
            $position = EmployeePosition::firstOrCreate(['slug' => trim($slug)], ['name' => $item->$fileHeader]);
        }
        $positionId = $position ? $position->id : null;
        return $positionId;
    }

    public function getDepartmentId($item, $dbField, $fileHeader)
    {
        $department = null;
        if (!empty($item->$fileHeader)) {
            $slug = str_slug($item->$fileHeader, '_');
            $department = Department::firstOrCreate(['slug' => trim($slug)], ['name' => $item->$fileHeader]);
        }
        $departmentId = $department ? $department->id : null;
        return $departmentId;
    }

    public function getEmployeeTypeId($item, $dbField, $fileHeader)
    {
        $employeeType = null;
        if (!empty($item->$fileHeader)) {
            $slug = str_slug($item->$fileHeader, '_');
            $employeeType = EmployeeType::where('slug', trim($slug))->first();
        }
        $employeeTypeId = $employeeType ? $employeeType->id : null;
        return $employeeTypeId;
    }

    public function getStatus($item, $dbField, $fileHeader)
    {
        $status = 1;
        if (!empty($item->$fileHeader)) {
            if (strtoupper(trim($item->$fileHeader)) == 'FALSE') {
                $status = 0;
            }
        }
        return $status;
    }

    public function getLegalHold($item, $dbField, $fileHeader)
    {
        $status = 0;
        if (!empty($item->$fileHeader)) {
            $status = 1;
        }
        return $status;
    }
}
