<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\CategoryRequest;
use App\Models\Category;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class AdminCategoryController extends Controller
{
    public function index(): View
    {
        $categories = Category::with('parent', 'children')
            ->withCount('products')
            ->orderBy('name_en')
            ->get();

        return view('admin.categories.index', compact('categories'));
    }

    public function create(): View
    {
        $parentCategories = Category::whereNull('parent_id')
            ->orderBy('name_en')
            ->get();

        return view('admin.categories.create', compact('parentCategories'));
    }

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

        // Handle image upload or URL
        if ($request->hasFile('image_file')) {
            $data['image'] = $this->uploadImage($request->file('image_file'));
        } elseif ($request->filled('image_url')) {
            $data['image'] = $data['image_url'];
        }

        unset($data['image_url'], $data['image_file']);

        Category::create($data);

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

    public function edit(Category $category): View
    {
        $parentCategories = Category::whereNull('parent_id')
            ->where('id', '!=', $category->id)
            ->orderBy('name_en')
            ->get();

        return view('admin.categories.edit', compact('category', 'parentCategories'));
    }

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

        // Handle image upload or URL
        if ($request->hasFile('image_file')) {
            // Delete old image if exists
            if ($category->image && str_starts_with($category->image, 'uploads/')) {
                Storage::disk('public')->delete($category->image);
            }
            $data['image'] = $this->uploadImage($request->file('image_file'));
        } elseif ($request->filled('image_url')) {
            $data['image'] = $data['image_url'];
        }

        unset($data['image_url'], $data['image_file']);

        $category->update($data);

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

    public function destroy(Category $category): RedirectResponse
    {
        if ($category->products()->count() > 0) {
            return redirect()->route('admin.categories.index')
                ->with('error', 'Cannot delete category with existing products.');
        }

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

        $category->delete();

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

    private function uploadImage(UploadedFile $file): string
    {
        $path = $file->store('categories', 'public');

        return 'storage/'.$path;
    }
}
