<?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.';

    /**
     * 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',compact('title'));
    }

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Page::orderByDesc('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->title) {
            $query->where('pd.title', 'LIKE', '%'.$request->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= __('pages.new');
        return view( $this->viewDirectory.'form', compact('action', 'head') );
    }

    /**
     * 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 = __('pages.edit');
        $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 RedirectResponse|Redirector
     */
    public function update(PageRequest $request, Page $page) :RedirectResponse
    {
        // Update image if request has it
        $page->update($request->all());
        // Delete old description
        PageDescription::where('page_id', $page->id)->delete();

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

        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();
        foreach (languages() as $lang) {
            $data = [
                'title'=> $requestData['title_'.$lang->local],
                'page_title'=> $requestData['page_title_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                '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
    {
        $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 ($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')]);
        }
    }
}
