<?php

namespace App\Services;

use App\Models\Unit;

class UnitService
{
    protected AuditTrailService $auditTrailService;

    public function __construct(AuditTrailService $auditTrailService)
    {
        $this->auditTrailService = $auditTrailService;
    }

    public function getAll()
    {
        $unit = Unit::useFilters()->dynamicPaginate();

        if ($unit->isEmpty()) {
            return null;
        }

        return $unit;
    }

    public function getById(int $id)
    {
        $unit = Unit::find($id);

        if (!$unit) {
            return null;
        }

        return $unit;
    }

    public function create(array $data)
    {
        $unit = Unit::create([
            "code" => $data["code"],
            "name" => $data["name"],
        ]);

        $module_type = __("models.lc_masterlist");
        $module_name = __("models.uom");
        $action = __("models.lc_created");

        $this->auditTrailService->log(
            $module_type,
            $module_name,
            $unit->id,
            $action,
            $unit,
            null,
            $data
        );

        return $unit;
    }

    public function update(array $data, int $id)
    {
        $unit = Unit::find($id);

        if (!$unit) {
            return null;
        }

        $oldData = $unit->getAttributes();

        $unit->fill([
            "code" => $data["code"],
            "name" => $data["name"],
        ]);

        if ($unit->isDirty()) {
            $unit->save();
            $unit->was_changed = true;

            $this->auditTrailService->log(
                __("models.lc_masterlist"),
                __("models.uom"),
                $unit->id,
                __("models.lc_updated"),
                $unit,
                $oldData,
                $data
            );
        } else {
            $unit->was_changed = false;
        }

        return $unit;
    }

    public function toggleArchive(int $id)
    {
        $unit = Unit::withTrashed()->find($id);

        if (!$unit) {
            return null;
        }

        if ($unit->trashed()) {
            $unit->restore();
            $action = __("models.lc_restored");
        } else {
            $unit->delete();
            $action = __("models.lc_archived");
        }

        $this->auditTrailService->log(
            __("models.lc_masterlist"),
            __("models.uom"),
            $unit->id,
            $action,
            $unit
        );

        return $unit;
    }
}
