<?php

namespace App\Services;

use App\Models\Classes;
use App\Services\AuditTrailService;
use App\Http\Resources\ClassesResource;

class ClassesService
{
    protected AuditTrailService $auditTrailService;

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

    public function getAll($status, $pagination)
    {
        $classes = Classes::when($status == "inactive", function ($query) {
            $query->onlyTrashed();
        })
            ->useFilters()
            ->dynamicPaginate();

        if (!$pagination) {
            ClassesResource::collection($classes);
        } else {
            $classes = ClassesResource::collection($classes);
        }

        return $classes;
    }

    public function getById($id)
    {
        return $classes = Classes::withTrashed()->find($id);
    }
    public function create(array $data)
    {
        $classes = Classes::create([
            "name" => $data["name"],
        ]);

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

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

        return $classes;
    }

    public function update($id, array $data)
    {
        $classes = Classes::find($id);

        if (!$classes) {
            return null;
        }

        $oldData = $classes->getAttributes();

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

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

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

        return $classes;
    }

    public function toggleArchived($id)
    {
        $classes = Classes::withTrashed()->find($id);

        if (!$classes) {
            return null;
        }

        $oldData = $classes->getAttributes();

        if (!$classes->trashed()) {
            $classes->delete();
            $message = __("models.lc_archived");
        } else {
            $classes->restore();
            $message = __("models.lc_unarchived");
        }

        $action = $message;

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

        return [
            "classes" => $classes,
            "status" => $message,
        ];
    }
}
