<?php



namespace App\Http\Controllers;



use Illuminate\Http\Request;

use Spatie\Permission\Models\Role;

use Spatie\Permission\Models\Permission;

use App\Models\Carvarient;



use App\Models\Carmodel;

use App\Models\Colortone;

use App\Models\Product;

use App\Models\Fuletype;

use App\Models\Transmission;

use App\Models\Interiorcolor;

use App\Models\Exteriorcolor;

use App\Models\Texmaster;

use App\Imports\ImportCarVarient;

use App\Exports\ExportCarVarient;

use Maatwebsite\Excel\Facades\Excel;

use Auth, DB, Mail, Validator, File, DataTables, Exception;



class CarVarientController extends Controller{

    /** construct */

        public function __construct(){

            $this->middleware('permission:car_varient-create', ['only' => ['create']]);

            $this->middleware('permission:car_varient-edit', ['only' => ['edit']]);

            $this->middleware('permission:car_varient-view', ['only' => ['view']]);

            $this->middleware('permission:car_varient-delete', ['only' => ['delete']]);

        }

    /** construct */



    /** index */

        public function index(Request $request) {

            if ($request->ajax()) {

                $data = DB::table('car_varient as i')

                    ->select(

                        'i.id',

                        'i.name',

                        'i.status',

                        'cm.name as car_model',

                        'ft.title as fuel_type', 

                        'tra.name as transmission_value',

                        'i.hsn_code',

                        'tex_master.gst',

                        'tex_master.compensation_cess'

                    )

                    ->leftJoin('car_model as cm', 'cm.id', '=', 'i.car_model')

                    ->leftJoin('fule_type as ft', 'ft.id', '=', 'i.fule_type')

                    ->leftJoin('transmission as tra', 'tra.id', '=', 'i.transmission')

                    ->leftjoin('tex_master', 'tex_master.id', '=', 'i.tex_master_id')

                    ->whereIn('i.status', ['active', 'inactive', 'deleted'])

                    // ->where('i.status', '!=', 'deleted')

                    ->orderBy('i.id', 'desc');

        

                return Datatables::of($data)

                    ->addIndexColumn()

                    ->addColumn('action', function ($data) {

                        $return = '<div class="btn-group">';

        

                        if (auth()->user()->can('car_varient-view')) {

                            $return .= '<a href="'.route('car_varient.view', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">

                                            <i class="fa fa-eye"></i>

                                        </a> &nbsp;';

                        }

        

                        if (auth()->user()->can('car_varient-edit')) {

                            $return .= '<a href="'.route('car_varient.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">

                                            <i class="fa fa-pencil"></i>

                                        </a> &nbsp;';

                        }

        

                        if (auth()->user()->can('car_varient-delete')) {

                            $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">

                                            <i class="fa fa-bars"></i>

                                        </a> &nbsp;

                                                <ul class="dropdown-menu">

                                                    <li><a class="dropdown-item change-status" href="javascript:;" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>

                                                    <li><a class="dropdown-item change-status" href="javascript:;" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>

                                                    <li><a class="dropdown-item change-status" href="javascript:;" data-status="deleted" data-id="' . base64_encode($data->id) . '">Deleted</a></li>

                                                </ul>';

                        }

        

                        $return .= '</div>';

                        return $return;

                    })

                    ->editColumn('status', function ($data) {

                        if ($data->status == 'active') {

                            return '<span class="badge badge-pill badge-success">Active</span>';

                        } elseif ($data->status == 'inactive') {

                            return '<span class="badge badge-pill badge-warning">Inactive</span>';

                        } elseif ($data->status == 'deleted') {

                            return '<span class="badge badge-pill badge-danger">Deleted</span>';

                        }

                    })

                    ->rawColumns(['action', 'status'])

                    ->filter(function ($query) {

                        if (request()->get('car_varient_name', false)) {

                            $query->where('i.name', 'like', "%" . request()->get("car_varient_name") . "%");

                        }

                        if (request()->get('model_name', false)) {

                            $query->where('cm.name', 'like', "%" . request()->get("model_name") . "%");

                        }

                        if (request()->get('fuel_type', false)) {

                            $query->where('ft.title', 'like', "%" . request()->get("fuel_type") . "%");

                        }

                        if (request()->get('transmission_value', false)) {

                            $query->where('tra.name', 'like', "%" . request()->get("transmission_value") . "%");

                        }

                        if (request()->get('hsn_code', false)) {

                            $query->where('i.hsn_code', 'like', "%" . request()->get("hsn_code") . "%");

                        }

                        if (request()->get('gst', false)) {

                            $query->where('tex_master.gst', 'like', "%" . request()->get("gst") . "%");

                        }

                        if (request()->get('compensation_cess', false)) {

                            $query->where('tex_master.compensation_cess', 'like', "%" . request()->get("compensation_cess") . "%");

                        }

                    })

                    ->make(true);

            }

        

            return view('car_varient.index');

        }



    /** index */



    /** create */

        public function create(Request $request){

            $Carmodel = Carmodel::where(['status' => 'active'])->get();

            $Colortone = Colortone::where(['status' => 'active'])->get();

            $Fuletype = Fuletype::where(['status' => 'active'])->get();

            $Transmission = Transmission::where(['status' => 'active'])->get();

            $Interiorcolor = Interiorcolor::where(['status' => 'active'])->get();

            $Exteriorcolor = Exteriorcolor::where(['status' => 'active'])->get();

            $Texmaster = Texmaster::where(['status' => 'active'])->get();

            return view('car_varient.create')->with(['Carmodel' => $Carmodel ,'Colortone' => $Colortone,'Fuletype'=>$Fuletype,'Transmission' => $Transmission,'Interiorcolor' => $Interiorcolor,'Exteriorcolor' => $Exteriorcolor,'Texmaster' => $Texmaster]);



            // return view('car_varient.create');

        }

    /** create */



    /** insert */

        public function insert(Request $request){

            if($request->ajax()) { return true; }





            $crud = [

                'name' => $request->name,

                // 'percentage' => $request->percentage,

                'car_model' => $request->car_model,

                'fule_type' => $request->fule_type,

                'transmission' => $request->transmission,

                'hsn_code' => $request->hsn_code,

                'tex_master_id' => $request->tex_master_id,

                'status' => 'active',

                'created_at' => date('Y-m-d H:i:s'),

                'created_by' => auth()->user()->id,

                'updated_at' => date('Y-m-d H:i:s'),

                'updated_by' => auth()->user()->id

            ];



            if(!empty($request->color_tone)){

                $crud['color_tone'] = implode(',',$request->color_tone);

            }else{

                $crud['color_tone'] = '';

            }



            $exterior_color_arr = [];

            if(!empty($request->exterior_color)){

                $crud['exterior_color'] = implode(',',$request->exterior_color);

                $exterior_color_arr = $request->exterior_color;

            }else{

                $crud['exterior_color'] = '';

                return redirect()->back()->with(['error'=>'Please select at leaset one exterior color'])->withInput();

            }



            $Interior_color_arr = [];
            $crud['Interior_color'] = '';

            if(!empty($request->Interior_color)){

                $crud['Interior_color'] = implode(',',$request->Interior_color);

                $Interior_color_arr = $request->Interior_color;

            }
            // else{

            //     $crud['Interior_color'] = '';

            //     return redirect()->back()->with(['error'=>'Please select at leaset one interior color'])->withInput();

            // }

            



            $last_id = Carvarient::insertGetId($crud);



            if ($last_id) {



                // $car_master_arr_g = [];



                if(!empty($exterior_color_arr)){

                    foreach ($exterior_color_arr as $value_e) {



                        foreach ($Interior_color_arr as $value_i) {

                            $car_master_arr = [

                                'car_model' => $request->car_model,

                                'veriant' => $last_id,

                                'interior_color' => $value_i,

                                'exterior_color' => $value_e,

                                'status' => 'active',

                                'created_at' => date('Y-m-d H:i:s'),

                                'created_by' => auth()->user()->id,

                                'updated_at' => date('Y-m-d H:i:s'),

                                'updated_by' => auth()->user()->id

                            ];



                            // $car_master_arr_g[] = $car_master_arr;

                            $car_master__id = Product::insertGetId($car_master_arr);           

                        }

                    }

                }



                /*echo "<pre>";

                print_r($car_master_arr_g);

                die('stop');*/



                return redirect()->route('car_varient')->with(['success' => 'Record inserted successfully']);

            } else {

                return redirect()->back()->with(['error'=>'Faild to insert Record!'])->withInput();

            }

        

        }

    /** insert */



    /** view */

        public function view(Request $request){

            $id = base64_decode($request->id);

            $data = Carvarient::where(['id' => $id])->first();

            

            // return view('car_varient.view')->with(['data'=>$data]);



            $Carmodel = Carmodel::where(['status' => 'active'])->get();

            $Colortone = Colortone::where(['status' => 'active'])->get();

            $Fuletype = Fuletype::where(['status' => 'active'])->get();

            $Transmission = Transmission::where(['status' => 'active'])->get();

            $Interiorcolor = Interiorcolor::where(['status' => 'active'])->get();

            $Exteriorcolor = Exteriorcolor::where(['status' => 'active'])->get();

             $Texmaster = Texmaster::where(['status' => 'active'])->get();            

            return view('car_varient.view')->with(['data'=>$data,'Carmodel' => $Carmodel ,'Colortone' => $Colortone,'Fuletype'=>$Fuletype,'Transmission' => $Transmission,'Interiorcolor' => $Interiorcolor,'Exteriorcolor' => $Exteriorcolor,'Texmaster' => $Texmaster]);

        }

    /** view */

    

    /** edit */

        public function edit(Request $request){

            $id = base64_decode($request->id);

            $data = Carvarient::where(['id' => $id])->first();

            $Carmodel = Carmodel::where(['status' => 'active'])->get();

            $Colortone = Colortone::where(['status' => 'active'])->get();

            $Fuletype = Fuletype::where(['status' => 'active'])->get();

            $Transmission = Transmission::where(['status' => 'active'])->get();

            $Interiorcolor = Interiorcolor::where(['status' => 'active'])->get();

            $Exteriorcolor = Exteriorcolor::where(['status' => 'active'])->get();

            $Texmaster = Texmaster::where(['status' => 'active'])->get();            

            return view('car_varient.edit')->with(['data'=>$data,'Carmodel' => $Carmodel ,'Colortone' => $Colortone,'Fuletype'=>$Fuletype,'Transmission' => $Transmission,'Interiorcolor' => $Interiorcolor,'Exteriorcolor' => $Exteriorcolor,'Texmaster' => $Texmaster]);

        }

    /** edit */



    /** update */

        public function update(Request $request){

            if($request->ajax()){ return true; }

            $id = $request->id;

            

            $crud = [

                'name' => $request->name,

                // 'percentage' => $request->percentage,

                'car_model' => $request->car_model,

                'fule_type' => $request->fule_type,

                'transmission' => $request->transmission,   

                'hsn_code' => $request->hsn_code,      

                'tex_master_id' => $request->tex_master_id,       

                'updated_at' => date('Y-m-d H:i:s'),

                'updated_by' => auth()->user()->id

            ];



            if(!empty($request->color_tone)){

                $crud['color_tone'] = implode(',',$request->color_tone);

            }else{

                $crud['color_tone'] = '';

            }



            $exterior_color_arr = [];

            if(!empty($request->exterior_color)){

                $crud['exterior_color'] = implode(',',$request->exterior_color);

                 $exterior_color_arr = $request->exterior_color;               

            }else{

                $crud['exterior_color'] = '';

                return redirect()->back()->with(['error'=>'Please select at leaset one exterior color'])->withInput();

            }



            $Interior_color_arr = [];
            $crud['Interior_color'] = '';

            if(!empty($request->Interior_color)){

                $crud['Interior_color'] = implode(',',$request->Interior_color);

                $Interior_color_arr = $request->Interior_color;

            }
            // else{

            //     $crud['Interior_color'] = '';

            //     return redirect()->back()->with(['error'=>'Please select at leaset one interior color'])->withInput();

            // }

            



            DB::enableQueryLog();

            $update = Carvarient::where(['id' => $id])->update($crud);

            // dd(DB::getQueryLog());

            if ($update){



                if(!empty($exterior_color_arr)){

                    // echo "1";

                    foreach ($exterior_color_arr as $value_e) {

                        // echo "2";



                        foreach ($Interior_color_arr as $value_i) {



                            $Product_id_data_count = Product::select('id')->where(['car_model' => $request->car_model,'veriant' => $id,'interior_color' => $value_i,'exterior_color' => $value_e])->count();



                            // echo "<pre>";

                            // var_dump($Product_id_data_count);



                            if($Product_id_data_count == 0){

                                $car_master_arr = [

                                    'car_model' => $request->car_model,

                                    'veriant' => $id,

                                    'interior_color' => $value_i,

                                    'exterior_color' => $value_e,

                                    'status' => 'active',

                                    'created_at' => date('Y-m-d H:i:s'),

                                    'created_by' => auth()->user()->id,

                                    'updated_at' => date('Y-m-d H:i:s'),

                                    'updated_by' => auth()->user()->id

                                ];

                                // echo "1";

                                // $car_master_arr_g[] = $car_master_arr;

                                $car_master__id = Product::insertGetId($car_master_arr);    

                            } 

                        }

                    }

                }

                // die('s');



                return redirect()->route('car_varient')->with(['success' => 'Record updated successfully']);

            }else{

                return redirect()->back()->with(['error'=>'Faild to update Record!'])->withInput();

            }

        }

    /** update */



    /** change-status */

        public function change_status(Request $request){

            if (!$request->ajax()) { exit('No direct script access allowed'); }

            $id = base64_decode($request->id);

            

            $data = Carvarient::where(['id' => $id])->first();



            if (!empty($data)) {

                $update = Carvarient::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth('sanctum')->user()->id]);

                if ($update) {

                    return response()->json(['code' => 200]);

                } else {

                    return response()->json(['code' => 201]);

                }

            } else {

                return response()->json(['code' => 201]);

            }

           

        }

    /** change-status */



    /** Import */

        public function import(Request $request){

            $import = Excel::import(new ImportCarVarient(), $request->file('file'));    

            if($import){

                Excel::store(new ImportCarVarient(), 'CarVarient_'.Date('YmdHis').'.xlsx' ,'excel_import');

                return redirect()->route('car_varient')->with('sucess' ,'File Imported Sucessfully');

            }

        }

    /** Import */



    /** Export */

        public function export(Request $request){

            $slug = $request->slug;

            $name = 'CarVarient_'.Date('YmdHis').'.xlsx';

    

            try {

                return Excel::download(new ExportCarVarient($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error', $e->getMessage());

            }

        }

    /** Export */



   

}

