<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use App\Models\Attribute;
use App\Models\CategoryAttribute;
use Exception;
use App\Models\Category;
use Illuminate\View\View;
use App\Services\Response\ResponseService;
use App\Models\CategoryDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CategoryRequest; // for Validation
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class CategoryController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/categories';
    /** View folder */
    private $viewDirectory = 'admin.categories.';
    private $ajax = 'admin.ajax.';

    /**
     * Display a listing of the categories.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('categories.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the categories.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Category::latest()
            ->join('category_descriptions AS cd', 'categories.id', 'cd.category_id')
            ->join('languages', 'languages.id', 'cd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['cd.name', 'categories.*']);

        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 ($request->name) {
            $query->where('cd.name', 'LIKE', '%'.$request->name.'%');
        }

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

        return view($this->viewDirectory.'grid',compact('categories'));
    }

    /**
     * Show the form for creating a new category.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('categories.store');
        $head = metaFields('categories', 'add_new', getCurrentLocale()) ?? __('categories.new');
        $categories = Category::withDescription()->where('categories.category_id',null)->cursor();
        $attributes = Attribute::withDescription()->cursor();
        $attribute_ids = [];
        return view( $this->viewDirectory.'form', compact('action', 'head','categories','attributes','attribute_ids') );
    }

    /**
     * Store a newly created category in storage.
     * @param CategoryRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(CategoryRequest $request)
    {
        $category = Category::create($request->all());
        $category->attributes()->attach($request->attribute_ids);
        // Insert Description
        $this->saveData( $request, $category->id );

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }

    /**
     * Show the form for editing the specified category.
     *
     * @param  Category  $category
     * @return View
     */
    public function edit(Category $category) :View
    {
        $action= route('categories.update', $category->id);
        $head = metaFields('categories', 'edit', getCurrentLocale()) ?? __('categories.edit');

        $query = CategoryDescription::where('category_id', $category->id)
            ->join('languages', 'languages.id', 'category_descriptions.language_id')
            ->select(['category_descriptions.*', 'languages.local']);

        $categoryDescription= $query->get();

        foreach ($categoryDescription as $row) {
            $category[$row->local]= $row;
        }
        $categories = Category::withDescription()->where('categories.category_id',null)->cursor();
        $attributes = Attribute::withDescription()->cursor();
        if($category->main_id)
        {
            $subAttributes = Attribute::withDescription()->where('attributes.id','!=',$category->main_id)->cursor();
        }
        else
        {
            $subAttributes = [];
        }
        $attribute_ids = CategoryAttribute::where('category_id',$category->id)->pluck('attribute_id')->toArray();
        return view( $this->viewDirectory.'form', compact('category', 'action', 'head','categories','attributes','attribute_ids','subAttributes') );
    }
    
    public function subAttr(Request $request)
    {
        $subAttributes = Attribute::withDescription()->where('attributes.id','!=',$request->main_id)->cursor();
        return view( $this->ajax.'subAttributes', compact('subAttributes') );
    }

    /**
     * Update the specified category in storage.
     * @param CategoryRequest $request
     * @param Category $category
     * @return RedirectResponse|Redirector
     */
    public function update(CategoryRequest $request, Category $category) 
    {
        // Update the "updated_at" column only
        $category->update($request->all());
        $category->attributes()->sync($request->attribute_ids);

        // Delete old description
        CategoryDescription::where('category_id', $category->id)->delete();

        // Insert new description
        $this->saveData( $request, $category->id );

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }

    /**
     * Handle Save form data
     *
     * @param CategoryRequest $request
     * @param int $category_id
     * @return void
     */

    private function saveData(CategoryRequest $request, int $category_id ) :void
    {

        $requestData= $request->all();

        foreach (languages() as $lang) {
            $data=[
                'category_id'=> $category_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
            ];

            CategoryDescription::create($data);
        }

    }

    /**
     * Remove the specified category from storage.
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $category= Category::withTrashed()->find($id);
        if ($category) {
            if ($category->deleted_at) {
                $category->forceDelete();
            } else {
                $category->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several categories by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;

        if ($request->force) {
            Category::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Category::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

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

    }

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