<?php

namespace Modules\Category\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Category\Interfaces\CategoryRepositoryInterface;
use Modules\Category\Models\Category;
use Modules\Category\Models\CategoryDescription;

class CategoryRepository implements CategoryRepositoryInterface
{
    public function get(Request $request)
    {
        $query = Category::orderBy('id', 'DESC')
            ->join('category_descriptions AS sd', 'categories.id', 'sd.category_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'categories.*']);
        if($request->category_id)
        {
            if ($request->category_id == 'main')
            {
                $query->where('categories.category_id',null);
            }
            elseif($request->category_id == 'sub')
            {
                $query->where('categories.category_id','!=',null);
            }
            else
            {
                $query->where('categories.category_id',$request->category_id);
            }
        }
        if ($request->not_id)
        {
            $query->where('categories.id','!=',$request->not_id);
        }
        if ($request->title) {
            $query->where('sd.title', 'LIKE', '%'.$request->title.'%');
        }
        if ($request->date_from) {
            $query->whereDate('categories.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('categories.created_at', '<=', $request->date_to);
        }


        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        if ($request->paginate ?? null) {
            $categories= $query->paginate(50);
        }else{
            $categories=$query->cursor();
        }

        return $categories;
    }

    public function getItem(Category $category)
    {
        $query = CategoryDescription::where('category_descriptions.category_id', $category->id)
            ->join('languages', 'languages.id', 'category_descriptions.language_id')
            ->join('categories', 'categories.id', 'category_descriptions.category_id')
            ->select(['categories.*','category_descriptions.title', 'languages.local']);

        $categoryDescription= $query->get();
        foreach ($categoryDescription as $key=>$row) {
            if ($row->local == getCurrentLocale())
            {
                $category = $row;
            }
            $category[$row->local] = $row;
        }
        return $category ;
    }

    //
    public function save(Request $request, ?Category $category): Category
    {
        $data= $request->all();
        unset($data['id']);// for security reasons
        if (!$category) {
            $category = Category::create($data);
        } else {
            $category->update($data);
            CategoryDescription::where('category_id', $category->id)->delete();
        }
        $this->saveData( $request, $category->id );
        return $category;
    }

    private function saveData(Request $request, int $category_id ) :void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'category_id'=> $category_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
            ];

            CategoryDescription::create($data);
        }
    }
    /**
     * Remove the specified client from storage.
     * @param Request $request
     * @param int $id
     * @return array
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :array
    {
        $category= Category::withTrashed()->find($id);
        if ($category) {
            if (is_null($category->category_id) && count($category->sub) > 0)
            {
                return [ ['message'=> __('categories.has_sub_categories')], 400];
            }
            if ($category->category_id && count($category->stores) > 0)
            {
                return [ ['message'=> __('categories.has_stores')], 400];
            }
            if ($category->deleted_at) {
                $category->forceDelete();
            } else {
                $category->delete();
            }
            return [ ['message'=> __('dashboard.deletedDone')]];
        } else{
            return [ ['message'=> __('dashboard.noResult')], 400];
        }
    }

    /**
     * Remove several clients by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function destroyAll(Request $request) :array
    {
        $ids= $request->ids;
        $categories = Category::whereIn('id', $ids)->cursor();
        foreach($categories as $category)
        {
            if (is_null($category->category_id) && count($category->sub) > 0)
            {
                return [ ['message'=> __('categories.has_sub_categories')], 400];
            }
            if ($category->category_id && count($category->stores) > 0)
            {
                return [ ['message'=> __('categories.has_stores')], 400];
            }
        }
        $query= Category::whereIn('id', $ids);
        if ($request->force) {
            $deleted= $query->onlyTrashed()->forceDelete();
        } else {
            $deleted= $query->delete();
        }
        if($deleted){
            return [['message'=> __('dashboard.deletedDone')]];
        }
        return [ ['message'=> __('dashboard.noResult')], 400];
    }

    /**
     * Restore the specified client from storage.
     *
     * @param Request $request
     * @param int $id
     * @return array
     */
    public function restore(Request $request, int $id) :array
    {
        $category= Category::withTrashed()->find($id);
        if ($category) {
            $category->restore();
            return [['message'=> __('dashboard.saveDone')]];
        }
        return [['message'=> __('dashboard.noResult')], 400];

    }

    /**
     * Restore several clients by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function restoreAll(Request $request) :array
    {
        $ids= $request->ids;
        Category::whereIn('id', $ids)->onlyTrashed()->restore();
        return [['message'=> __('dashboard.saveDone')]];
    }

    public function addVisit(Category $category)
    {
        $category->update(['visits'=>($category->visits + 1)]);
    }

}
