<?php

namespace Modules\Category\Observers;

use Modules\Category\Entities\Category;

class CategoryObserver
{
    /**
     * Handle the model "created" event.
     */
    public function created(Category $category): void
    {
        if (is_null($category->slug)) {
            $category->slug = str($category->name)->slug() . '-' . $category->id;
        }

        $category->position = Category::max('position') + 1;
        $category->saveQuietly();
    }

    /**
     * Handle the model "updated" event.
     */
    public function updated(Category $category): void
    {
        if ($category->wasChanged('name')) {
            $category->updateQuietly([
                'slug' => str($category->name)->slug() . '-' . $category->id
            ]);
        }
    }

    /**
     * Handle the model "deleted" event.
     */
    public function deleted(Category $category): void
    {
        $category->updateQuietly([
            'is_active' => false,
        ]);

        $category->children()->update(['parent_id' => null, 'position' => 0]);
    }

    /**
     * Handle the model "restored" event.
     */
    public function restored(Category $category): void
    {
        //
    }

    /**
     * Handle the model "force deleted" event.
     */
    public function forceDeleted(Category $category): void
    {
        //
    }
}
