<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\SliderRequest;
use App\Slider;
use App\SliderDescription;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\ArticleRequest;

class SliderController extends Controller
{

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

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

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

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $langId = currentLanguage()->id;
        $query = Slider::orderByDesc('sliders.id')
            ->join('slider_descriptions AS sDesc', 'sliders.id', 'sDesc.slider_id')
            ->where('sDesc.language_id', $langId)
            ->select([
                'sDesc.title',
                'sDesc.description',
                'sliders.*'
            ]);

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

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

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

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


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

        $sliders= $query->paginate(100);

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param SliderRequest $request
     * @return JsonResponse
     */
    public function store(SliderRequest $request) :JsonResponse
    {
        $data = $request->all();
        $slider = Slider::create($data);
        $this->saveData($request, $slider->id);
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('sliders.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


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

        $query = SliderDescription::where('slider_id', $slider->id)
            ->join('languages', 'languages.id', 'slider_descriptions.language_id')
            ->select(['slider_descriptions.*', 'languages.local']);

        $sliderDescription= $query->get();

        foreach ($sliderDescription as $row) {
            $slider[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param SliderRequest $request
     * @param Slider $slider
     * @return JsonResponse
     */
    public function update(SliderRequest $request, Slider $slider) :JsonResponse
    {

        $data = $request->all();
        $slider->update($data);
        SliderDescription::where('slider_id', $slider->id)->delete();
        $this->saveData( $request, $slider->id );

        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('sliders.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param ArticleRequest $request
     * @param int $slider_id
     * @return void
     */

    private function saveData(SliderRequest $request, int $slider_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data = [
                'title'=> $requestData['title_'.$lang->local] ?? null,
                'description'=> $requestData['description_'.$lang->local] ?? null,
                'slider_id'=> $slider_id,
                'language_id'=> $lang->id,
            ];
            SliderDescription::create($data);
        }
    }


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

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Slider::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Slider::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
    {
        $slider = Slider::withTrashed()->find($id);

        if ($slider){
            $slider->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

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