<?php

namespace App\Http\Controllers\Admin;

use App\Page;
use Exception;
use App\Language;
use App\PageDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\PageRequest;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class PageController extends Controller
{

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

    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= __('pages.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
    {
        $query = Page::orderBy('pages.id')
            ->join('page_descriptions AS pd', 'pages.id', 'pd.page_id')
            ->where('pd.language_id', currentLanguage()->id)
            ->select(['pd.title', 'pd.page_title', 'pages.*']);

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

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

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

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

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param PageRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(PageRequest $request) :RedirectResponse
    {
        $page = Page::create($request->all());
        // Insert Description
        $this->saveData( $request, $page->id );

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


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

        $query = PageDescription::where('page_id', $page->id)
            ->join('languages', 'languages.id', 'page_descriptions.language_id')
            ->select(['page_descriptions.*', 'languages.local']);

        $pageDescription= $query->get();

        foreach ($pageDescription as $row) {
            $page[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param PageRequest $request
     * @param Page $page
     * @return JsonResponse
     */
    public function update(PageRequest $request, Page $page) :JsonResponse
    {
        $data = $request->all();
        $local = getCurrentLocale();

        if ($page->id == 1 && $request->video){
            $data['meta'] = [
                'video' => $request->video
            ];
        }

        if ($request->{'properties_'.$local}){
            foreach (languages() as $language) {
                $data['meta']['titles'][$language->local] = $request->{'properties_'.$language->local};
            }
        }

        // Update image if request has it
        $page->update($data);

        // Delete old description
        PageDescription::where('page_id', $page->id)->delete();

        // Insert new description
        $this->saveData( $request, $page->id );

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

    /**
     * Handle Save form data
     *
     * @param PageRequest $request
     * @param int $page_id
     * @return void
     */

    private function saveData(PageRequest $request, int $page_id ):void
    {
        $requestData= $request->all();
        $languages= Language::where('status', 1)->cursor();

        foreach ($languages as $lang) {
            $data=[
                'page_title'=> $requestData['page_title_'.$lang->local] ?? null,
                'title'=> $requestData['title_'.$lang->local] ?? null,
                'title_2'=> $requestData['title_2_'.$lang->local] ?? null,
                'description'=> $requestData['description_'.$lang->local] ?? null,
                'description_2'=> $requestData['description_2_'.$lang->local] ?? null,
                'page_id'=> $page_id,
                'language_id'=> $lang->id,
            ];
            PageDescription::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
    {
        if (1 == $id) {
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }

        $page = Page::withTrashed()->find($id);
        if ($page) {
            if ($page->deleted_at) {
                $page->forceDelete();
            } else {
                $page->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 ( in_array( 1, $ids) ) {
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }

        if ($request->force) {
            Page::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Page::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
    {
        $page = Page::withTrashed()->find($id);

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