<?php

namespace App\Http\Controllers\Admin;

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

class AdminBlogCategoryController extends Controller
{
    protected $data = [];

    public function index()
    {
        $this->data['title'] = 'Categories';

        $query = BlogCategory::with('posts')->orderBy('id', 'desc');

        if (request('search')) {
            $query->where(function ($query) {
                $query->where('name', 'like', '%' . request('search') . '%')
                    ->orWhere('description', 'like', '%' . request('search') . '%');
            });
        }

        $this->data['categories'] = $query->paginate(10);

        $this->data['allCategories'] = BlogCategory::all();

        return view('admin.blog.categories.index', $this->data);
    }

    public function create()
    {
        $this->data['title'] = 'Create Category';

        return view('admin.blog.categories.create', $this->data);
    }

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

        $category = BlogCategory::create([
            'name' => $validatedData['name'],
            'description' => $validatedData['description'],
        ]);

        return redirect()->route('ch-admin.blog.categories.edit', $category->id)->with('success', 'Category created successfully.');
    }

    public function edit($id)
    {
        $this->data['title'] = 'Edit Category';

        $this->data['category'] = BlogCategory::findOrFail($id);

        return view('admin.blog.categories.edit', $this->data);
    }

    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable',
        ]);

        $category = BlogCategory::findOrFail($id);

        $category->update([
            'name' => $validatedData['name'],
            'description' => $validatedData['description'],
        ]);

        return redirect()->route('ch-admin.blog.categories.edit', $category->id)->with('success', 'Category updated successfully.');
    }

    public function destroy(Request $request)
    {
        $deletePosts = $request->boolean('deletePosts');
        $singleDelete = $request->boolean('singleDelete');

        if ($singleDelete) {
            $categoryIds = (array) $request->categoryIds;
            $categoryId = $categoryIds[0];
            $category = BlogCategory::findOrFail($categoryId);

            if ($deletePosts) {
                if ($category->posts && $category->posts->isNotEmpty()) {
                    foreach ($category->posts as $post) {
                        $post->delete();
                    }
                }
                $category->delete();

                session()->flash('success', 'Category with its posts deleted successfully.');
            } else {
                $movingCategoryId = $request->movingCategoryId;

                $category->load('posts');

                foreach ($category->posts as $post) {
                    $post->categories()->updateExistingPivot($category->id, ['category_id' => $movingCategoryId]);
                }

                $category->delete();

                session()->flash('success', 'Category deleted and posts moved successfully.');
            }
        } else {
            $categories = BlogCategory::whereIn('id', $request->categoryIds)->with('posts')->get();

            if ($deletePosts) {

                foreach ($categories as $category) {
                    if ($category->posts && $category->posts->isNotEmpty()) {
                        foreach ($category->posts as $post) {
                            $post->delete();
                        }
                    }
                    $category->delete();
                }

                session()->flash('success', 'Selected categories with their posts deleted successfully.');
            } else {
                $movingCategoryId = $request->movingCategoryId;

                foreach ($categories as $category) {
                    $category->load('posts');

                    foreach ($category->posts as $post) {
                        $post->categories()->updateExistingPivot($category->id, ['category_id' => $movingCategoryId]);
                    }

                    $category->delete();
                }
                session()->flash('success', 'Selected categories deleted and posts moved successfully.');
            }
        }

        return response()->json(['success' => true,]);
    }
}
