<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\GalleryRequest;
use App\Gallery;
use App\GalleryDescription;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class GalleryController extends Controller
{

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

    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= __('galleries.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 = Gallery::orderByDesc('galleries.id')
            ->join('gallery_descriptions AS gDesc', 'galleries.id', 'gDesc.gallery_id')
            ->where('gDesc.language_id', $langId)
            ->select([
                'gDesc.title',
                'galleries.*'
            ]);

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

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

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


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

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

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

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

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

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


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

        $query = GalleryDescription::where('gallery_id', $gallery->id)
            ->join('languages', 'languages.id', 'gallery_descriptions.language_id')
            ->select(['gallery_descriptions.*', 'languages.local']);

        $galleryDescription= $query->get();

        foreach ($galleryDescription as $row) {
            $gallery[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param GalleryRequest $request
     * @param Gallery $gallery
     * @return JsonResponse
     */
    public function update(GalleryRequest $request, Gallery $gallery) :JsonResponse
    {

        $data = $request->all();
        $data['video_url'] = $request->video_url ? parseExternalVideoLink($request->video_url)['url'] : null;
        $gallery->update($data);
        GalleryDescription::where('gallery_id', $gallery->id)->delete();
        $this->saveData( $request, $gallery->id );

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

    /**
     * Handle Save form data
     *
     * @param GalleryRequest $request
     * @param int $gallery_id
     * @return void
     */

    private function saveData(GalleryRequest $request, int $gallery_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data = [
                'title'=> $requestData['title_'.$lang->local] ?? null,
                'gallery_id'=> $gallery_id,
                'language_id'=> $lang->id,
            ];
            GalleryDescription::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
    {
        $gallery = Gallery::withTrashed()->find($id);
        if ($gallery) {
            if ($gallery->deleted_at) {
                $gallery->forceDelete();
            } else {
                $gallery->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) {
            Gallery::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Gallery::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
    {
        $gallery = Gallery::withTrashed()->find($id);

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