<?php

namespace App\Http\Controllers;

use Arcanedev\Support\Validation\Rule;
use Illuminate\Support\Str;
use Rinvex\Categories\Models\Category;

class CategoriesController extends Controller
{
    public function store()
    {
        // for test purpose only
//        Category::create(
//            [
//                'name'=>[
//                    'en' => 'Dis',
//                    'ar'=> 'توزيع',
//                ],
//                'parent_id' => 1,
//            ]
//        );

        request()->validate([
            'en' => 'required|min:3|max:50',
            'ar' => 'required|min:3|max:50',

        ]);
        $cat=Category::whereSlug(Str::slug(request('en')))->first();
        if($cat!=null && $cat->verified){
            return back(303)->with(['error' => "Category already exist"]);
        }
        if($cat!=null){
            $category=$cat;
        }else{
            $category = Category::create(
                [
                    'name' => request('en'),
                    'parent_id' => request('parent_id'),
                    'children' => request('children'),
                ]
            );
        }


        $category->load('descendants');

        return redirect()->back()->with(['success' => 'success', 'return_data' => $category]);

    }

    public function index()
    {
        return Category::all()->where('verified', true);
    }

    public function update(Category $category)
    {
        $category->update([
            'name' => [
                'en' => request('en'),
                'ar' => request('ar'),
            ],
            'parent_id' => request('parent_id'),
            'children' => request('children'),
        ]);
        return back(303)->with(['success' => 'success']);
    }

    public function destroy(Category $category)
    {
        $category->delete();
        return back(303)->with(['success' => 'success']);
    }

    public function show(int $id)
    {
        return Category::find($id);
    }
}
