<?php

namespace App\Services;

use App\Models\Category;

class CategoryService
{
    public function store($data)
    {
        Category::create($data);
    }

    public function update($data, $category)
    {
        $this->checkDefaultCategory("unassigned", $category);

        $category->update($data);
    }

    public function destory($category)
    {
        $this->checkDefaultCategory("unassigned", $category);

        $this->checkHasResource($category);

        $category->delete();
    }

    public function getCategories()
    {
        $table = Category::tableName();

        return Category::withCount('resources')
            ->orderByRaw("CASE WHEN id = (SELECT MIN(id) FROM {$table}) THEN id ELSE created_at END")
            ->orderBy('created_at', 'desc')->get();
    }

    public function getCategoriesCount()
    {
        return Category::where('name', '!=', 'Unassigned')->count();
    }

    private function checkDefaultCategory($defaultCategoryName, $category)
    {

        if (strtolower($category->name) == strtolower($defaultCategoryName)) {
            abort(400, "\"$defaultCategoryName\" category can't be edited or deleted.");
        }

    }

    private function checkHasResource($category)
    {

        if ($category->resources()->exists()) {
            abort(400, trans('categories.remove_resources_before',
                ['category' => $category->name]));
        }

    }

}
