<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Category;
use App\Log;
use Illuminate\View\View;
use App\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\CategoryRequest; // for Validation
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class CategoryController extends Controller
{

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

    /**
     * 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::orderBy('num','ASC')
        ->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= __('categories.new');
        return view( $this->viewDirectory.'form', compact('action', 'head') );
    }

    /**
     * Store a newly created category in storage.
     * @param CategoryRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(CategoryRequest $request) :RedirectResponse
    {
       
        $max = Category::max('num');
        $request->merge(['num'=>$max+1]);
        $category = Category::create($request->all());
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاقسام الرئيسية','action'=>'اضافة','product_id'=>$category->id]);
       
        // Insert Description
        $this->saveData( $request, $category->id );

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * 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 = __('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;
        }

        return view( $this->viewDirectory.'form', compact('category', 'action','head') );
    }

    /**
     * Update the specified category in storage.
     * @param CategoryRequest $request
     * @param Category $category
     * @return RedirectResponse|Redirector
     */
    public function update(CategoryRequest $request, Category $category) :RedirectResponse
    {
        // Update the "updated_at" column only
        $category->update($request->all());
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاقسام الرئيسية','action'=>'تعديل','product_id'=>$category->id]);
       

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

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

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * 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);
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاقسام الرئيسية','action'=>'حذف']);
        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;
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاقسام الرئيسية','action'=>'حذف']);

        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);
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاقسام الرئيسية','action'=>'استرجاع']);
        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;
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاقسام الرئيسية','action'=>'استرجاع']);
        Category::whereIn('id', $ids)->onlyTrashed()->restore();
        return response()->json(['message'=> __('dashboard.saveDone')]);
    }
}
