<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\rto_master;
use App\Models\Carmodel;
use App\Models\Carvarient;
use App\Models\pricelist;
use App\Models\Branch;
use Auth, DB, Mail, Validator, File, DataTables, Exception;
use Maatwebsite\Excel\Facades\Excel; 
use App\Imports\ImportRTO;
use App\Exports\ExportRTO;
class rto_masterController extends Controller
{
     /** construct */
        public function __construct(){
            $this->middleware('permission:rto_master-create', ['only' => ['create']]);
            $this->middleware('permission:rto_master-edit', ['only' => ['edit']]);
            $this->middleware('permission:rto_master-view', ['only' => ['view']]);
            $this->middleware('permission:rto_master-delete', ['only' => ['delete']]);
        }
    /** construct */

    public function index(Request $request)
    {

        if($request->ajax()){
                //$data = rto_master::where('status','!=','deleted')->get();
                //$data = rto_master::select('rto_master.id as id','car_model.id as car_model_id','car_model.name as car_model_name','car_varient.id as car_varient_id','car_varient.name','pricelist_master.id as price_id','pricelist_master.price_list_name','rto_master.amount','rto_master.status','branches.name as branch_name','branches.id as branchid')->leftjoin('car_model','car_model.id','=','rto_master.car_model_id')->join('car_varient','car_varient.id','=','rto_master.car_varient_id')->leftjoin('pricelist_master','pricelist_master.id','=','rto_master.pricelist_id')->leftjoin('branches','branches.id','=','rto_master.branch_id')->get();
                //dd($data);
                $data = rto_master::select('rto_master.*');
                
                return Datatables::of($data)
                        ->addIndexColumn()
                        ->addColumn('action', function($data){
                            $return = '<div class="btn-group">';

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

                             if (auth()->user()->can('rto_master-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) . '">Deleted</a></li>
                                                </ul>';
                            }

                            $return .= '</div>';

                            return $return;
                        })

                        ->editColumn('rto_type', function ($data) {
                            if($data->rto_type == 'ev_six'){
                                return 'EV6';
                            } elseif($data->rto_type == 'csd'){
                                return 'CSD';
                            }else {
                                return ucwords(str_replace('_', ' ', $data->rto_type));
                            }        
                        })
                        ->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>';
                            }
                        })

                        ->rawColumns(['action' ,'percentage' ,'status'])
                        ->filter(function ($query) {
                                if (request()->filled('rto_type')) {
                                    $query->where('rto_master.rto_type', 'like', '%' . request()->get('rto_type') . '%');
                                }
                                if (request()->filled('rto_tax_individual')) {
                                    $query->where('rto_master.rto_tax_individual', request()->get('rto_tax_individual'));
                                }
                                if (request()->filled('totali_individual_charges')) {
                                    $query->where('rto_master.totali_individual_charges', request()->get('totali_individual_charges'));
                                }
                                if (request()->filled('rto_tax_company')) {
                                    $query->where('rto_master.rto_tax_company', request()->get('rto_tax_company'));
                                }
                                if (request()->filled('totalcharges')) {
                                    $query->where('rto_master.totalcharges', request()->get('totalcharges'));
                                }
                            })
                        ->make(true);
            }
            return view('rto_master.index');
    }

     /** create */
        public function create(Request $request){
            $carmodel = Carmodel::where(['status' => 'active'])->get();
            $carvarient = Carvarient::where(['status' => 'active'])->get();
            $branch = Branch::where(['status' => 'active'])->get();
            return view('rto_master.create')->with(['carmodel'=>$carmodel,'carvarient'=>$carvarient,'branch'=>$branch]);
        }
    /** create */   


    /** insert */
        public function insert(Request $request){
            // $priselist=implode(",",$request->pricelist);
            if($request->ajax()) { return true; }
            
            $total_individual_charges= $request->temporary_registration + $request->smart_card_fee +  $request->hypothecation + $request->fresh_permit + $request->new_registion; 

            $totalcharges= $request->temporary_registration + $request->smart_card_fee +  $request->hypothecation + $request->fresh_permit + $request->new_registion +  $request->crtem + $request->agent_charges + $request->rto_heandling_charges; 
            
            $crud = [
                'branch_id'=>$request->branch,
                'car_model_id' => $request->car_model,
                'car_varient_id' => $request->car_varient,
                'rto_type' => implode(",",$request->rto_type) ?? null,
                'rto_tax_individual' => $request->rto_tax_individual ?? null,
                'rto_tax_company' => $request->rto_tax_company ?? null,
                'temporary_registration' => $request->temporary_registration ?? null,
                'smart_card_fee' => $request->smart_card_fee ?? null,
                'hypothecation' => $request->hypothecation ?? null,
                'fresh_permit' => $request->fresh_permit ?? null,
                'new_registion' => $request->new_registion ?? null,
                'crtem' => $request->crtem ?? null,
                'agent_charges' => $request->agent_charges ?? null,
                'rto_heandling_charges' => $request->rto_heandling_charges ?? null,
                'totali_individual_charges' => $total_individual_charges ?? null,
                'totalcharges' => $totalcharges ?? null,
                'fuel_type' => $request->fuel_type ?? null,
                'below_1_lac' => $request->below_1_lac ?? null,
                '10_20_lac' => $request->input('10_20_lac') ?? null,
                'above_20_lac' => $request->above_20_lac ?? null,
                'parsing_percentage' => $request->parsing_percentage ?? null,
                'bh_parsing_validity' => $request->bh_parsing_validity ?? null,
                'total_parsing_validity' => $request->total_parsing_validity ?? null,
                '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 = rto_master::insertGetId($crud);

            if ($last_id) {
                return redirect()->route('rto_master')->with(['success' => 'Record inserted successfully']);
            } else {
                return redirect()->back()->with(['error'=>'Faild to insert Record!'])->withInput();
            }
        
        }

    /** insert */

    /** view */
        public function view(Request $request,$id){
            //dd($id);
            $id = base64_decode($request->id); 
           // $data = rto_master::select('rto_master.id','rto_master.pricelist_id','car_model.id as car_model_id','car_model.name as car_model_name','car_varient.id as car_varient_id','car_varient.name as car_variant_name','pricelist_master.id as price_id','pricelist_master.price_list_name','rto_master.amount','branches.name as branch_name','branches.id as branchid')->join('car_model','car_model.id','=','rto_master.car_model_id')->join('car_varient','car_varient.id','=','rto_master.car_varient_id')->join('pricelist_master','pricelist_master.id','=','rto_master.pricelist_id')->leftjoin('branches','branches.id','=','rto_master.branch_id')->where(['rto_master.id' => $id])->orWhereNotNull(['rto_master.branch_id'])->first();
            $data = rto_master::where(['id' => $id])->first();

            $pricelist = pricelist::where(['status' => 'active'])->get();
            $carmodel = Carmodel::where(['status' => 'active'])->get();
            $carvarient = Carvarient::where(['status' => 'active'])->get();
            $branch = Branch::where(['status' => 'active'])->get();
            return view('rto_master.view')->with(['data'=>$data,'query'=>$pricelist,'carmodel'=>$carmodel,'carvarient'=>$carvarient,'branch'=>$branch]);
        }
    /** view */

    /** edit */
        public function edit(Request $request)
        {
            $id = base64_decode($request->id); 
            //$data = rto_master::select('rto_master.id as id','rto_master.pricelist_id as pricelist_id','car_model.id as car_model_id','car_model.name as car_model_name','car_varient.id as car_varient_id','car_varient.name as car_variant_name','pricelist_master.id as price_id','pricelist_master.price_list_name','rto_master.amount','branches.name as branch_name','branches.id as branchid')->join('car_model','car_model.id','=','rto_master.car_model_id')->join('car_varient','car_varient.id','=','rto_master.car_varient_id')->join('pricelist_master','pricelist_master.id','=','rto_master.pricelist_id')->leftjoin('branches','branches.id','=','rto_master.branch_id')->where(['rto_master.id' => $id])->orWhereNotNull(['rto_master.branch_id'])->first();
            $data = rto_master::where(['id' => $id])->first();
            $carmodel = Carmodel::where(['status' => 'active'])->get();
            $pricelist = pricelist::where(['status' => 'active'])->get();
            $carvarient = Carvarient::where(['status' => 'active'])->get();
            $branch = Branch::where(['status' => 'active'])->get();
            return view('rto_master.edit')->with(['data'=>$data,'carmodel'=>$carmodel,'carvarient'=>$carvarient,'branch'=>$branch,'query'=>$pricelist]);
        }
    /** edit */

    /** update */
        public function update(Request $request){
            if($request->ajax()){ return true; }
                  //      $priselist=implode(",",$request->pricelist);
            $id = $request->id;
            
           $total_individual_charges= $request->temporary_registration + $request->smart_card_fee +  $request->hypothecation + $request->fresh_permit + $request->new_registion; 

           
           $totalcharges =  $request->temporary_registration + $request->smart_card_fee +  $request->hypothecation + $request->fresh_permit + $request->new_registion + $request->crtem + $request->agent_charges + $request->rto_heandling_charges; 
            
            $crud = [
               // 'amount' => $request->amount,
                // 'percentage' => $request->percentage,
                'branch_id'=>$request->branch,
                'car_model_id' => $request->car_model,
                'car_varient_id' => $request->car_varient,
                //'pricelist_id' => $priselist,
                'rto_type' => is_array($request->rto_type) ? implode(",", $request->rto_type) : $request->rto_type,
                'rto_tax_individual' => $request->rto_tax_individual ?? null,
                'rto_tax_company' => $request->rto_tax_company ?? null,
                'temporary_registration' => $request->temporary_registration ?? null,
                'smart_card_fee' => $request->smart_card_fee ?? null,
                'hypothecation' => $request->hypothecation ?? null,
                'fresh_permit' => $request->fresh_permit ?? null,
                'new_registion' => $request->new_registion ?? null,
                'crtem' => $request->crtem ?? null,
                'agent_charges' => $request->agent_charges ?? null,
                'rto_heandling_charges' => $request->rto_heandling_charges ?? null,
                 'totali_individual_charges' => $total_individual_charges ?? null,
                'totalcharges' => $totalcharges ?? null,
                'fuel_type' => $request->fuel_type ?? null,
                'below_1_lac' => $request->below_1_lac ?? null,
                '10_20_lac' => $request->input('10_20_lac') ?? null,
                'above_20_lac' => $request->above_20_lac ?? null,
                'parsing_percentage' => $request->parsing_percentage ?? null,
                'bh_parsing_validity' => $request->bh_parsing_validity ?? null,
                'total_parsing_validity' => $request->total_parsing_validity ?? null,
                '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::enableQueryLog();
            $update = rto_master::where(['id' => $id])->update($crud);
            // dd(DB::getQueryLog());
            if ($update){
                return redirect()->route('rto_master')->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 = rto_master::where(['id' => $id])->first();

            if (!empty($data)) {
                $update = rto_master::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 */

     /** car varient as per car model*/
    public function varient_carmodel(Request $request)
    {
        $model = $request->car_model;

        $query = Carmodel::select('car_varient.id','car_varient.name')->leftjoin('car_varient','car_varient.car_model','=','car_model.id')->where('car_varient.car_model',$model)->get();

        return view('rto_master.carvarientlist')->with(['query'=>$query]);
    }
    /** car varient as per car model*/ 

    /** VIN Number as per car varient */
    public function pricelistaspercarvarient(Request $request)
    {
        $car_varient = $request->car_varient;
        //dd($car_varient);
        $query = pricelist::select('pricelist_master.id','pricelist_master.price_list_name')->where('pricelist_master.car_variant',$car_varient)->get();
        //dd($query);
        return view('rto_master.pricelistaspercarvarient')->with(['query'=>$query]);
    }
    /** VIN Number as per car varient */
    
     /** Import */
        public function import(Request $request){
            $import = Excel::import(new ImportRTO(), $request->file('file'));  

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

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

            try {
                return Excel::download(new ExportRTO($slug), $name);
            }catch(\Exception $e){
                return redirect()->back()->with('error' ,$e->getMessage());
            }
        }
    /** Export */
    public function getdetails(Request $request){
          $response['data'] = rto_master::where(['rto_type' => $request->id])->first();
           $response['status'] = 200;
                $response['message'] = "RTO Type Details";
                return response($response, 200);
    }
}
