<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\SiteSliderRequest;
use App\SiteSlider;
use App\SiteSliderDescription;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class SiteSliderController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/siteSliders';
    /** View folder */
    private $viewDirectory = 'admin.site_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= __('siteSliders.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 = SiteSlider::orderByDesc('site_sliders.id')
            ->join('site_slider_descriptions AS sDesc', 'site_sliders.id', 'sDesc.site_slider_id')
            ->where('sDesc.language_id', $langId)
            ->select([
                'sDesc.title',
                'sDesc.description',
                'site_sliders.*'
            ]);

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

        if ($request->date_to) {
            $query->whereDate('site_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();
        }

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

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

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

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

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


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

        $query = SiteSliderDescription::where('site_slider_id', $siteSlider->id)
            ->join('languages', 'languages.id', 'site_slider_descriptions.language_id')
            ->select(['site_slider_descriptions.*', 'languages.local']);

        $siteSliderDescription= $query->get();

        foreach ($siteSliderDescription as $row) {
            $siteSlider[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param SiteSliderRequest $request
     * @param SiteSlider $siteSlider
     * @return JsonResponse
     */
    public function update(SiteSliderRequest $request, SiteSlider $siteSlider) :JsonResponse
    {

        $data = $request->all();
        $siteSlider->update($data);
        SiteSliderDescription::where('site_slider_id', $siteSlider->id)->delete();
        $this->saveData( $request, $siteSlider->id );

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

    /**
     * Handle Save form data
     *
     * @param SiteSliderRequest $request
     * @param int $site_slider_id
     * @return void
     */

    private function saveData(SiteSliderRequest $request, int $site_slider_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data = [
                'title'=> $requestData['title_'.$lang->local] ?? null,
                'button_title'=> $requestData['button_title_'.$lang->local] ?? null,
                'description'=> $requestData['description_'.$lang->local] ?? null,
                'site_slider_id'=> $site_slider_id,
                'language_id'=> $lang->id,
            ];
            SiteSliderDescription::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
    {
        $siteSlider = SiteSlider::withTrashed()->find($id);
        if ($siteSlider) {
            if ($siteSlider->deleted_at) {
                $siteSlider->forceDelete();
            } else {
                $siteSlider->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) {
            SiteSlider::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            SiteSlider::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
    {
        $siteSlider = SiteSlider::withTrashed()->find($id);

        if ($siteSlider){
            $siteSlider->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
    {
        $siteSlider = SiteSlider::whereIn('id', $request->ids)->onlyTrashed();
        if ($siteSlider){
            $siteSlider->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
