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

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Page::orderBy('pages.id', 'DESC')
            ->join('page_descriptions AS pd', 'pages.id', 'pd.page_id')
            ->join('languages', 'languages.id', 'pd.language_id')
            ->where('pd.language_id', currentLanguage()->id)
            ->select(['pd.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->name) {
            $query->where('pd.title', 'LIKE', '%'.$request->name.'%');
        }

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

        $pages= $query->cursor();

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create()
    {
        return redirect()->route('pages.index');
//        $action= route('pages.store');
//        $head = metaFields('pages', 'add_new', getCurrentLocale()) ?? __('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 = metaFields('pages', 'edit', getCurrentLocale()) ?? __('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', compact('page', 'action', 'head') );
    }

    /**
     * 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(['image' => $request->image??null]);

        // 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();
        $languages= Language::where('status', 1)->cursor();

        foreach ($languages as $lang) {
            $data=[
                'page_id'=> $page_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
                'slug'=> $requestData['slug_'.$lang->local],
                'keywords'=> $requestData['keywords_'.$lang->local],
                'meta_description'=> $requestData['meta_description_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
            ];
            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')]);
        }
    }
}
