<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Carmodel;
use App\Models\Interiorcolor;
use App\Models\Exteriorcolor;
use App\Models\Carvarient;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Fuletype;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Auth, DB, Mail, Validator, File, DataTables, Exception;
use Illuminate\Support\Facades\DB as FacadesDB;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportProduct;
use App\Exports\ExportProduct;

class ProductController extends Controller{
    /** construct */
        public function __construct(){
            $this->middleware('permission:products-create', ['only' => ['create']]);
            $this->middleware('permission:products-edit', ['only' => ['edit']]);
            $this->middleware('permission:products-view', ['only' => ['view']]);
            $this->middleware('permission:products-delete', ['only' => ['delete']]);
        }
    /** construct */

    /** index */
        public function index(Request $request){
            
                    
            if($request->ajax()){
                 
                $data = Product::select('products.id','products.status','car_model.name as car_name', 'exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color', 'car_varient.name as varient_name')
                    ->leftJoin('car_model','car_model.id','=','products.car_model')
                    ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
                    ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
                    ->leftJoin('car_varient','car_varient.id','=','products.veriant')
                    ->where('products.status', 'active')
                    ->orderBy('id' , 'desc');
                    //->orderBy('id' , 'desc')->get();
               // $data = Product::orderBy('id' , 'desc')->get();
                
                return Datatables::of($data)
                        ->addIndexColumn()
                        ->addColumn('action', function($data){
                            $return = '<div class="btn-group">';

                            if(auth()->user()->can('products-view')){
                                $return .= '<a href="'.route('products.view', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-eye"></i>
                                            </a> &nbsp;';
                            }   
                            
                            if(auth()->user()->can('products-edit')){
                                $return .= '<a href="'.route('products.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-pencil"></i>
                                            </a> &nbsp;';
                            }   

                            if (auth()->user()->can('products-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>';
                            } else if ($data->status == 'inactive') {
                                return '<span class="badge badge-pill badge-warning">Inactive</span>';
                            } else if ($data->status == 'deleted') {
                                return '<span class="badge badge-pill badge-danger">Deleted</span>';
                            }else if ($data->status == 'pdi_hold') {
                                return '<span class="badge badge-pill badge-warning">Hold By PDI</span>';
                            }
                        })
                        ->rawColumns([ 'action' ,'status'])
                        ->filter(function ($query){
                            if (request()->get('car_name',false)) {
                                $query->where('car_model.name', "like", "%".request()->get("car_name")."%");
                            }
                            if (request()->get('varient_name',false)) {
                                $query->where('car_varient.name', "like", "%".request()->get("varient_name")."%");
                            }
                            if (request()->get('exterior_color',false)) {
                                $query->where('exteriorcolor.name', "like", "%".request()->get("exterior_color")."%");
                            }
                            if (request()->get('interior_color',false)) {
                                $query->where('interiorcolor.name', "like", "%".request()->get("interior_color")."%");
                            }
                        })    
                        ->make(true);
            }
            return view('product.index');
        }
    /** index */

    /**create */
        public function create(Request $request){ 

            $Carmodel = Carmodel::where(['status' => 'active'])->get();
            $Carvarient = Carvarient::where(['status' => 'active'])->get();
            $fuel_type = Fuletype::select('*')->where('status','=','active')->get();
            /* return view('car_varient.create')->with(['Carmodel' => $Carmodel ,'Colortone' => $Colortone,'Fuletype'=>$Fuletype,'Transmission' => $Transmission,'Interiorcolor' => $Interiorcolor,'Exteriorcolor' => $Exteriorcolor]);

            $data = Carmodel::select('car_model.*', 'car_varient.id as v_id', 'car_varient.name as car_vname')
            ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
            ->where('car_model.status', 'active')*/
            // ->where('car_varient.status', 'active')->get();
             //dd($data);
            return view('product.create')->with(['Carmodel'=>$Carmodel,'Carvarient'=>$Carvarient,'fuel_type'=>$fuel_type]);
         }
    /**create */

    /**carvarient */
        public function carvarient(Request $request){ 
            $id = ($request->id);
            $data_new = Carvarient::select('Interior_color')->where(['id' => $id])->where(['status' => 'active'])->get()->toArray();

            $Interior_color =  $data_new[0]['Interior_color'];

            $Interior_color_arr = explode(',', $Interior_color);
           

            $data_new = Interiorcolor::select('name','id')->whereIn('id',$Interior_color_arr)->where(['status' => 'active'])->get();


            $data_new_Interior_color_arr = [];
            foreach ($data_new as $value) {
                $color_data = [];
                $color_data['id'] = $value->id;
                $color_data['name'] = $value->name;
                $data_new_Interior_color_arr[] = $color_data;
                
            }
            
            $data_new_e = Carvarient::select('exterior_color')->where(['id' => $id])->where(['status' => 'active'])->get()->toArray();
            $Exterior_color =  $data_new_e[0]['exterior_color'];
            $Exterior_color_arr = explode(',', $Exterior_color);
            $data_new_e = Exteriorcolor::select('name','id')->whereIn('id',$Exterior_color_arr)->where(['status' => 'active'])->get();

            
            $data_new_Exterior_color_arr = [];
            foreach ($data_new_e as $value) {
                $excolor_data = [];
                $excolor_data['e_id'] = $value->id;
                $excolor_data['e_name'] = $value->name;
                $data_new_Exterior_color_arr[] = $excolor_data;
                
            }

            $data = [];

            $data['Interior_color'] = $data_new_Interior_color_arr;
            $data['Exterior_color'] = $data_new_Exterior_color_arr;

           
            return json_encode(array('status'=> true ,'data' => $data));
        }
    /** carvarient */

    /** insert */
        public function insert(Request $request){
            if($request->ajax()) { return true; }

            // if(empty($request->ex_showroom_price) || $request->ex_showroom_price == '') {
            //     return redirect()->back()->with(['error'=>'Please Enter Ex-Showroom Price'])->withInput();
            // }


            $crud = [
                'car_model' => $request->car_model,
                'fuel_type'=>$request->fuel_type,
                'veriant' => $request->veriant,
                'interior_color' => $request->interior_color,
                'exterior_color' => $request->exterior_color,
                // 'ex_showroom_price' => $request->ex_showroom_price,
                //'is_applicable_for_mcp' => $request->is_applicable_for_mcp,
                '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
            ];

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

            // die('sss');

            if ($last_id) {
                return redirect()->route('products')->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 = Product::select('products.*','car_model.name as car_name', 'exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color', 'car_varient.name as varient_name','fule_type.title')
                    ->leftJoin('car_model','car_model.id','=','products.car_model')
                    ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
                    ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
                    ->leftJoin('car_varient','car_varient.id','=','products.veriant')
                    ->leftJoin('fule_type','fule_type.id','=','products.fuel_type')
                    ->where(['products.id' => $id])->first();

            /*$data = Product::select('products.*' ,'categories.name AS category_name')->leftjoin('categories' ,'products.category_id' ,'categories.id')->where(['products.id' => $id])->first();*/
            // dd($data);
            return view('product.view')->with(['data'=>$data]);
        }
    /** view */

    /** edit */
        public function edit(Request $request){
            $id = base64_decode($request->id);
            
            /*$data_new = Product::select('products.*','car_model.name as car_name', 'exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color', 'car_varient.name as varient_name')
                    ->leftJoin('car_model','car_model.id','=','products.name')
                    ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
                    ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
                    ->leftJoin('car_varient','car_varient.id','=','products.veriant')
                    ->where(['products.id' => $id])->first();
             
             $data = Carmodel::select('car_model.*', 'car_varient.id as v_id', 'car_varient.name as car_vname', 'car_varient.exterior_color as v_exterior_color', 'car_varient.exterior_color as v_Interior_color', 'exteriorcolor.name as exterior_color', 'exteriorcolor.id as exterior_id', 'interiorcolor.name as interior_color', 'interiorcolor.id as interior_id')
            ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
            ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')
            ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')
            ->where('car_varient.status', 'active')->get();*/

            $data = Product::where(['id' => $id])->first();
            $Carmodel = Carmodel::where(['status' => 'active'])->get();
            $Carvarient = Carvarient::where(['status' => 'active','car_model'=>$data->car_model,'fule_type'=>$data->fuel_type])->get();
            $fuel_type = Fuletype::select('*')->where('status','=','active')->get();
            return view('product.edit')->with(['data'=>$data, 'Carmodel'=>$Carmodel, 'Carvarient'=>$Carvarient,'fuel_type'=>$fuel_type]);
        }
    /** edit */

    /** update */
        public function update(Request $request){

            // if(empty($request->ex_showroom_price) || $request->ex_showroom_price == '') {
            //     return redirect()->back()->with(['error'=>'Please Enter Ex-Showroom Price'])->withInput();
            // }


            if($request->ajax()) { return true; }
            $crud = [
                  'car_model' => $request->car_model,
                  'fuel_type'=>$request->fuel_type,
                  'veriant' => $request->veriant,
                  'interior_color' => $request->interior_color,
                  'exterior_color' => $request->exterior_color,
                //   'ex_showroom_price' => $request->ex_showroom_price,
                  //'is_applicable_for_mcp' => $request->is_applicable_for_mcp,
                  '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
                ];

               
                DB::beginTransaction();
                try {
                    DB::getQueryLog();
                    $last_id = Product::where(['id' => $request->id])->update($crud);
                    
                    if ($last_id) {
                        DB::commit();
                        return redirect()->route('products')->with('success', 'Record updated successfully');
                    } else {
                        DB::rollback();
                        return redirect()->back()->with('error', 'Failed to update record')->withInput();
                    }
                } catch (\Throwable $th) {
                    DB::rollback();
                    return redirect()->back()->with('error', 'Something went wrong, please try again later')->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 = Product::where(['id' => $id])->first();
            if (!empty($data)) {
                $update = Product::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 ImportProduct(), $request->file('file'));  

            
            if($import){
                Excel::store(new ImportProduct(), 'Product_'.Date('YmdHis').'.xlsx' ,'excel_import');
                 /*var_dump($import);
             die('stop');*/
                return redirect()->route('products')->with('sucess' ,'File Imported Sucessfully');
            }
        }
    /** Import */

    /** Export */
        public function export(Request $request){
            $slug = $request->slug;
            $name = 'Product'.Date('YmdHis').'.xlsx';

            try {
                return Excel::download(new ExportProduct($slug), $name);
            }catch(\Exception $e){
                return redirect()->back()->with('error' ,$e->getMessage());
            }
        }
    /** Export */
}
