<?php

namespace App\Http\Controllers\Admin;

use App\Position;
use App\PositionTranslation;
use App\Route;
use DB;
use App\Log;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;

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

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

        $data = [];
        $data['position']  = $position;
        $data['positions'] = $position::with('ctranslation')->get();

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Position $position)
    {
        $this->authorize('create', $position);
        $data = [];
        $data['position']   = $position;
        $data['create'] = 1;
        return view('admin.positions.form', $data);
    }

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

        $rules = [
            'pos_mainnav'           => 'required|integer|in:1,0',
        ];


        foreach(config('app.languages') as $lang) {
            $rules[$lang.'_pos_name']      = 'required|string|min:3';
            $rules[$lang.'_pos_sticker']   = 'required|string|min:3';
            $rules[$lang.'_pos_title']     = 'required|string|min:3';
            $rules[$lang.'_pos_metadesc']  = 'required|string|min:3';
            $rules[$lang.'_pos_keyw']      = 'required|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 position data
            // ---------------------------

            $position = new Position();

            $position->pos_mainnav  = $request->pos_mainnav;

            $position->save();


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

                $pt = new PositionTranslation();

                $pt->lang         = $lang;
                $pt->pos_name     = $request->{$lang.'_pos_name'};
                $pt->pos_sticker  = $request->{$lang.'_pos_sticker'};
                $pt->pos_title    = $request->{$lang.'_pos_title'};
                $pt->pos_metadesc = $request->{$lang.'_pos_metadesc'};
                $pt->pos_keyw     = $request->{$lang.'_pos_keyw'};
                //$pt->pos_slug     = $request->{$lang.'_slug'};

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

            }


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


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

                $route = new Route();

                $route->object    = 'Position';
                $route->object_id = $position->pos_id;
                $route->lang      = $lang.'_slug';
                $route->slug      = $request->{$lang.'_slug'};

                $route->save();

            }


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

            $log = new Log();

            $log->object    = 'Position';
            $log->object_id = $position->pos_id;
            $log->action    = 'create';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = NULL;

            $log->save();

            DB::commit();


            return redirect()->route('admin.position.index')->with('result', __('adminforms.positions.insert_controller_msg', ['name' => $position->ctranslation()->pos_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\Position  $position
     * @return \Illuminate\Http\Response
     */
    public function show(Position $position)
    {
        //
    }

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

        $data = [];
        $data['position']   = $position;
        $data['create'] = 0;
        return view('admin.positions.form', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Position  $position
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Position $position)
    {

        $this->authorize('update', $position);

        $rules = [
            'pos_mainnav'           => 'required|integer|in:1,0',
        ];


        foreach(config('app.languages') as $lang) {
            $rules[$lang.'_pos_name']      = 'required|string|min:3';
            $rules[$lang.'_pos_sticker']   = 'required|string|min:3';
            $rules[$lang.'_pos_title']     = 'required|string|min:3';
            $rules[$lang.'_pos_metadesc']  = 'required|string|min:3';
            $rules[$lang.'_pos_keyw']      = 'required|string|min:3';
            $rules[$lang.'_slug']          = ['required', 'string', 'min:3',
                                               Rule::unique('routes','slug')
                                                ->where(function ($query) use ($lang, $position) {
                                                return $query
                                                    ->where('lang', $lang)
                                                    ->whereRaw('CONCAT(object,"",object_id) <> ? ', ['Position'.$position->pos_id]);
                                                })
                                            ];
        }

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

        try{
            DB::beginTransaction();

            $position->pos_mainnav  = $request->pos_mainnav;

            $position->save();

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

                $pt = PositionTranslation::where('pos_id', $position->pos_id)->where('lang', $lang)->first();

                if(!is_null($pt)){

                    $pt->pos_name     = $request->{$lang.'_pos_name'};
                    $pt->pos_sticker  = $request->{$lang.'_pos_sticker'};
                    $pt->pos_title    = $request->{$lang.'_pos_title'};
                    $pt->pos_metadesc = $request->{$lang.'_pos_metadesc'};
                    $pt->pos_keyw     = $request->{$lang.'_pos_keyw'};
                    //$pt->pos_slug     = $request->{$lang.'_slug'};

                    $pt->save();

                } else {

                    $pt = new PositionTranslation();

                    $pt->lang         = $lang;
                    $pt->pos_name     = $request->{$lang.'_pos_name'};
                    $pt->pos_sticker  = $request->{$lang.'_pos_sticker'};
                    $pt->pos_title    = $request->{$lang.'_pos_title'};
                    $pt->pos_metadesc = $request->{$lang.'_pos_metadesc'};
                    $pt->pos_keyw     = $request->{$lang.'_pos_keyw'};
                    //$pt->pos_slug     = $request->{$lang.'_slug'};

                    $position->translations()->save($pt);
                }

            }


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

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

                $route = Route::where('object', '=', 'Position')->where('object_id', '=', $position->pos_id)->where('lang', $lang)->first();

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

                    $newroute = new Route();

                    $newroute->object    = 'Position';
                    $newroute->object_id = $position->pos_id;
                    $newroute->lang      = $lang;
                    $newroute->slug      = $request->{$lang.'_slug'};

                    $newroute->save();

                }
            }

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

            $log = new Log();

            $log->object    = 'Position';
            $log->object_id = $position->pos_id;
            $log->action    = 'update';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = NULL;

            $log->save();

            DB::commit();

            return redirect()->route('admin.position.index')->with('result', __('adminforms.positions.update_controller_msg', ['name' => $position->ctranslation->pos_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\Position  $position
     * @return \Illuminate\Http\Response
     */
    public function destroy(Position $position)
    {

        $this->authorize('delete', $position);

        $name = $position->pos_name;
        $id   = $position->pos_id;

        try{
            DB::beginTransaction();


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

            $log = new Log();

            $log->object    = 'Position';
            $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', '=', 'Position')->where('object_id', '=', $id)->get();
            if(!empty($routes)){
                foreach($routes as $route){
                    $route->destroy($route->id);
                }
            }


            // Delete Page
            // ----------------------------------------------

            $position->destroy($position->pos_id);

            DB::commit();

            return redirect()->route('admin.position.index')->with('result', __('adminforms.positions.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);
        }
    }
}
