<?php

namespace App\Http\Controllers\Admin;

use App\Models\Product;
use App\Models\Category;
use App\Services\SweetAlert;
use Illuminate\Http\Request;
use PhpParser\Node\Expr\New_;
use App\Events\Admin\NewCategory;
use App\Models\CategoryAttribute;
use App\Http\Controllers\Controller;
use App\Events\Admin\CategoryUpdated;
use App\Models\CategoryAttributeItem;
use App\Models\ProductAttributeValue;
use Illuminate\Support\Facades\Response;

class CategoryController extends Controller
{
    public function index(Request $request)
    {
        $categories = Category::with('children')->where('parent_id' , '0')->paginate(15);

        if ($request->ajax() || $request->ajax == true) {
            return Response::success(['categories' => $categories]);
        }

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

    public function create(Request $request)
    {
        $parentCategories = Category::pluck('name', 'id');

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'parent_id' => 'nullable',
            'commission' => 'required|numeric|min:0',
            'order_index' => 'nullable|integer',
            'image' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('categories', 'public_upload');
        }

        $category = Category::create($data);

        event(new NewCategory);
        if ($request->ajax() || $request->ajax == true) {
            return Response::success(['category' => $category]);
        }

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

    public function show(Request $request, Category $category)
    {
        if ($request->ajax() || $request->ajax == true) {
            return Response::success(['category' => $category]);
        }

        return view('pages.admin.categories.show', compact('category'));
    }

    public function edit(Request $request, Category $category)
    {
        $parentCategories = Category::where('id', '!=', $category->id)
            ->pluck('name', 'id');

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

    public function update(Request $request, Category $category)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'parent_id' => 'nullable',
            'commission' => 'required|numeric|min:0',
            'order_index' => 'nullable|integer',
            'image' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('categories', 'public_upload');
        }

        $category->update($data);

        event(new CategoryUpdated);

        if ($request->ajax() || $request->ajax == true) {
            return Response::success(['category' => $category]);
        }

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

    public function destroy(Request $request, $id)
    {
        $categories = Category::find($id);
        if ($categories == null) {
            return back()->with('sweetalert', SweetAlert::error(__('not found'), __('The operation encountered an error ')));
        }

        // check if this advertise type has child
        if (Category::where('parent_id', $categories->id)->exists()) {
            return back()->with('sweetalert', SweetAlert::error(__('Error'), __('This advertise type has child, please delete them first')));
        }

        // set advertise_type_id to NULL as to show that these advertises are now uncategorized
        Product::where('category_id', $categories->id)->delete();
        Product::withTrashed()->where('category_id', $categories->id)->update(['category_id' => null]);

        // now we should clear all the attributes of this advertise type and it's items

        $attributeIds = $categories->attributes()->pluck('id')->toArray();
        $attributeItemIds = CategoryAttributeItem::whereIn('category_attribute_id', $attributeIds)->get()->pluck('id')->toArray();
        $attributeValuesIds = ProductAttributeValue::whereIn('category_attribute_id', $attributeIds)->get()->pluck('id')->toArray();

        ProductAttributeValue::whereIn('category_attribute_id', $attributeIds)->delete();
        CategoryAttributeItem::whereIn('category_attribute_id', $attributeIds)->delete();
        CategoryAttribute::whereIn('id', $attributeIds)->delete();

        Category::where('id', $categories->id)->delete();

        return back()->with('sweetalert', SweetAlert::success(__('success'), __('The operation was successful')));
    }
}
