<?php

namespace App\Http\Controllers\Backend;

use App\DataTables\ProductManagement\Categories\CategoryDataTable;
use App\DataTables\ProductManagement\Categories\CategoryDataTableEditor;
use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\CategoryRequest;
use App\Models\ProductManagement\Category;
use App\Traits\ImageUploadTrait;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\File;

class CategoryController extends Controller{
    use ImageUploadTrait;


    public function __construct(){

        $this->middleware('permission:category-list')
            ->only(["index"]);

        $this->middleware('permission:category-show')
            ->only(["show"]);

        $this->middleware('permission:category-create')
            ->only(["store"]);

        $this->middleware('permission:category-update')
            ->only(['update',"edit"]);

        $this->middleware('permission:category-delete')
            ->only(['destroy',"removeImage"]);

    }

    public function indexV1(): View{

        $categories = Category::with('parent')
            ->withCount('products')
            ->when(request()->keyword != null, function ($query) {
                $query->search(request()->keyword);
            })
            ->when(request()->active != null, function ($query) {
                $query->whereStatus(request()->active);
            })
            ->orderBy(request()->sortBy ?? 'id', request()->orderBy ?? 'asc')
            ->paginate(request()->limitBy ?? 10);

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

    public function index(CategoryDataTable $dataTable){
        $title = __("Manage Categories");
        return $dataTable->render('backend.categories.index',compact("title"));
    }

    public function create(): View{
        $mainCategories = Category::whereNull('parent_id')->get(['id', 'name']);
        return view('backend.categories.create', compact('mainCategories'));
    }

    public function dtEdit(CategoryDataTableEditor $editor){
        return $editor->process(request());
    }

    public function store(CategoryRequest $request): RedirectResponse{
        $image = NULL;

      $category =   Category::create([
                        'name' => $request->name,
                        'parent_id' => $request->parent_id,
                        'active' => $request->active,
                       // 'cover' => $image
                    ]);


        if ($request->hasFile('cover')){
            $file = $request->file("cover");
            $options = ["resize" => ["width" => 500, "height" => null,]];
            $category->uploadFiles([$file],$options);
        }

        clear_cache();

        return redirect()->route('admin.categories.index')->with([
            'message' => action_message("create"),
            'alert-type' => 'success'
        ]);
    }

    public function show(Category $category): View{
        return view('backend.categories.show', compact('category'));
    }

    public function edit(Category $category): View{
        $mainCategories = Category::whereNull('parent_id')->get(['id', 'name']);
        return view('backend.categories.edit', compact('category', 'mainCategories'));
    }

    public function update(CategoryRequest $request, Category $category): RedirectResponse{

        $category->update([
            'name' => $request->name,
          //  'slug' => null,
            'parent_id' => $request->parent_id,
            'active' => $request->active,
        ]);

        if ($request->hasFile('cover')){
            $file = $request->file("cover");
            $options = ["resize" => ["width" => 500, "height" => null,]];
            $category->uploadFiles([$file],$options);
        }


        clear_cache();
        return redirect()->route('admin.categories.index')->with([
            'message' => action_message("update"),
            'alert-type' => 'success'
        ]);
    }

    public function destroy(Category $category): RedirectResponse{

        if ($category->cover) {
            if (File::exists('storage/assets/images/categories/'. $category->cover)) {
                unlink('storage/assets/images/categories/'. $category->cover);
            }
        }

        $category->delete();

        clear_cache();
        return redirect()->route('admin.categories.index')->with([
            'message' => action_message("delete"),
            'alert-type' => 'success'
        ]);

    }

    public function removeImage(Category $category): RedirectResponse{

        if (File::exists('storage/images/categories/'.$category->cover)) {
            unlink('storage/images/categories/'.$category->cover);
            $category->cover = null;
            $category->save();
        }

        $category->getFirstMedia($category->getMediaCollectionName())->delete();
        clear_cache();
        return back()->with([
            'message' => action_message("delete"),
            'alert-type' => 'success'
        ]);
    }
}
