<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Branch;
use App\Models\Department;
use App\Models\offer;
use App\Models\Carmodel;
use App\Models\Lead;
use App\Exports\ExportOffersDiscount;
use App\Models\Fuletype;
use App\Models\Carvarient;
use App\Models\Inventory;
use App\Models\Exteriorcolor;
use App\Models\Interiorcolor;
use Maatwebsite\Excel\Facades\Excel;
use Auth, DB, Mail, Validator, File, DataTables, Exception;
use App\Imports\ImportOffersDiscount;

class offercontroller extends Controller
{
    public function __construct(){
            $this->middleware('permission:offers_discounts-create', ['only' => ['create']]);
            $this->middleware('permission:offers_discounts-edit', ['only' => ['edit']]);
            $this->middleware('permission:offers_discounts-view', ['only' => ['view']]);
            $this->middleware('permission:offers_discounts-delete', ['only' => ['delete']]);
        }
    //  construct
    
    //  index 
    public function index(Request $request){
        if($request->ajax()){
           $data =  DB::table('offer')
                ->select(
                    'offer.*',
                    'branches.name as branch',
                    'fule_type.title as fuel_type',
                    'car_varient.name as variant',
                    'car_model.name as car_model',
                    DB::raw("(SELECT GROUP_CONCAT(DISTINCT city SEPARATOR ',<br>') 
                      FROM branches 
                      WHERE FIND_IN_SET(branches.id, offer.fk_branch_id)
                    ) as branch_city"),
                )
                ->leftJoin('branches', 'branches.id', '=', 'offer.fk_branch_id')
                ->leftJoin('fule_type', 'fule_type.id', '=', 'offer.fk_fuel_id')
                ->leftJoin('car_model', 'car_model.id', '=', 'offer.fk_car_model_id')
                ->leftJoin('car_varient', 'car_varient.id', '=', 'offer.fk_car_varient_id')
                ->orderBy('offer.id', 'desc');
            
                return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($data){
                        $return = '<div class="btn-group">';

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

                       //if (auth()->user()->can('city-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" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                                                <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                                                <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>
                                            </ul>';
                       // }

                        $return .= '</div>';

                        return $return;
                    })

                ->editColumn('booking_date',function($data){
                            return (isset($data->booking_date) && !empty($data->booking_date))?\Carbon\Carbon::createFromFormat('Y-m-d',$data->booking_date)->format('d-m-Y') : '--';
                        })
                        ->editColumn('booking_date',function($data){
                            return (isset($data->booking_date) && !empty($data->booking_date))?\Carbon\Carbon::createFromFormat('Y-m-d',$data->booking_date)->format('d-m-Y') : '--';
                        })
                        ->editColumn('description', function($data) {
                            $fullText = $data->description;
                            $shortText = strlen($fullText) > 8 ? substr($fullText, 0, 8) . '...' : $fullText;
                        
                            return '<span title="' . e($fullText) . '">' . e($shortText) . '</span>';
                        })
                        ->editColumn('branch', function ($data) {
                            return $data->branch_city ?? '-';
                        })
                    ->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{
                            return '-';
                        }
                    })

                    ->rawColumns([ 'action' ,'status','description','branch'])
                    ->filter(function ($query){
                            if (request()->get('title',false)) {
                                $query->where('offer.title', "like", "%".request()->get("title")."%");
                            }
                            if (request()->get('start_date',false)) {
                                $query->where('offer.start_date', "like", "%".request()->get("start_date")."%");
                            }
                            if (request()->get('end_date',false)) {
                                $query->where('offer.end_date', "like", "%".request()->get("end_date")."%");
                            }
                            if (request()->get('offer_type',false)) {
                                $query->where('offer.offer_type', "like", "%".request()->get("offer_type")."%");
                            }
                            if (request()->get('branch',false)) {
                                $query->where('branches.name', "like", "%".request()->get("branch")."%");
                            }
                            if (request()->get('car_model',false)) {
                                $query->where('car_model.name', "like", "%".request()->get("car_model")."%");
                            }
                            if (request()->get('fuel_type',false)) {
                                $query->where('fule_type.title', "like", "%".request()->get("fuel_type")."%");
                            }
                            if (request()->get('amount',false)) {
                                $query->where('offer.description', "like", "%".request()->get("description")."%");
                            }
                            if (request()->get('company_contribution',false)) {
                                $query->where('offer.company_contribution', "like", "%".request()->get("company_contribution")."%");
                            }
                            if (request()->get('status',false)) {
                                $query->where('offer.status', "like", "%".request()->get("status")."%");
                            }
                        })    
                    ->make(true);
            }
        return view('offer.index');
    }
    //  index 
    
    // create /
    public function create(Request $request){
        $fuel_type = Fuletype::where(['status'=>'active'])->get();
        $veriant = Carvarient::where(['status'=>'active'])->get();
        $Carmodel_arr = Carmodel::where(['status' => 'active'])->get(); 
        $branch = Branch::where(['status'=>'active'])->get();
        return view('offer.create')->with(['fuel_type'=>$fuel_type,'veriant'=>$veriant,'Carmodel_arr'=>$Carmodel_arr,'branch'=>$branch]);
    }
    //  create /
    //  insert 
    public function insert(Request $request){
        if($request->ajax()){
            return true ;
        }
        
        $varient = $request->veriant;
        $varient_id = implode(',',$varient);
        $vin = $request->vin ?? '';
        $vin_num = implode(',',$vin);
        
        $branch = $request->branch_id;
        $branch_id = implode(',',$branch);
        
        $crud = [
                'title' => $request->title,
                'fk_branch_id'=>$branch_id ?? '',
                'fk_car_model_id'=>$request->car_name,
                'fk_fuel_id' => $request->fuel_type,
                'fk_car_varient_id'=>$varient_id ?? '',
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'offer_type' => $request->offer_type,
                'amount' =>$request->amount,
                'company_contribution' => $request->company_contribution ?? '',
                'vin_number' => $vin_num ?? '' ,
                'description' => $request->description,
                '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::enableQueryLog();
            $last_id = offer::insertGetId($crud);
            if ($last_id) {
                
                DB::commit();
                return redirect()->route('offer')->with('success', 'Record inserted successfully');
            } else {
                DB::rollback();
                return redirect()->back()->with('error', 'Failed to insert record')->withInput();
            }
        } catch (\Throwable $th) {
            DB::rollback();
            return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();
        }
    }
    //  insert /

    //  view /
    public function view(Request $request){  
        $id = base64_decode($request->id);
                                
        $data = offer::select('offer.*','fule_type.title as ftitle','fule_type.id as fid','car_model.id as mid','car_model.name','car_varient.id as vid','car_varient.name as vname','interiorcolor.name as iname','exteriorcolor.name as ename','branches.name as branch_name')->leftjoin('fule_type','fule_type.id','=','offer.fk_fuel_id')->leftjoin('car_model','car_model.id','=','offer.fk_car_model_id')->leftjoin('car_varient','car_varient.id','=','offer.fk_car_varient_id')->leftjoin('interiorcolor','interiorcolor.id','=','offer.interior_color')->leftjoin('exteriorcolor','exteriorcolor.id','=','offer.exterior_color')->leftjoin('branches','branches.id','=','offer.fk_branch_id')->where(['offer.id' => $id])->first();
        
        return view('offer.view')->with(['data' => $data]);
    }
    // view /

    // edit /
    public function edit(Request $request){
        $id = base64_decode($request->id);
                                
        $data = offer::select('offer.*','fule_type.title as ftitle','fule_type.id as fid','car_model.id as mid','car_model.name','car_varient.id as vid','car_varient.name as vname','interiorcolor.name as iname','exteriorcolor.name as ename','branches.name as branch_name','branches.id as branch_id')->leftjoin('fule_type','fule_type.id','=','offer.fk_fuel_id')->leftjoin('car_model','car_model.id','=','offer.fk_car_model_id')->leftjoin('car_varient','car_varient.id','=','offer.fk_car_varient_id')->leftjoin('interiorcolor','interiorcolor.id','=','offer.interior_color')->leftjoin('exteriorcolor','exteriorcolor.id','=','offer.exterior_color')->leftjoin('branches','branches.id','=','offer.fk_branch_id')->where(['offer.id' => $id])->first();
        $fuel_type = Fuletype::where(['status'=>'active'])->get();
        $veriant = Carvarient::where(['status'=>'active'])->get();
        $Carmodel_arr = Carmodel::where(['status' => 'active'])->get();
        $branch = Branch::where(['status'=>'active'])->get();
        return view('offer.edit')->with(['data' => $data,'fuel_type'=>$fuel_type,'veriant'=>$veriant,'Carmodel_arr'=>$Carmodel_arr,'branch'=>$branch]);
    }
    // edit /

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

        if($request->exteriorcolor != null){
            $ecolor = Exteriorcolor::where('name',$request->exteriorcolor)->first();
            $exteriorcolor = $ecolor->id;            
        }

        if($request->interiorcolor != null){
            $icolor = Interiorcolor::where('name',$request->interiorcolor)->first();
            $interiorcolor = $icolor->id;            
        }
        
        $variant = $request->veriant;
        $varient_id = is_array($variant) ? implode(',', $variant) : $variant;
        
        $vin = $request->vin;
        $vin_num = is_array($vin) ? implode(',', $vin) : $vin;
            
       // $branch_admin=$request->branch_admin ? 1 : NULL;
        $crud = [       
            'title' => $request->title,
            'fk_branch_id'=>$request->branch_id,
            'fk_car_model_id'=>$request->car_name,
            'fk_fuel_id' => $request->fuel_type,
            'fk_car_varient_id'=>$varient_id,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'offer_type' => $request->offer_type,
            'amount' =>$request->amount,
            'company_contribution' => $request->company_contribution ?? '',
            'vin_number' => $vin_num,
            'description' => $request->description,          
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => auth()->user()->id    
        ];
       
        //dd($crud);
        DB::beginTransaction();
        try {
            DB::enableQueryLog();
            $update = offer::where(['id' => $request->id])->update($crud);
            if($update){
                DB::commit();
                return redirect()->route('offer')->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 = offer::where(['id' => $id])->first();
       
            if(!empty($data)){
                $update = offer::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s')]);
                if($update){
                    return response()->json(['code' => 200]);
                }else{
                    return response()->json(['code' => 201]);
                }
            }else{
                return response()->json(['code' => 201]);
            }
    }
    /* change-status /

    /* Export */
    public function export(Request $request){
        if(isset($request->slug) && $request->slug != null){
            $slug = $request->slug;
        }else{
            $slug = 'all';
        }

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

        try {
            return Excel::download(new ExportOffersDiscount($slug), $name);
        }catch(\Exception $e){
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
    
    /* Import */
    public function import(Request $request){
           
        if(Excel::import(new ImportOffersDiscount, $request->file('file')->store('file'))){
            return redirect()->route('offer')->with('sucess' ,'File Imported Sucessfully');
        }else{
            return redirect()->route('offer')->with('error' ,'Faild To Import File!');
        }
    }
    
    //car_vin_asper_variant
    public function car_vin_asper_variant(Request $request){

        $varient = $request->varient;
        $data =[];
        $vin_num = [];

        if($request->option_check == 'vin_number'){
                $vin= Inventory::select('inventory.vin_number','branches.name as branch_name')->leftjoin('products','products.id','=','inventory.name')->leftjoin('branches','branches.id','=','inventory.branch_id')->where('inventory.offer_applicable','Yes')->whereIn('products.veriant', $varient)->get();
                
                foreach ($vin as $value) {
                    $color_data = [];                    
                    $color_data['vin_num'] = $value->vin_number;
                    $color_data['branch'] = $value->branch_name;
                    $vin_num[] = $color_data;                    
                }  
            }
            
            $data['vin_num'] = $vin_num;  

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

    //ex_price_asper_vin
    public function ex_price_asper_vin(Request $request){
        $vin_num = $request->vin_num;
        $data =[];
        //$price = [];

        if($request->option_check == 'ex_showroom_price'){
                $ex_price= Inventory::select('inventory.ex_showroom_price','inventory.aging_days as agingdays','interiorcolor.name as iname','exteriorcolor.name as ename')->leftjoin('products','products.id','=','inventory.name')->leftjoin('interiorcolor','interiorcolor.id','=','products.interior_color')->leftjoin('exteriorcolor','exteriorcolor.id','=','products.interior_color')->where(['inventory.vin_number' => $vin_num,'inventory.status' => 'active'])->first();
                
                $price = $ex_price->ex_showroom_price;
                $exteriorcolor = $ex_price->ename;
                $interiorcolor = $ex_price->iname;
                $aging_days = $ex_price->agingdays;
                // foreach ($ex_price as $value) {
                //     $color_data = [];                    
                //     $color_data['ex_showroom_price'] = $value->ex_showroom_price;
                //     $price[] = $color_data;                    
                // }  
            }
            
            $data['price'] = $price;
            $data['exteriorcolor'] = $exteriorcolor;
            $data['interiorcolor'] = $interiorcolor;  
            $data['aging_days'] = $aging_days;
            return json_encode(array('status'=> true ,'data' => $data));
    }
}