<?php

namespace App\Http\Controllers\Admin;

use App\CategoryGroup;
use App\CategoryGroupTranslation;
use App\CategoryTranslation;
use App\Route;
use DB;
use App\Log;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;

class CategoryGroupController extends Controller
{

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

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

        $data = [];
        $data['group']  = $categorygroup;
        $data['groups'] = $categorygroup::with('ctranslation')->get();

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

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


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

        $rules = [
            'cg_img'   => 'required|string|min:3',
            'cg_icon'  => 'nullable|string|min:3',
            'cg_feat'  => 'in:0,1',
        ];

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

            $rules[$lang.'_cg_name']  = 'required|string|min:3';
            $rules[$lang.'_cg_title'] = 'nullable|string|min:3';

            $rules[$lang.'_cg_desc'] = 'nullable|string|min:3';
            $rules[$lang.'_cg_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();

            // Create category group data
            //--------------------------------

            $categorygroup = new CategoryGroup();

            $categorygroup->cg_img   = $request->cg_img;
            $categorygroup->cg_icon  = $request->cg_icon;
            $categorygroup->cg_feat  = $request->cg_feat;
            $categorygroup->cg_ord   = 999;

            $categorygroup->save();




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

                $gt = new CategoryGroupTranslation();

                $gt->cgt_lang = $lang;
                $gt->cg_name  = $request->{$lang.'_cg_name'};
                //$gt->cg_slug  = $request->{$lang.'_slug'};
                $gt->cg_title = $request->{$lang.'_cg_title'};
                $gt->cg_desc  = $request->{$lang.'_cg_desc'};
                $gt->cg_keyw  = $request->{$lang.'_cg_keyw'};

                $categorygroup->translations()->save($gt);

            }


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

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

                $newroute = new Route();

                $newroute->object    = 'CategoryGroup';
                $newroute->object_id = $categorygroup->cg_id;
                $newroute->lang      = $lang;
                $newroute->slug      = $request->{$lang.'_slug'};

                $newroute->save();

            }

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

            $log = new Log();

            $log->object    = 'CategoryGroup';
            $log->object_id = $categorygroup->cg_id;
            $log->action    = 'create';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = NULL;

            $log->save();

            DB::commit();

            return redirect()->route('admin.categorygroup.index')->with('result', 'Dodata nova grupa kategorija: "' . $categorygroup->ctranslation->cg_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\CategoryGroup  $categorygroup
     * @return \Illuminate\Http\Response
     */
    public function show(CategoryGroup $categorygroup)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\CategoryGroup  $categorygroup
     * @return \Illuminate\Http\Response
     */
    public function edit(CategoryGroup $categorygroup)
    {

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

        $data = [];
        $data['group']          = $categorygroup;
        $data['create'] = 0;
        return view('admin.categorygroups.form', $data);
    }

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

        $rules = [
            'cg_img'   => 'required|string|min:3',
            'cg_icon'  => 'nullable|string|min:3',
            'cg_feat'  => 'in:0,1',
        ];

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

            $rules[$lang.'_cg_name']  = 'required|string|min:3';
            $rules[$lang.'_cg_title'] = 'nullable|string|min:3';

            $rules[$lang.'_cg_desc'] = 'nullable|string|min:3';
            $rules[$lang.'_cg_keyw'] = 'nullable|string|min:3';

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

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


        try{
            DB::beginTransaction();

            // Save category group data
            //--------------------------------


            $categorygroup->cg_img   = $request->cg_img;
            $categorygroup->cg_icon  = $request->cg_icon;
            $categorygroup->cg_feat  = $request->cg_feat;
            $categorygroup->cg_ord   = 999;

            $categorygroup->save();




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

                $gt = $categorygroup->translations()->where('cgt_lang', $lang)->first();

                if (!is_null($gt)){

                    $gt->cg_name  = $request->{$lang.'_cg_name'};
                    //$gt->cg_slug  = $request->{$lang.'_slug'};
                    $gt->cg_title = $request->{$lang.'_cg_title'};
                    $gt->cg_desc  = $request->{$lang.'_cg_desc'};
                    $gt->cg_keyw  = $request->{$lang.'_cg_keyw'};

                    $gt->save();

                } else {

                    $gt = new CategoryGroupTranslation();

                    $gt->cgt_lang = $lang;
                    $gt->cg_name  = $request->{$lang.'_cg_name'};
                    //$gt->cg_slug  = $request->{$lang.'_slug'};
                    $gt->cg_title = $request->{$lang.'_cg_title'};
                    $gt->cg_desc  = $request->{$lang.'_cg_desc'};
                    $gt->cg_keyw  = $request->{$lang.'_cg_keyw'};

                    $categorygroup->translations()->save($gt);

                }


            }


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

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

                $route = Route::where('object', '=', 'CategoryGroup')->where('lang', '=', $lang)->where('object_id', '=', $categorygroup->cg_id)->first();

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

                    $newroute = new Route();

                    $newroute->object    = 'CategoryGroup';
                    $newroute->object_id = $categorygroup->cg_id;
                    $newroute->lang      = $lang;
                    $newroute->slug      = $request->{$lang.'_slug'};

                    $newroute->save();

                }

            }

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

            $log = new Log();

            $log->object    = 'CategoryGroup';
            $log->object_id = $categorygroup->cg_id;
            $log->action    = 'update';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = NULL;

            $log->save();

            DB::commit();

            return redirect()->route('admin.categorygroup.index')->with('result', 'Podaci o grupi kategorija "' . $categorygroup->ctranslation->cg_name . '" su izmenjeni');

        } 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\CategoryGroup  $categorygroup
     * @return \Illuminate\Http\Response
     */
    public function destroy(CategoryGroup $categorygroup)
    {
        $this->authorize('delete', $categorygroup);

        // If categories in category group restrict delete
        if($categorygroup->categories->count()){
            return redirect()->back()->withInput()->with('error', __('adminforms.categorygroups.have_categories_cant_delete_msg', ['name' => $categorygroup->cg_name]));
            exit;
        }
        $name = $categorygroup->ctranslation->cg_name;
        $id   = $categorygroup->cg_id;

        // Delete CG icon
        $path  = public_path($categorygroup->cg_img);
        if(file_exists($path) && is_readable($path)){ unlink($path);}

        try{
            DB::beginTransaction();


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

            $log = new Log();

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


            // Delete Category group
            // ----------------------------------------------
            $categorygroup->destroy($categorygroup->cg_id);

            DB::commit();

            return redirect()->route('admin.categorygroup.index')->with('result', 'Grupa kategorija "'.$name.'" je obrisana');

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