<?php

namespace App\Http\Controllers\Admin;

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

class CategoryController extends Controller
{

    private $descTypes = ['m' => 'Skraceni opis', 's' => 'Specifikacija - atributi', 'n' => 'Bez opisa'];
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }


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

        $data = [];
        $data['category']   = $category;
        $data['categories'] =  $category->getALlCategories(); //with('group')->get();

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


    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Category $category)
    {
        $this->authorize('create', $category);



        $data = [];
        $data['category']   = $category;
        $data['cgroups']    = CategoryGroup::getALlCategoryGroupsCT();
        $data['attributes'] = [];
        $data['descTypes']  = $this->descTypes;
        $data['create'] = 1;
        return view('admin.categories.form', $data);
    }

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

        $rules = [

            'cg_id' => 'required|integer|exists:category_groups,cg_id',
            'cat_feat' => 'in:0,1',
            'cat_vat' => "required|regex:/^\d*(\.\d{1,2})?$/",
            'cat_filterable' => 'in:0,1',
            'cat_bold' => 'in:0,1',
            'cat_desc_type' => 'in:m,s,n',
            'cat_vip_disc' => "nullable|regex:/^\d*(\.\d{1,2})?$/",
            'cat_sale_disc' => "nullable|regex:/^\d*(\.\d{1,2})?$/",

            'cat_icon' => 'nullable|string|min:5',
        ];




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

            $rules[$lang.'_cat_name'] = 'required|string|min:3';

            $rules[$lang.'_cat_sale_sticker'] = 'nullable|string|min:5';
            $rules[$lang.'_cat_banner'] = 'nullable|string|min:5';
            $rules[$lang.'_cat_bannerlink'] = 'nullable|string|min:10';


            $rules[$lang.'_cat_title'] = 'nullable|string|min:10';
            $rules[$lang.'_cat_metadesc'] = 'nullable|string|min:10';
            $rules[$lang.'_cat_keyw'] = 'nullable|string|min:10';

            $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();

            // Insert category data
            // -----------------------------------

            $category = new Category();

            $category->cg_id            = $request->cg_id;
            $category->cg_order         = $request->cg_order;
            $category->cat_feat         = $request->cat_feat;
            $category->cat_feat_order   = $request->cat_feat_order;
            $category->cat_vat          = $request->cat_vat;
            $category->cat_filterable   = $request->cat_filterable;
            $category->cat_bold         = $request->cat_bold;
            $category->cat_desc_type    = $request->cat_desc_type;
            $category->cat_reg_disc     = $request->cat_reg_disc;
            $category->cat_sale_disc    = $request->cat_sale_disc;
            $category->cat_icon         = $request->cat_icon;
            $category->cg_order         = 999;
            $category->cat_feat_order   = 999;

            $category->save();


            // Translations


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

                $ct = new CategoryTranslation();


                $ct->ct_lang          = $lang;
                $ct->cat_name         = $request->{$lang.'_cat_name'};
                $ct->cat_sale_sticker = $request->{$lang.'_cat_sale_sticker'};
                $ct->cat_banner       = $request->{$lang.'_cat_banner'};
                $ct->cat_bannerlink   = $request->{$lang.'_cat_bannerlink'};
                $ct->cat_title        = $request->{$lang.'_cat_title'};
                $ct->cat_metadesc     = $request->{$lang.'_cat_metadesc'};
                $ct->cat_keyw         = $request->{$lang.'_cat_keyw'};
                $ct->cat_title_sufix  = ''; //$request->{$lang.'_cat_title_sufix'};
                //$ct->cat_slug         = $request->{$lang.'_slug'};

                $category->translations()->save($ct);


            }


            // Insert category attributes
            // -----------------------------------

            $corectAttributes = [];

            if($request->has('atr_id') && is_array($request->atr_id)){
                $existingAttrIds = Attribute::pluck('atr_id')->toArray();
                foreach($request->atr_id as $aid => $label){
                    if(is_numeric($aid) && $aid > 0 && in_array($aid, $existingAttrIds)){
                        $corectAttributes[] = $aid;
                    }
                }
            }

            $category->attributes()->sync($corectAttributes);



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

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

                $route = new Route();

                $route->lang      = $lang;
                $route->object    = 'Category';
                $route->object_id = $category->cat_id;
                $route->slug      = $request->{$lang.'_slug'};

                $route->save();

            }

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

            $log = new Log();

            $log->object    = 'Category';
            $log->object_id = $category->cat_id;
            $log->action    = 'create';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = NULL;

            $log->save();


            DB::commit();

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

    }

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



        $data = [];
        $data['category']   = $category;
        $data['cgroups']    = CategoryGroup::getALlCategoryGroupsCT();
        $data['attributes'] = $category->attributes;
        $data['descTypes']  = $this->descTypes;
        $data['create'] = 0;
        return view('admin.categories.form', $data);
    }

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



        $rules = [

            'cg_id' => 'required|integer|exists:category_groups,cg_id',
            'cat_feat' => 'in:0,1',
            'cat_vat' => "required|regex:/^\d*(\.\d{1,2})?$/",
            'cat_filterable' => 'in:0,1',
            'cat_bold' => 'in:0,1',
            'cat_desc_type' => 'in:m,s,n',
            'cat_vip_disc' => "nullable|regex:/^\d*(\.\d{1,2})?$/",
            'cat_sale_disc' => "nullable|regex:/^\d*(\.\d{1,2})?$/",

            'cat_icon' => 'nullable|string|min:5',
        ];




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

            $rules[$lang.'_cat_name'] = 'required|string|min:3';

            $rules[$lang.'_cat_sale_sticker'] = 'nullable|string|min:5';
            $rules[$lang.'_cat_banner'] = 'nullable|string|min:5';
            $rules[$lang.'_cat_bannerlink'] = 'nullable|string|min:10';


            $rules[$lang.'_cat_title'] = 'nullable|string|min:10';
            $rules[$lang.'_cat_metadesc'] = 'nullable|string|min:10';
            $rules[$lang.'_cat_keyw'] = 'nullable|string|min:10';

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

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





        try{
            DB::beginTransaction();

            $category->cg_id            = $request->cg_id;
            $category->cg_order         = $request->cg_order;
            $category->cat_feat         = $request->cat_feat;
            $category->cat_feat_order   = $request->cat_feat_order;
            $category->cat_vat          = $request->cat_vat;
            $category->cat_filterable   = $request->cat_filterable;
            $category->cat_bold         = $request->cat_bold;
            $category->cat_desc_type    = $request->cat_desc_type;
            $category->cat_reg_disc     = $request->cat_reg_disc;
            $category->cat_sale_disc    = $request->cat_sale_disc;
            $category->cat_icon         = $request->cat_icon;
            $category->cg_order         = 999;
            $category->cat_feat_order   = 999;

            $category->save();

            // Translations


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

                $ct = CategoryTranslation::where('cat_id', $category->cat_id)->where('ct_lang', $lang)->first();

                if(!is_null($ct)){

                    $ct->cat_name = $request->{$lang . '_cat_name'};
                    $ct->cat_sale_sticker = $request->{$lang . '_cat_sale_sticker'};
                    $ct->cat_banner = $request->{$lang . '_cat_banner'};
                    $ct->cat_bannerlink = $request->{$lang . '_cat_bannerlink'};
                    $ct->cat_title = $request->{$lang . '_cat_title'};
                    $ct->cat_metadesc = $request->{$lang . '_cat_metadesc'};
                    $ct->cat_keyw = $request->{$lang . '_cat_keyw'};
                    $ct->cat_title_sufix = ''; //$request->{$lang.'_cat_title_sufix'};
                    //$ct->cat_slug = $request->{$lang.'_slug'};

                    $ct->save();

                } else {

                    $ct = new CategoryTranslation();


                    $ct->ct_lang = $lang;
                    $ct->cat_name = $request->{$lang . '_cat_name'};
                    $ct->cat_sale_sticker = $request->{$lang . '_cat_sale_sticker'};
                    $ct->cat_banner = $request->{$lang . '_cat_banner'};
                    $ct->cat_bannerlink = $request->{$lang . '_cat_bannerlink'};
                    $ct->cat_title = $request->{$lang . '_cat_title'};
                    $ct->cat_metadesc = $request->{$lang . '_cat_metadesc'};
                    $ct->cat_keyw = $request->{$lang . '_cat_keyw'};
                    $ct->cat_title_sufix = ''; //$request->{$lang.'_cat_title_sufix'};
                    //$ct->cat_slug = $request->{$lang.'_slug'};

                    $category->translations()->save($ct);

                }
            }


            // Attributes

            $corectAttributes = [];

            if($request->has('atr_id') && is_array($request->atr_id)){
                $existingAttrIds = Attribute::pluck('atr_id')->toArray();
                foreach($request->atr_id as $aid => $label){
                    if(is_numeric($aid) && $aid > 0 && in_array($aid, $existingAttrIds)){
                        $corectAttributes[] = $aid;
                    }
                }
            }

            $category->attributes()->sync($corectAttributes);


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

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

                $route = Route::where('object', '=', 'Category')->where('lang', '=', $lang)->where('object_id', '=', $category->cat_id)->first();

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

                    $newroute = new Route();

                    $newroute->object    = 'Category';
                    $newroute->object_id = $category->cat_id;
                    $newroute->lang      = $lang;
                    $newroute->slug      = $request->{$lang.'_slug'};

                    $newroute->save();

                }

            }

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

            $log = new Log();

            $log->object    = 'Category';
            $log->object_id = $category->cat_id;
            $log->action    = 'update';
            $log->admin     = auth('admin')->user()->full_name;
            $log->note      = NULL;

            $log->save();

            DB::commit();

            return redirect()->route('admin.category.index')->with('result', __('adminforms.categories.update_controller_msg', ['name' => $category->ctranslation->cat_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\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function destroy(Category $category)
    {
        $this->authorize('delete', $category);

        // Provera da li ima proizvoda u kategoriji ako ima nema brisanja
        if($category->products->count()){
            return redirect()->back()->withInput()->with('error', __('adminforms.categories.have_products_cant_delete_msg', ['name' => $category->cat_name]));
            exit;
        }

        try{
            DB::beginTransaction();


            $id   = $category->cat_id;
            $name = $category->cat_name;

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

            $log = new Log();

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

            $log->save();

            // Remove slugs from routes
            // ------------------------------

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


            // Delete category
            //-----------------------------------------------------

            $category->destroy($id);

            DB::commit();

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