<?php

namespace App\Http\Controllers\Admin;

use App\Models\Item;
use App\Models\ItemDescription;
use App\Models\Page;
use Exception;
use App\Models\Language;
use App\Models\PageDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\Admin\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::latest()
            ->join('page_descriptions AS pd', 'pages.id', 'pd.page_id')
            ->join('languages', 'languages.id', 'pd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->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->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', '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;
        }
        $items = Item::where('page_id',$page->id)->cursor();

        return view( $this->viewDirectory.'form', compact('page', 'action', 'head','items') );
    }

    /**
     * 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();
        Item::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] ?? null,
//                'slug'=> $requestData['slug_'.$lang->local],
//                'keywords'=> $requestData['keywords_'.$lang->local],
//                'meta_description'=> $requestData['meta_description_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local]?? null,
            ];
            PageDescription::create($data);
        }
        if (isset($request['items']))
        {
            foreach ($request['items'] as $row)
            {
                $item = Item::create([
                    'page_id'=>$page_id,
                ]);
                foreach (languages() as $lang)
                {
                    ItemDescription::create([
                        'item_id' => $item->id,
                        'language_id' => $lang->id,
                        'name' => $row['name_' . $lang->local],
                    ]);
                }
            }
        }
    }


    /**
     * 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')]);
        }
        return response()->json(['message'=> __('dashboard.saveDone')]);
    }
}
