<?php

namespace App\Http\Controllers\Admin;

use App\Page;
use App\PageTranslation;
use App\PageGroup;
use App\PageGroupTranslation;
use App\Route;
use DB;
use App\Log;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;

class PageController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Page $page)
    {
        //
        $this->authorize('view', $page);

        $data = [];
        $data['page']  = $page;
        $data['pages'] = $page->with('ctranslation','group.ctranslation')->get();

        //dd($data['pages']);

        return view('admin.pages.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Page $page)
    {
        $this->authorize('create', $page);
        $data = [];
        $data['page']   = $page;
        $data['pgroups']   = PageGroupTranslation::where('lang',app()->getLocale())->pluck('page_gr_name','page_gr_id');
        $data['create'] = 1;
        return view('admin.pages.form', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, Page $page)
    {
        $this->authorize('create', $page);

        $rules = [
            'page_gr_id'            => 'required|integer|exists:page_groups,page_gr_id',
            'page_act'              => 'required|integer|in:1,0',
            'page_in_nav'           => 'required|integer|in:1,0',
        ];

        foreach(config('app.languages') as $lang) {

            $rules[$lang.'_page_name'] = 'required|string|min:3';
            $rules[$lang.'_page_text'] = 'required|string|min:50';
            $rules[$lang.'_page_desc'] = 'required|string|min:15';
            $rules[$lang.'_page_keyw'] = 'nullable|string|min:3';

            $rules[$lang.'_slug']          = ['required', 'string', 'min:3',
                Rule::unique('routes','slug')
                    ->where(function ($query) use ($lang) {
                        return $query
                            ->where('lang', $lang);
                    })
            ];
        }

        $this->validate($request,$rules);


        try{
            DB::beginTransaction();

            // Save page data
            // ---------------------------------

            $page = new Page();

            $page->page_gr_id   = $request->page_gr_id;
            $page->page_act     = $request->page_act;
            $page->page_in_nav  = $request->page_in_nav;

            $page->save();

            // Translations
            // ---------------------------------


            foreach(config('app.languages') as $lang){

                $pt = new PageTranslation();

                $pt->lang       = $lang;
                $pt->page_name  = $request->{$lang.'_page_name'};
                $pt->page_text  = $request->{$lang.'_page_text'};
                $pt->page_desc  = $request->{$lang.'_page_desc'};
                $pt->page_keyw  = $request->{$lang.'_page_keyw'};
                //$pt->page_slug  = $request->{$lang.'_slug'};

                $page->translations()->save($pt);

            }


            // Insert slug in routes
            // ---------------------------

            foreach(config('app.languages') as $lang) {

                $newroute = new Route();

                $newroute->object    = 'Page';
                $newroute->object_id = $page->page_id;
                $newroute->lang      = $lang;
                $newroute->slug      = $request->{$lang.'_slug'};

                $newroute->save();
            }

            // Create log record
            //--------------------------------------------

            $log = new Log();

            $log->object    = 'Page';
            $log->object_id = $page->page_id;
            $log->action    = 'create';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = NULL;

            $log->save();

            DB::commit();

            return redirect()->route('admin.page.index')->with('result', __('adminforms.pages.insert_controller_msg', ['name' => $page->ctranslation->page_name]));

        } catch (\Illuminate\Database\QueryException $e) {
            DB::rollBack();
            echo handle_error($e);
        } catch (\Exception $e) {
            DB::rollBack();
            echo handle_error($e);
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Page  $page
     * @return \Illuminate\Http\Response
     */
    public function show(Page $page)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Page  $page
     * @return \Illuminate\Http\Response
     */
    public function edit(Page $page)
    {
        $this->authorize('update', $page);

        $data = [];
        $data['page']     = $page;
        $data['pgroups']   = PageGroupTranslation::where('lang',app()->getLocale())->pluck('page_gr_name','page_gr_id');
        $data['create']   = 0;
        return view('admin.pages.form', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Page  $page
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Page $page)
    {
        $this->authorize('update', $page);

        $rules = [
            'page_gr_id'            => 'required|integer|exists:page_groups,page_gr_id',
            'page_act'              => 'required|integer|in:1,0',
            'page_in_nav'           => 'required|integer|in:1,0',
        ];

        foreach(config('app.languages') as $lang) {

            $rules[$lang.'_page_name'] = 'required|string|min:3';
            $rules[$lang.'_page_text'] = 'required|string|min:50';
            $rules[$lang.'_page_desc'] = 'required|string|min:15';
            $rules[$lang.'_page_keyw'] = 'nullable|string|min:3';

            $rules[$lang.'_slug']          = ['required', 'string', 'min:3',
                Rule::unique('routes','slug')
                    ->where(function ($query) use ($lang, $page) {
                        return $query
                            ->where('lang', $lang)
                            ->whereRaw('CONCAT(object,"",object_id) <> ? ', ['Page'.$page->page_id]);
                    })
            ];
        }

        $this->validate($request,$rules);


        try{
            DB::beginTransaction();

            // Save page data
            // ---------------------------------

            $page->page_gr_id   = $request->page_gr_id;
            $page->page_act     = $request->page_act;
            $page->page_in_nav  = $request->page_in_nav;

            $page->save();

            // Translations
            // ---------------------------------


            foreach(config('app.languages') as $lang){

                $pt = $page->translations()->where('lang', $lang)->first();

                if (!is_null($pt)){

                    $pt->page_name  = $request->{$lang.'_page_name'};
                    $pt->page_text  = $request->{$lang.'_page_text'};
                    $pt->page_desc  = $request->{$lang.'_page_desc'};
                    $pt->page_keyw  = $request->{$lang.'_page_keyw'};
                    //$pt->page_slug  = $request->{$lang.'_slug'};

                    $pt->save();

                } else {

                    $pt = new PageTranslation();

                    $pt->lang       = $lang;
                    $pt->page_name  = $request->{$lang.'_page_name'};
                    $pt->page_text  = $request->{$lang.'_page_text'};
                    $pt->page_desc  = $request->{$lang.'_page_desc'};
                    $pt->page_keyw  = $request->{$lang.'_page_keyw'};
                    //$pt->page_slug  = $request->{$lang.'_slug'};

                    $page->translations()->save($pt);

                }


            }


            // Update slug in routes
            // ---------------------------

            foreach(config('app.languages') as $lang) {

                $route = Route::where('object', '=', 'Page')->where('lang', '=', $lang)->where('object_id', '=', $page->page_id)->first();

                if ($route) {
                    $route->slug = $request->{$lang.'_slug'};
                    $route->save();
                } else {

                    $newroute = new Route();

                    $newroute->object    = 'Page';
                    $newroute->object_id = $page->page_id;
                    $newroute->lang      = $lang;
                    $newroute->slug      = $request->{$lang.'_slug'};

                    $newroute->save();

                }

            }


            // Create log record
            //--------------------------------------------

            $log = new Log();

            $log->object    = 'Page';
            $log->object_id = $page->page_id;
            $log->action    = 'update';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = NULL;

            $log->save();

            DB::commit();

            return redirect()->route('admin.page.index')->with('result', __('adminforms.pages.update_controller_msg', ['name' => $page->ctranslation->page_name]));

        } catch (\Illuminate\Database\QueryException $e) {
            DB::rollBack();
            echo handle_error($e);
        } catch (\Exception $e) {
            DB::rollBack();
            echo handle_error($e);
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Page  $page
     * @return \Illuminate\Http\Response
     */
    public function destroy(Page $page)
    {
        $this->authorize('delete', $page);

        $name = $page->page_name;
        $id   = $page->page_id;


        try{
            DB::beginTransaction();


            // Create log record
            //--------------------------------------------

            $log = new Log();

            $log->object    = 'Page';
            $log->object_id = $id;
            $log->action    = 'delete';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = 'Name: '.$name;

            $log->save();

            // Remove slug from routes
            // ------------------------------

            $routes = Route::where('object', '=', 'Page')->where('object_id', '=', $id)->get();
            if(!empty($routes)){
                foreach($routes as $route){
                    $route->destroy($route->id);
                }
            }


            // Delete Category group
            // ----------------------------------------------

            $page->destroy($page->page_id);

            DB::commit();

            return redirect()->route('admin.page.index')->with('result', __('adminforms.pages.delete_controller_msg', ['name' => $name]));

        } catch (\Illuminate\Database\QueryException $e) {
            DB::rollBack();
            echo handle_error($e);
        } catch (\Exception $e) {
            DB::rollBack();
            echo handle_error($e);
        }
    }
}
