<?php

namespace App\Http\Controllers\Api\V1\Backend\Catalog;

use App\Http\Controllers\Api\V1\Backend\ResponseController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Backend\Catalog\Category;
use App\Models\Backend\Catalog\CategoryDescription;
use App\Models\Backend\Catalog\CategoryFilter;
use App\Models\Backend\Catalog\CategoryPath;
use App\Models\Backend\Catalog\CategoryToStore;
use App\Models\Backend\Catalog\CategoryToLayout;
use App\Models\Backend\Catalog\UrlAlias;
use Illuminate\Support\Facades\Validator;
use Exception;


class CategoryController extends ResponseController
{
    function buildCategoryTree($elements, $parentId = 0)
    {
        $branch = [];
        foreach ($elements as $element) {
            if ((int) $element['parent_id'] === (int) $parentId) {
                $children = $this->buildCategoryTree($elements, $element['id']);
                if ($children) {
                    // dd($children);
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }
        return $branch;
    }

    public function index()
    {

        try {
            $categories = Category::with('description')
                ->get();

            $categoryArray = $categories->map(function ($cat) {
                return [
                    'id' => $cat->category_id,
                    'text' => optional($cat->description->first())->name ?? '',
                    'parent_id' => $cat->parent_id,
                ];
            })->toArray();

            $categoryTree = $this->buildCategoryTree($categoryArray);

            return $this->sendResponse($categoryTree,'All categories fetched successfully!!');
        }
        catch(Exception $err) {
            return $this->sendError(errorMessages:$err->getMessage(), code:500);
        }
        // dd('last', $categoryTree);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function store(Request $request)
    {
        // dd($request->all());
            try{
            $validator = Validator::make($request->all(), [
                'name'              => 'required|string|max:255',
                'description'       => 'nullable|string',
                'meta_title'        => 'required|string|max:255',
                'meta_description'  => 'nullable|string|max:255',
                'meta_keyword'      => 'nullable|string|max:255',
                'parent_id'         => 'nullable|integer',
                'filter_id'         => 'nullable|array',
                'image'             => 'nullable|string|max:255',
                'sort_order'        => 'nullable|integer',
                'status'            => 'required|boolean',
            ]);

            if($validator->fails()) {
                return $this->sendError('Validation fails !', $validator->errors(), 422);
            }


            $category = Category::create([
                'image'          => $request->image ? $request->image : 'cache/no_image-100x100.png',
                'parent_id'      => $request->parent_id ?? 0,
                'sort_order'     => $request->sort_order ?? 0,
                'status'         => $request->status,
                'date_added'     =>NOW(),
                'date_modified'  =>NOW(),

                'top'         => 1,
                'home_page'   => 1,
                'column'      => 1,
            ]);

            CategoryDescription::create([
                'category_id'       => $category->category_id,
                'name'              => $request->name,
                'description'       => $request->description ?? '',
                'meta_title'        => $request->meta_title,
                'meta_description'  => $request->meta_description ?? '',
                'meta_keyword'      => $request->meta_keyword ?? '',
                'language_id'       => 1,
            ]);

            // if ($request->has('filter_id') && is_array($request->filter_id)) {
            //     foreach ($request->filter_id as $filterId) {
            //         CategoryFilter::create([
            //             'category_id' => $category->category_id,
            //             'filter_id'   => $filterId,
            //         ]);
            //     }
            // }

            $level = 0;
            $paths = CategoryPath::where('category_id', $category->parent_id)
                ->orderBy('level', 'asc')
                ->get();

            foreach ($paths as $path) {
                CategoryPath::create([
                    'category_id' => $category->category_id,
                    'path_id'     => $path->path_id,
                    'level'       => $level++,
                ]);
            }

            CategoryPath::create([
                'category_id' => $category->category_id,
                'path_id'     => $category->category_id,
                'level'       => $level,
            ]);

            CategoryToStore::create([
                'category_id'  => $category->category_id,
                'store_id'     => 0,
            ]);
            
            CategoryToLayout::create([
                'category_id'  => $category->category_id,
                'store_id'     => 0,
                'layout_id'    => 0,
            ]);
            if ($request->has('seo_keyword')) {
                UrlAlias::create([
                    'query'     => 'category_id='.$category->category_id,
                    'keyword'    => $request->seo_keyword,
                ]);
            }
            $data = ["category_id" => $category->category_id];
            return $this->sendResponse($data,'Category saved successfully!!');
        }
        catch(Exception $err) {
            return $this->sendError(errorMessages:$err->getMessage(), code:500);
        }

    }
    public function show(string $category_id)
    {
        try{
            $category = Category::with([
                'description',
                'paths.pathName',
                'categoryToLayout',
            ])
            ->where('category_id', $category_id)
            ->first();

            // dd($category);

            if (!$category) {
                abort(404, 'Category not found');
            }

            $seo_keyword = UrlAlias::where("query","category_id=".$category->category_id)->first();
            // dd($category->categoryToLayout);


            $data = [
                'id'         => $category->category_id,
                'name'       => $category->description[0]->name,
                'description'       => $category->description[0]->description,
                'meta_title'       => $category->description[0]->meta_title,
                'meta_description'       => $category->description[0]->meta_description,
                'meta_keyword'       => $category->description[0]->meta_keyword,
                'image'      => 'image/'.$category->image,
                'parent_id'  => $category->parent_id,
                'status'     => $category->status,
                'sort_order' => $category->sort_order,
                'keyword'    => $seo_keyword ? $seo_keyword->keyword : '',

                // 'store'    => $seo_keyword ? $seo_keyword : '',
                'store'       => $category->categoryToLayout->store_id,
            ];

            // dd($data);
            return $this->sendResponse($data,'Category fetch successfully!!');
        }
        catch(Exception $err) {
            return $this->sendError(errorMessages:$err->getMessage(), code:500);
        }
    }
    public function update(Request $request, string $category_id)
    {
        try{
            // dd($request->all());
            $validator = Validator::make($request->all(), [
                'name'              => 'required|string|max:255',
                'description'       => 'nullable|string',
                'meta_title'        => 'required|string|max:255',
                'meta_description'  => 'nullable|string|max:255',
                'meta_keyword'      => 'nullable|string|max:255',
                'parent_id'         => 'nullable|integer',
                'filter_id'         => 'nullable|array',
                'image'             => 'nullable|string|max:255',
                'sort_order'        => 'nullable|integer',
                'status'            => 'required|boolean',
            ]);

            if($validator->fails()) {
                return $this->sendError('Validation fails !', $validator->errors(), 422);
            }

            $category = Category::findOrFail($category_id);

            $category->update([
                'image'          => $request->image ?? 'cache/no_image-100x100.png',
                'parent_id'      => $request->parent_id ?? 0,
                'sort_order'     => $request->sort_order ?? 0,
                'status'         => $request->status,
                'date_modified'  => NOW(),

                // 'top'            => 1,
                // 'home_page'      => 1,
                // 'column'         => 1,
            ]);

            // dd($category->category_id);

            CategoryDescription::updateOrCreate(
                ['category_id' => $category->category_id],
                [
                    'name'              => $request->name,
                    'description'       => $request->description ?? '',
                    'meta_title'        => $request->meta_title,
                    'meta_description'  => $request->meta_description ?? '',
                    'meta_keyword'      => $request->meta_keyword ?? '',
                ]
            );

            // if ($request->has('filter_id') && is_array($request->filter_id)) {
            //     foreach ($request->filter_id as $filterId) {
            //         CategoryFilter::updateOrCreate(
            //             ['category_id' => $category->category_id],
            //             ['filter_id'   => $filterId,
            //         ]);
            //     }
            // }

            
            CategoryPath::where('category_id', $category->category_id)->delete();

            $level = 0;
            $paths = CategoryPath::where('category_id', $category->parent_id)
                ->orderBy('level', 'asc')
                ->get();

            foreach ($paths as $path) {
                CategoryPath::create([
                    'category_id' => $category->category_id,
                    'path_id'     => $path->path_id,
                    'level'       => $level++,
                ]);
            }

            CategoryPath::create([
                'category_id' => $category->category_id,
                'path_id'     => $category->category_id,
                'level'       => $level,
            ]);        

            // CategoryToStore::updateOrCreate(
            //     ['category_id' => $category->category_id],
            //     ['store_id'     => 0,
            // ]);
            
            // CategoryToLayout::updateOrCreate(
            //     ['category_id' => $category->category_id],
            //     ['store_id'     => 0,
            //     'layout_id'    => 0,
            // ]);

            if ($request->has('seo_keyword')) {
                // dd('category_id='.$category->category_id);
                UrlAlias::where('query' , 'category_id='.$category->category_id)
                ->update([
                'keyword'    => $request->seo_keyword,
                ]);
            }
            $data = ["category_id" => $category->category_id];
            return $this->sendResponse($data,'Category Updated successfully!!');
        }
        catch(Exception $err) {
            return $this->sendError(errorMessages:$err->getMessage(), code:500);
        }
    }
}
