<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PortfolioCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class PortfolioCategoryController extends Controller
{
    public function index()
    {
        $categories = PortfolioCategory::orderBy('name')->get();
        return view('admin.portfolio.categories.index', compact('categories'));
    }

    public function create()
    {
        return view('admin.portfolio.categories.form', ['category' => new PortfolioCategory()]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:portfolio_categories,slug',
        ]);

        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['name']);
        }

        PortfolioCategory::create($validated);

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

    public function edit(PortfolioCategory $portfolio_category)
    {
        return view('admin.portfolio.categories.form', ['category' => $portfolio_category]);
    }

    public function update(Request $request, PortfolioCategory $portfolio_category)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:portfolio_categories,slug,' . $portfolio_category->id,
        ]);

        $portfolio_category->update($validated);

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

    public function destroy(PortfolioCategory $portfolio_category)
    {
        if ($portfolio_category->portfolioItems()->count() > 0) {
            return back()->with('error', 'Cannot delete category that has portfolio items.');
        }

        $portfolio_category->delete();

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