<?php

namespace App\Services;

use App\Models\Category;
use Illuminate\Support\Facades\Storage;

class CategoryService
{
    public function list($request)
    {
        $query = Category::with('parent');

        if ($request->filled('search')) {
            $query->where('category_name', 'like', '%' . $request->search . '%');
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('parent_id')) {
            if ($request->parent_id == 0) {
                $query->whereNull('parent_id');
            } else {
                $query->where('parent_id', $request->parent_id);
            }
        }

        return $query
            ->orderBy('display_order')
            ->orderBy('category_name')
            ->paginate(10);
    }

    public function store($request)
    {
        $data = $request->validated();

        if ($request->hasFile('category_icon')) {
            $data['category_icon'] = $request->file('category_icon')
                ->store('categories', 'public');
        }

        return Category::create($data);
    }

    public function update($request, Category $category)
    {
        $data = $request->validated();

        if ($request->hasFile('category_icon')) {

            if ($category->category_icon &&
                Storage::disk('public')->exists($category->category_icon)) {

                Storage::disk('public')->delete($category->category_icon);
            }

            $data['category_icon'] = $request->file('category_icon')
                ->store('categories', 'public');
        }

        $category->update($data);

        return $category->refresh();
    }

    public function delete(Category $category)
    {
        if ($category->children()->count()) {
            throw new \Exception('Cannot delete category. Subcategories exist.');
        }

        if ($category->category_icon &&
            Storage::disk('public')->exists($category->category_icon)) {

            Storage::disk('public')->delete($category->category_icon);
        }

        $category->delete();
    }
}