<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use App\Models\ProductCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class CategoryController extends Controller
{
    public function index()
    {
        $categories = ProductCategory::with('parent')
            ->withCount('products', 'children')
            ->orderBy('name')
            ->paginate(15);
        
        return view('settings.categories.index', compact('categories'));
    }

    public function tree()
    {
        $categories = ProductCategory::with('children.children')
            ->whereNull('parent_id')
            ->orderBy('name')
            ->get();
        
        return view('settings.categories.tree', compact('categories'));
    }

    public function create()
    {
        $categories = ProductCategory::orderBy('name')->get();
        return view('settings.categories.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:product_categories',
            'parent_id' => 'nullable|exists:product_categories,id',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $data = [
            'name' => $request->name,
            'slug' => Str::slug($request->name),
            'parent_id' => $request->parent_id,
            'description' => $request->description,
            'status' => $request->boolean('status', true),
            'created_by' => Auth::id()
        ];

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $imageName = time() . '_' . Str::slug($request->name) . '.' . $image->getClientOriginalExtension();
            $image->storeAs('public/categories', $imageName);
            $data['image'] = $imageName;
        }

        ProductCategory::create($data);

        return redirect()->route('settings.categories.index')
            ->with('success', 'Category created successfully.');
    }

    public function edit(ProductCategory $category)
    {
        $categories = ProductCategory::where('id', '!=', $category->id)
            ->whereNotIn('id', $category->childIds())
            ->orderBy('name')
            ->get();
        
        return view('settings.categories.edit', compact('category', 'categories'));
    }

    public function update(Request $request, ProductCategory $category)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:product_categories,name,' . $category->id,
            'parent_id' => 'nullable|exists:product_categories,id|not_in:' . $category->id,
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $data = [
            'name' => $request->name,
            'slug' => Str::slug($request->name),
            'parent_id' => $request->parent_id,
            'description' => $request->description,
            'status' => $request->boolean('status', true),
            'updated_by' => Auth::id()
        ];

        if ($request->hasFile('image')) {
            // Delete old image
            if ($category->image) {
                \Storage::delete('public/categories/' . $category->image);
            }
            
            $image = $request->file('image');
            $imageName = time() . '_' . Str::slug($request->name) . '.' . $image->getClientOriginalExtension();
            $image->storeAs('public/categories', $imageName);
            $data['image'] = $imageName;
        }

        $category->update($data);

        return redirect()->route('settings.categories.index')
            ->with('success', 'Category updated successfully.');
    }

    public function destroy(ProductCategory $category)
    {
        if ($category->children()->count() > 0) {
            return redirect()->route('settings.categories.index')
                ->with('error', 'Cannot delete category with subcategories.');
        }

        if ($category->products()->count() > 0) {
            return redirect()->route('settings.categories.index')
                ->with('error', 'Cannot delete category with products.');
        }

        // Delete image
        if ($category->image) {
            \Storage::delete('public/categories/' . $category->image);
        }

        $category->delete();
        return redirect()->route('settings.categories.index')
            ->with('success', 'Category deleted successfully.');
    }
}