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

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', '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.why_us_title',
                'pd.about_us_overview_title',
                'pd.about_us_social_responsibility_title',
                'pd.about_us_company_strategy_title',
                'pd.vision_title',
                'pd.culture_values_title',
                'pd.performance_development_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', get_defined_vars());
    }

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

        foreach ($languages as $lang) {
            $data=[
                'why_us_title'=> $requestData['why_us_title_'.$lang->local] ?? null,
                'why_us_experience_years_title'=> $requestData['why_us_experience_years_title_'.$lang->local] ?? null,
                'about_us_overview_title'=> $requestData['about_us_overview_title_'.$lang->local] ?? null,
                'about_us_social_responsibility_title'=> $requestData['about_us_social_responsibility_title_'.$lang->local] ?? null,
                'about_us_company_strategy_title'=> $requestData['about_us_company_strategy_title_'.$lang->local] ?? null,
                'vision_title'=> $requestData['vision_title_'.$lang->local] ?? null,
                'message_title'=> $requestData['message_title_'.$lang->local] ?? null,
                'values_title'=> $requestData['values_title_'.$lang->local] ?? null,
                'culture_values_title'=> $requestData['culture_values_title_'.$lang->local] ?? null,
                'performance_development_title'=> $requestData['performance_development_title_'.$lang->local] ?? null,
                'why_us_description'=> $requestData['why_us_description_'.$lang->local] ?? null,
                'about_us_overview_description'=> $requestData['about_us_overview_description_'.$lang->local] ?? null,
                'about_us_social_responsibility_description'=> $requestData['about_us_social_responsibility_description_'.$lang->local] ?? null,
                'about_us_company_strategy_description'=> $requestData['about_us_company_strategy_description_'.$lang->local] ?? null,
                'vision_description'=> $requestData['vision_description_'.$lang->local] ?? null,
                'message_description'=> $requestData['message_description_'.$lang->local] ?? null,
                'values_description'=> $requestData['values_description_'.$lang->local] ?? null,
                'culture_values_description'=> $requestData['culture_values_description_'.$lang->local] ?? null,
                'performance_development_description'=> $requestData['performance_development_description_'.$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')]);
        }
    }
}
