<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\FlavorType;
use Illuminate\View\View;
use App\FlavorTypeDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\FlavorTypeRequest;

class FlavorTypeController extends Controller
{

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

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }

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

    /**
     * return data of the flavorTypes.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = FlavorType::orderByDesc('flavor_types.id')
        ->join('flavor_type_descriptions AS fDesc', 'flavor_types.id', 'fDesc.flavor_type_id')
        ->where('fDesc.language_id', currentLanguage()->id)
        ->select(['fDesc.name', 'flavor_types.*']);

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

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

        if ($request->name) {
            $query->where('fDesc.name', 'LIKE', '%'.$request->name.'%');
        }

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

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

    /**
     * Show the form for creating a new category.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('flavorTypes.store');
        $head = metaFields('flavorTypes', 'new', getCurrentLocale()) ?? __('flavorTypes.new');
        $title = $head;
//        dd(md5(Str::random(32)));
        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Store a newly created category in storage.
     * @param FlavorTypeRequest $request
     * @return JsonResponse
     */
    public function store(FlavorTypeRequest $request) :JsonResponse
    {
        $flavorType = FlavorType::create($request->all());

        // Insert Description
        $this->saveData( $request, $flavorType->id );
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('flavorTypes.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Show the form for editing the specified category.
     *
     * @param  FlavorType  $flavorType
     * @return View
     */
    public function edit(FlavorType $flavorType) :View
    {
        $action= route('flavorTypes.update', $flavorType->id);
        $head = metaFields('flavorTypes', 'edit', getCurrentLocale()) ?? __('flavorTypes.edit');
        $title = $head;
        $query = FlavorTypeDescription::where('flavor_type_id', $flavorType->id)
        ->join('languages', 'languages.id', 'flavor_type_descriptions.language_id')
        ->select(['flavor_type_descriptions.*', 'languages.local']);

        $flavorTypeDescription= $query->get();

        foreach ($flavorTypeDescription as $row) {
            $flavorType[$row->local]= $row;
        }

        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Update the specified category in storage.
     * @param FlavorTypeRequest $request
     * @param FlavorType $flavorType
     * @return JsonResponse
     */
    public function update(FlavorTypeRequest $request, FlavorType $flavorType) :JsonResponse
    {
        // Update the "updated_at" column only
        $flavorType->update($request->all());

        // Delete old description
        FlavorTypeDescription::where('flavor_type_id', $flavorType->id)->delete();

        // Insert new description
        $this->saveData( $request, $flavorType->id );
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('flavorTypes.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param FlavorTypeRequest $request
     * @param int $flavor_type_id
     * @return void
     */

     private function saveData(FlavorTypeRequest $request, int $flavor_type_id ) :void
     {

        $requestData= $request->all();

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

            FlavorTypeDescription::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
    {
        $flavorType= FlavorType::withTrashed()->find($id);
        if ($flavorType) {
            if ($flavorType->deleted_at) {
                $flavorType->forceDelete();
            } else {
                $flavorType->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

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

        if ($request->force) {
            FlavorType::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            FlavorType::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
    {
        $flavorType= FlavorType::withTrashed()->find($id);
        if ($flavorType) {
            $flavorType->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);

    }

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