<?php

namespace App\Services;

use App\Models\Supplier;

class SupplierService
{
    protected AuditTrailService $auditTrailService;

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

    public function getAll()
    {
        $supplier = Supplier::useFilters()
            ->dynamicPaginate();

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

        return $supplier;
    }

    public function getById(int $id)
    {
        $supplier = Supplier::where("id", $id)->first();

        if (!$supplier) {
            return null;
        }

        return $supplier;
    }

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

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

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

        return $supplier;
    }

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

        if (!$supplier) {
            return null;
        }

        $oldData = $supplier->getAttributes();

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

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

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

        return $supplier;
    }

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

        if (!$supplier) {
            return null;
        }

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

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

        return $supplier;
    }
}
