<?php

namespace App\Http\Controllers\Admin;


/** Ajax Request */
// use App\Http\Resources\CategoryResource;


use Exception;
use App\PackageCategory;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\PackageCategoryDescription;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\PackageCategoryRequest;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class PackageCategoryController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/packageCategories';
    /** View folder */
    private $viewDirectory = 'admin.package_categories.';

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

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

        if ($request->date_from) {
            $query->whereDate('package_categories.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('package_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();
        }
        $packageCategories= $query->paginate(100);

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

    /**
     * Show the form for creating a new package category.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('packageCategories.store');
        $head = metaFields('packageCategories', 'add_new', getCurrentLocale()) ?? __('packageCategories.new');

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

    /**
     * Store a newly created package category in storage.
     *
     * @param PackageCategoryRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(PackageCategoryRequest $request) :RedirectResponse
    {
        // dd($request->all());
        $category = PackageCategory::create();

        // Insert package category Description
        $this->saveData( $request, $category->id );

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

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

        $query = PackageCategoryDescription::where('package_category_id', $packageCategory->id)
        ->join('languages', 'languages.id', 'package_category_descriptions.language_id')
        ->select(['package_category_descriptions.*', 'languages.local']);

        $packageCategoryDescription= $query->get();

        foreach ($packageCategoryDescription as $row) {
            $packageCategory[$row->local]= $row;
        }
        return view( $this->viewDirectory.'form', compact('packageCategory', 'action', 'head') );
    }

    /**
     * Update the specified package category in storage.
     *
     * @param PackageCategoryRequest $request
     * @param PackageCategory $packageCategory
     * @return RedirectResponse|Redirector
     */
    public function update(PackageCategoryRequest $request, PackageCategory $packageCategory) :RedirectResponse
    {

        $packageCategory->update();

        // Delete old package category description
        PackageCategoryDescription::where('package_category_id', $packageCategory->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param PackageCategoryRequest $request
     * @param int $package_category_id
     * @return void
     */

     private function saveData(PackageCategoryRequest $request, int $package_category_id ) :void
     {
        $requestData= $request->all();

        foreach (languages() as $lang) {
            $data=[
                'package_category_id'=> $package_category_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                'slug'=> $requestData['slug_'.$lang->local],
                'keywords'=> $requestData['keywords_'.$lang->local],
                'meta_description'=> $requestData['meta_description_'.$lang->local],
            ];

            PackageCategoryDescription::create($data);
        }

     }

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

    /**
     * Remove several package categories by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            PackageCategory::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            PackageCategory::whereIn('id', $ids)->delete();
        }

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

    /**
     * Restore the specified package category from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $packageCategory= PackageCategory::withTrashed()->find($id);
        if ($packageCategory) {
            $packageCategory->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;
        PackageCategory::whereIn('id', $ids)->onlyTrashed()->restore();
        return response()->json(['message'=> __('dashboard.saveDone')]);
    }
}
