<?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\User;
use App\Models\Department;
use App\Models\discount;
use App\Models\Carmodel;
use App\Models\Lead;
use App\Exports\ExportDepartment;
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\ImportDepartment;

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

    public function index(Request $request){
        if($request->ajax()){
            $data =  DB::table('discount')
                ->select(
                    'discount.*',
                    '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, discount.branch_id)
                    ) as branch_city"),
                )
                ->leftJoin('branches', 'branches.id', '=', 'discount.branch_id')
                ->leftJoin('fule_type', 'fule_type.id', '=', 'discount.fuel_id')
                ->leftJoin('car_model', 'car_model.id', '=', 'discount.car_model_id')
                ->leftJoin('car_varient', 'car_varient.id', '=', 'discount.car_varient_id')
                ->orderBy('discount.id', 'desc');
            
                return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($data){
                    $return = '<div class="btn-group">';

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

                   if (auth()->user()->can('discounts-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('branch', function ($data) {
                    return $data->branch_city ?? '-';
                })
                ->editColumn('start_date', function ($data) {
                    return !empty($data->start_date)
                        ? \Carbon\Carbon::parse($data->start_date)->format('d-m-Y')
                        : '--';
                })
                ->editColumn('end_date', function ($data) {
                    return !empty($data->end_date)
                        ? \Carbon\Carbon::parse($data->end_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('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('discount.title', "like", "%".request()->get("title")."%");
                    }
                    if (request()->get('start_date',false)) {
                        $query->where('discount.start_date', "like", "%".request()->get("start_date")."%");
                    }
                    if (request()->get('end_date',false)) {
                        $query->where('discount.end_date', "like", "%".request()->get("end_date")."%");
                    }
                    if (request()->get('discount_year',false)) {
                        $query->where('discount.discount_year', "like", "%".request()->get("discount_year")."%");
                    } 
                    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('gm_discount',false)) {
                        $query->where('discount.gm_discount', "like", "%".request()->get("gm_discount")."%");
                    }
                    if (request()->get('bh_discount',false)) {
                        $query->where('discount.bh_discount', "like", "%".request()->get("bh_discount")."%");
                    }
                    if (request()->get('ceo_discount',false)) {
                        $query->where('discount.ceo_discount', "like", "%".request()->get("ceo_discount")."%");
                    }
                    if (request()->get('md_discount',false)) {
                        $query->where('discount.md_discount', "like", "%".request()->get("md_discount")."%");
                    }
                    if (request()->get('amount',false)) {
                        $query->where('discount.description', "like", "%".request()->get("description")."%");
                    }
                    if (request()->get('status',false)) {
                        $query->where('discount.status', "like", "%".request()->get("status")."%");
                    }
                })    
                ->make(true);
            }
        return view('discount.index');
    }

    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('discount.create')->with([
            'fuel_type'=>$fuel_type,
            'veriant'=>$veriant,
            'Carmodel_arr'=>$Carmodel_arr,
            'branch'=>$branch,
        ]);
    }

    public function insert(Request $request){
        if($request->ajax()){
            return true ;
        }
        
        $varient = $request->veriant;
        $varient_id = implode(',',$varient);
        $vin = (array) $request->vin;
        $vin_num = implode(',', $vin);
        
        $branch = (array) $request->branch_id;
        $branch_id = implode(',', $branch);
        
        $crud = [
            'title' => $request->title,
            'branch_id' => $branch_id ?? '',
            'car_model_id' => $request->car_name,
            'fuel_id' => $request->fuel_type,
            'car_varient_id' => $varient_id ?? '',
            'car_vin_number' => $vin_num ?? '' ,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'discount_year' => $request->discount_year ?? '',
            'description' => $request->description,
            'kec_discount' => $request->kec_discount,
            'tl_discount' => $request->tl_discount,
            'sm_discount' => $request->sm_discount,
            'gm_discount' => $request->gm_discount,
            'bh_discount' => $request->bh_discount,
            'ceo_discount' => $request->ceo_discount,
            'md_discount' => $request->md_discount,
            'status' => 'active',
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
        ];
        
        
        DB::beginTransaction();
        try {
            DB::enableQueryLog();
            $last_id = discount::insertGetId($crud);
            if ($last_id) {
                
                DB::commit();
                return redirect()->route('discount')->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();
        }
    }

    public function view(Request $request){  
        $id = base64_decode($request->id);
                                
        $data = discount::select(
            'discount.*',
            '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',
            DB::raw('GROUP_CONCAT(branches.id) as branch_ids'),
            DB::raw('GROUP_CONCAT(branches.name) as branch_names')
        )
        ->leftjoin('fule_type','fule_type.id','=','discount.fuel_id')
        ->leftjoin('car_model','car_model.id','=','discount.car_model_id')
        ->leftjoin('car_varient','car_varient.id','=','discount.car_varient_id')
        ->leftJoin('branches', function ($join) {
            $join->on(
                DB::raw('FIND_IN_SET(branches.id, discount.branch_id)'),
                '>',
                DB::raw('0')
            );
        })
        ->where(['discount.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('discount.view')->with(['data' => $data,'fuel_type'=>$fuel_type,'veriant'=>$veriant,'Carmodel_arr'=>$Carmodel_arr,'branch'=>$branch]);
    }

    public function edit(Request $request){
        $id = base64_decode($request->id);
        
        $data = discount::select(
            'discount.*',
            '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',
            DB::raw('GROUP_CONCAT(branches.id) as branch_ids'),
            DB::raw('GROUP_CONCAT(branches.name) as branch_names')
        )
        ->leftjoin('fule_type','fule_type.id','=','discount.fuel_id')
        ->leftjoin('car_model','car_model.id','=','discount.car_model_id')
        ->leftjoin('car_varient','car_varient.id','=','discount.car_varient_id')
        ->leftJoin('branches', function ($join) {
            $join->on(
                DB::raw('FIND_IN_SET(branches.id, discount.branch_id)'),
                '>',
                DB::raw('0')
            );
        })
        ->where(['discount.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('discount.edit')->with(['data' => $data,'fuel_type'=>$fuel_type,'veriant'=>$veriant,'Carmodel_arr'=>$Carmodel_arr,'branch'=>$branch]);
    }
 
    public function update(Request $request){
        if($request->ajax()){
            return true ;
        }
        
        $varient = $request->veriant;
        $varient_id = implode(',',$varient);
        $vin = (array) $request->vin;
        $vin_num = implode(',', $vin);
        
        $branch = (array) $request->branch_id;
        $branch_id = implode(',', $branch);
        
        $crud = [
            'title' => $request->title,
            'branch_id' => $branch_id ?? '',
            'car_model_id' => $request->car_name,
            'fuel_id' => $request->fuel_type,
            'car_varient_id' => $varient_id ?? '',
            'car_vin_number' => $vin_num ?? '' ,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'discount_year' => $request->discount_year ?? '',
            'description' => $request->description,
            'kec_discount' => $request->kec_discount,
            'tl_discount' => $request->tl_discount,
            'sm_discount' => $request->sm_discount,
            'gm_discount' => $request->gm_discount,
            'bh_discount' => $request->bh_discount,
            'ceo_discount' => $request->ceo_discount,
            'md_discount' => $request->md_discount,
            'status' => 'active',
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => auth()->user()->id   
        ];
       
        DB::beginTransaction();
        try {
            DB::enableQueryLog();
            $update = discount::where(['id' => $request->id])->update($crud);
            if($update){
                DB::commit();
                return redirect()->route('discount')->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();
        }
    }

    public function change_status(Request $request){
        if (!$request->ajax()) { exit('No direct script access allowed'); }
            
            $id = base64_decode($request->id);
            $data = discount::where(['id' => $id])->first();
       
            if(!empty($data)){
                $update = discount::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]);
            }
    }

    public function car_vin_asper_variant(Request $request){

        $varient = $request->varient;
        $data =[];
        $vin_num = [];
        
        if (!is_array($varient)) {
            $varient = explode(',', $varient);
        }

        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));
    }

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

        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;
        }
        
        $data['price'] = $price;
        $data['exteriorcolor'] = $exteriorcolor;
        $data['interiorcolor'] = $interiorcolor;  
        $data['aging_days'] = $aging_days;
        return json_encode(array('status'=> true ,'data' => $data));
    }
}