<?php

namespace App\Http\Controllers\Backend;

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

class BlogCategoryController extends Controller
{
    public function index(Request $request)
    {
        $query = BlogCategory::withCount('blogs');

        // Search functionality
        if ($request->has('search') && !empty($request->search)) {
            $search = $request->input('search');
            $query->where('name', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
        }

        $categories = $query->latest()->paginate(15);
        return view('admin.blog_categories.index', compact('categories'));
    }

    public function create()
    {
        return view('admin.blog_categories.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:blog_categories,name',
            'description' => 'nullable|string|max:500',
            'status' => 'required|boolean',
        ]);

        BlogCategory::create([
            'name' => $request->name,
            'slug' => Str::slug($request->name),
            'description' => $request->description,
            'status' => $request->status,
        ]);

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

    public function edit(BlogCategory $blogCategory)
    {
        return view('admin.blog_categories.edit', compact('blogCategory'));
    }

    public function update(Request $request, BlogCategory $blogCategory)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:blog_categories,name,' . $blogCategory->id,
            'description' => 'nullable|string|max:500',
            'status' => 'required|boolean',
        ]);

        $blogCategory->update([
            'name' => $request->name,
            'slug' => Str::slug($request->name),
            'description' => $request->description,
            'status' => $request->status,
        ]);

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

    public function destroy(BlogCategory $blogCategory)
    {
        // Check if category has blogs
        if ($blogCategory->blogs()->count() > 0) {
            return redirect()->route('admin.blog-categories.index')
                ->with('error', 'Cannot delete category that has blogs. Please move or delete the blogs first.');
        }

        $blogCategory->delete();

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

    /**
     * Toggle category status
     */
    public function toggleStatus(Request $request, $id)
    {
        $category = BlogCategory::findOrFail($id);
        
        $request->validate([
            'status' => 'required|boolean',
        ]);

        $category->update([
            'status' => $request->status,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Category status updated successfully.',
            'status' => $category->status
        ]);
    }

    /**
     * Bulk toggle status
     */
    public function bulkToggleStatus(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:blog_categories,id',
            'status' => 'required|boolean',
        ]);

        BlogCategory::whereIn('id', $request->ids)->update([
            'status' => $request->status,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Categories status updated successfully.',
        ]);
    }

    /**
     * Bulk delete categories
     */
    public function bulkDelete(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:blog_categories,id',
        ]);

        // Check if any category has blogs
        $categoriesWithBlogs = BlogCategory::whereIn('id', $request->ids)
            ->whereHas('blogs')
            ->pluck('name')
            ->toArray();

        if (!empty($categoriesWithBlogs)) {
            return response()->json([
                'success' => false,
                'message' => 'Cannot delete categories that have blogs: ' . implode(', ', $categoriesWithBlogs),
            ], 400);
        }

        BlogCategory::whereIn('id', $request->ids)->delete();

        return response()->json([
            'success' => true,
            'message' => 'Categories deleted successfully.',
        ]);
    }

    /**
     * Search categories
     */
    public function search(Request $request)
    {
        $query = $request->get('q');
        $status = $request->get('status');

        $categories = BlogCategory::withCount('blogs')
            ->when($query, function ($q) use ($query) {
                $q->where('name', 'like', "%{$query}%")
                  ->orWhere('description', 'like', "%{$query}%");
            })
            ->when($status !== null, function ($q) use ($status) {
                $q->where('status', $status);
            })
            ->latest()
            ->paginate(15);

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