<?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\Inventory;
use App\Models\Product;
use App\Models\pricelist;
use App\Models\Transmission;
use App\Models\Carvarient;
use App\Models\Colortone;
use App\Models\ExtandWarranty; 
use App\Models\RSA;
use App\Models\Accessory;
use App\Models\Fasttag;
use App\Models\OtherOne;
use App\Models\OtherTwo;
use App\Models\OBF;
use App\Models\Mcp;
use App\Models\Order;
use App\Models\Carmodel;
use App\Models\Fuletype;
use App\Models\rto_master;
use App\Exports\ExportPriceList;
use App\Imports\ImportPriceList;
use App\Http\Requests\InventoryRequest;
use App\Http\Requests\InventoryAcceptRequest;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\User;
use App\Models\Interiorcolor;
use App\Models\Exteriorcolor;

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

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

    /** index */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            /*$data = DB::table('pricelist_master')
                ->select('*')
                ->get();*/

              /*  error_reporting(E_ALL);
            ini_set('display_errors', 1);*/        
            $data = DB::table('pricelist_master')
            ->select(
                'pricelist_master.*',
                'car_model.name as product',
                DB::raw("CONCAT(UCASE(LEFT(REPLACE(pricelist_master.rto_type, '_', ' '), 1)), 
                LOWER(SUBSTRING(REPLACE(pricelist_master.rto_type, '_', ' '), 2))) AS rtotype"),
                DB::raw("COALESCE(MAX(orders.invoice_date), '--') as invoice_date"),
                // 'car_varient.name as car_variant_name',
                DB::raw("CONCAT(car_varient.name, ' - ', tex_master.gst, ' - ',tex_master.compensation_cess,  ' %') AS car_variant_name"),
                'colortone.name as color_type',
                'transmission.name as t_name',
                'insurance.name as insurance_nm',
                'fasttags.brand_name as fasttags_nm',
                'rsa.name as rsa_nm',
                'extand_warranties.years as ew_name',
                'mcp.name as mcp_nm',
                // 'branches.name as location',
                DB::raw("(SELECT GROUP_CONCAT(name SEPARATOR ', ') FROM branches WHERE FIND_IN_SET(branches.id, pricelist_master.branch_id)) as location"),
                'other_one.name as other_1',
                'other_two.name as other_2',
                'fule_type.title as fuel_type',
                'obf.booking_date'
            )
            ->leftJoin('obf','pricelist_master.id','obf.pricelist_id')
            ->leftJoin('car_model', 'car_model.id', '=', 'pricelist_master.car_model')
            ->leftJoin('transmission', 'transmission.id', '=', 'pricelist_master.transmission')
            ->leftJoin('car_varient', 'car_varient.id', '=', 'pricelist_master.car_variant')
            ->leftJoin('colortone', 'colortone.id', '=', 'pricelist_master.colour_type')
            ->leftJoin('fule_type', 'fule_type.id', '=', 'pricelist_master.fule_type')
            ->leftJoin('insurance', 'insurance.id', '=', 'pricelist_master.insurance')
            ->leftJoin('fasttags', 'fasttags.id', '=', 'pricelist_master.fasttag')
            ->leftJoin('rsa', 'rsa.id', '=', 'pricelist_master.rsa_master')
            ->leftJoin('extand_warranties', 'extand_warranties.id', '=', 'pricelist_master.extended_warranty')
            // ->leftJoin('branches', 'branches.id', '=', 'pricelist_master.branch_id')
            ->leftJoin('mcp', 'mcp.id', '=', 'pricelist_master.convinience_program')
            ->leftjoin('orders','orders.obf_id','=','obf.id')
            ->leftJoin('other_one', 'other_one.id', '=', 'pricelist_master.other_details_1')
            ->leftJoin('other_two', 'other_two.id', '=', 'pricelist_master.other_details_2')
            ->leftjoin('tex_master', 'car_varient.tex_master_id', '=', 'tex_master.id')
            ->where('pricelist_master.status', '!=', 'deleted')
            ->groupBy('pricelist_master.id')
            ->orderBy('pricelist_master.id', 'desc');

            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function ($data) {
                    $return = '<div class="btn-group">';

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

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

                    // if (auth()->user()->can('inventory-delete')) {
                    //     if ($data->status == 'pdi_hold') {
                    //         $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">';

                    //         $return .= '<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>';
                    //     } else if ($data->status == 'sold') {
                    //         $return .= '';
                    //     } else {
                    //         $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">';

                    //         if ($data->status == 'active') {
                    //             $return .= '<li><a class="dropdown-item" href="' . route('inventory.accept', ['id' => base64_encode($data->id)]) . '">Assign</a></li>';
                    //         }

                    //         $return .= '<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>';
                    //     }
                    // }


                    if(auth()->user()->can('pricelist-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('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-info">PDI Hold</span>';
                //     } else if ($data->status == 'sold') {
                //         return '<span class="badge badge-pill badge-danger">Sold</span>';
                //     } else {
                //         return '-';
                //     }
                // })
                ->editColumn('booking_date', function($data) {
                            return (!empty($data->booking_date))
                                ? \Carbon\Carbon::parse($data->booking_date)->format('d-m-Y')
                                : '--';
                        })
                ->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 '-';
                    }
                }) 

                ->editColumn('created_at', function ($data) {
                    return date("d-m-Y",strtotime($data->created_at));
                })   

                ->rawColumns(['action','status','created_at'])
                ->filter(function ($query){
                            if ($dateRange = request()->get('booking_date', false)) {
                                        $dates = explode(' to ', $dateRange);
                                        if (count($dates) === 2) {
                                            try {
                                                $start = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[0]))->startOfDay()->format('Y-m-d');
                                                $end = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[1]))->endOfDay()->format('Y-m-d');
                                                $query->whereBetween('obf.booking_date', [$start, $end]);
                                            } catch (\Exception $e) {
                                                \Log::error('Invalid date range format for booking_date filter', [
                                                    'input' => $dateRange,
                                                    'error' => $e->getMessage()
                                                ]);
                                            }
                                        }
                                    }
                            if (request()->get('price_list_name', false)) {
                                $query->where('pricelist_master.price_list_name', 'like', '%' . request()->get('price_list_name') . '%');
                            }
                            if (request()->get('is_csd', false)) {
                                $query->where('pricelist_master.is_csd', 'like', '%' . request()->get('is_csd') . '%');
                            }
                            if (request()->get('rtotype', false)) {
                                $query->where('pricelist_master.rto_type', 'like', '%' . request()->get('rtotype') . '%');
                            }
                            if (request()->get('product', false)) {
                                $query->where('car_model.name', 'like', '%' . request()->get('product') . '%');
                            }
                            if (request()->get('fuel_type', false)) {
                                $query->where('fule_type.title', 'like', '%' . request()->get('fuel_type') . '%');
                            }
                            if (request()->get('car_variant_name', false)) {
                                $query->where('car_varient.name', 'like', '%' . request()->get('car_variant_name') . '%');
                            }
                            if (request()->get('rto_custome_handling_charges', false)) {
                                $query->where('pricelist_master.rto_custome_handling_charges', 'like', '%' . request()->get('rto_custome_handling_charges') . '%');
                            }
                            if (request()->get('color_type', false)) {
                                $query->where('colortone.name', 'like', '%' . request()->get('color_type') . '%');
                            }
                            if (request()->get('location', false)) {
                                $query->where('branches.name', 'like', '%' . request()->get('location') . '%');
                            }
                            if (request()->get('t_name', false)) {
                                $query->where('transmission.name', 'like', '%' . request()->get('t_name') . '%');
                            }
                            if (request()->get('basic', false)) {
                                $query->where('pricelist_master.basic', 'like', '%' . request()->get('basic') . '%');
                            }
                            if (request()->get('csd_selling_price', false)) {
                                $query->where('pricelist_master.csd_selling_price', 'like', '%' . request()->get('csd_selling_price') . '%');
                            }
                            if (request()->get('ls_order_amount', false)) {
                                $query->where('pricelist_master.ls_order_amount', 'like', '%' . request()->get('ls_order_amount') . '%');
                            }
                            if (request()->get('gst_percentage', false)) {
                                $query->where('pricelist_master.gst_percentage', 'like', '%' . request()->get('gst_percentage') . '%');
                            }
                            if (request()->get('gst_amount', false)) {
                                $query->where('pricelist_master.gst_amount', 'like', '%' . request()->get('gst_amount') . '%');
                            }
                            if (request()->get('cess_percentage', false)) {
                                $query->where('pricelist_master.cess_percentage', 'like', '%' . request()->get('cess_percentage') . '%');
                            }
                            if (request()->get('cess_amount', false)) {
                                $query->where('pricelist_master.cess_amount', 'like', '%' . request()->get('cess_amount') . '%');
                            }
                            if (request()->get('ex_showroom_price', false)) {
                                $query->where('pricelist_master.ex_showroom_price', 'like', '%' . request()->get('ex_showroom_price') . '%');
                            }
                            if (request()->get('tcs', false)) {
                                $query->where('pricelist_master.tcs', 'like', '%' . request()->get('tcs') . '%');
                            }
                            if (request()->get('registration_individual_charges', false)) {
                                $query->where('pricelist_master.registration_individual_charges', 'like', '%' . request()->get('registration_individual_charges') . '%');
                            }
                            if (request()->get('registration_corporate_charges', false)) {
                                $query->where('pricelist_master.registration_corporate_charges', 'like', '%' . request()->get('registration_corporate_charges') . '%');
                            }
                            if (request()->get('insurance', false)) {
                                $query->where('pricelist_master.insurance', 'like', '%' . request()->get('insurance') . '%');
                            }
                            if (request()->get('fasttags_nm', false)) {
                                $query->where('fasttags.brand_name', 'like', '%' . request()->get('fasttags_nm') . '%');
                            }
                            if (request()->get('on_road_individual_charges', false)) {
                                $query->where('pricelist_master.on_road_individual_charges', 'like', '%' . request()->get('on_road_individual_charges') . '%');
                            }
                            if (request()->get('on_road_corporate_charges', false)) {
                                $query->where('pricelist_master.on_road_corporate_charges', 'like', '%' . request()->get('on_road_corporate_charges') . '%');
                            }
                            if (request()->get('rsa_nm', false)) {
                                $query->where('rsa.name', 'like', '%' . request()->get('rsa_nm') . '%');
                            }
                            if (request()->get('ew_name', false)) {
                                $query->where('extand_warranties.years', 'like', '%' . request()->get('ew_name') . '%');
                            }
                            if (request()->get('mcp_nm', false)) {
                                $query->where('mcp.name', 'like', '%' . request()->get('mcp_nm') . '%');
                            }
                            if (request()->get('other_1', false)) {
                                $query->where('other_one.name', 'like', '%' . request()->get('other_1') . '%');
                            }
                            if (request()->get('other_2', false)) {
                                $query->where('other_two.name', 'like', '%' . request()->get('other_2') . '%');
                            }
                            if (request()->get('on_road_price_individual', false)) {
                                $query->where('pricelist_master.on_road_price_individual', 'like', '%' . request()->get('on_road_price_individual') . '%');
                            }
                            if (request()->get('on_road_price_corporate', false)) {
                                $query->where('pricelist_master.on_road_price_corporate', 'like', '%' . request()->get('on_road_price_corporate') . '%');
                            }
                            if (request()->get('created_at', false)) {
                                $date = \Carbon\Carbon::parse(request()->get('created_at'))->format('Y-m-d');
                                $query->whereDate('pricelist_master.created_at', $date);
                            }
                            if (request()->get('invoice_date',false)) {
                                $query->where('orders.invoice_date', "like", "%".request()->get("invoice_date")."%");
                            }
                            if (request()->get('status', false)) {
                                $query->where('pricelist_master.status', 'like', '%' . request()->get('status') . '%');
                            }
                        })   
                ->make(true);
        }
        
            
            
            $customer_name = OBF::select('obf.id','obf.customer_name')->get();
            $kec_name = User::select(DB::raw("CONCAT(users.first_name,' ',users.last_name) As kec_name",'users.id'))->get();
            $product = Carmodel::select('name','id')->where('status','active')->get();
                
            $price = OBF::select('on_road_price','id')->get();
            $varient = Carvarient::select('name','id')->where('status','active')->get();
            $branch = Branch::select('name','id')->where('status','active')->get();
                
                
        
        
        return view('pricelist.index')->with(['product'=>$product,'price'=>$price,'varient'=>$varient,'branch'=>$branch]);
    }
    /** index */

    /** create */
    public function create(Request $request)
    {   
        $accessory = Accessory::select('id' , 'name' ,'price')->where(['status' => 'active'])->get();
        $fasttag = Fasttag::select('id' , 'brand_name' ,'amount')->where(['status' => 'active'])->get();

        $tone = Colortone::where(['status' => 'active'])->get();  
        
        $Cardata = Product::select('car_model.name as car_name','products.id as car_id','car_varient.name as varient_name', 'exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
                   ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                    ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                    ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
                    ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
                    ->where('products.status', '=', 'active')
                    ->get();
        $extanded_warranty = ExtandWarranty::select('id' , 'years' ,'amount')->where(['status' => 'active'])->get();

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

         $rsa = RSA::where(['status' => 'active','deleted_at' => 0])->get();
         
         $Branch_data = Branch::where(['status' => 'active'])->get();

         $transmission = Transmission::where(['status' => 'active'])->get();  
         
         $mcp = Mcp::where(['status' => 'active'])->get();  
            
         $OtherOne = OtherOne::where(['status' => 'active'])->get();  
            
         $OtherTwo = OtherTwo::where(['status' => 'active'])->get(); 
         $fuel_type = Fuletype::select('*')->where('status','=','active')->get();
        return view('pricelist.create')->with(['Cardata' => $Cardata,'accessory' => $accessory ,'fasttag' => $fasttag,'Carmodel_arr' => $Carmodel_arr,'Branch_data' => $Branch_data, 'transmission' => $transmission, 'tone' => $tone, 'extanded_warranty' => $extanded_warranty, 'rsa' => $rsa, 'OtherOne' => $OtherOne,'OtherTwo' => $OtherTwo, 'mcp' => $mcp,'fuel_type'=>$fuel_type]); 
    }
    /** create */



    /** Car Fuel Type **/
        public function car_fuel_type(Request $request){ 
            $id = ($request->id);

            $fuel_type_id = Carvarient::select('fule_type')
            ->where('id', $id)
            ->where('status', '=', 'active')
            ->first();

            $fule_type_get = 0;
            if(!empty($fuel_type_id)){
                $fule_type_get = $fuel_type_id->fule_type;
            }

            $fule_data = Fuletype::select('*')->where('status', '=', 'active')->get();

            $ExtandWarranty_arr = [];

            $ExtandWarranty_data = ExtandWarranty::where(['car_model' => $request->model_id,'fule_type' => $fule_type_get,'status' => 'active'])->orderBy('years', 'asc')->get();
            foreach ($ExtandWarranty_data as $value) {
                $arr_sub = [];
                $arr_sub['id'] = $value->id;
                $arr_sub['amount'] = $value->amount;
                $arr_sub['years'] = $value->years;
                $ExtandWarranty_arr[] = $arr_sub;                    
            }
            
            return json_encode(array('status'=> true ,'data' => $fule_data,'ExtandWarranty_arr' => $ExtandWarranty_arr, 'id' => $fuel_type_id));
        }
    /** Car Fuel Type **/



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

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

        if(empty($request->branch_id) && $request->branch_id == ''){
             return redirect()->back()->with('error', 'Please select Branch Name')->withInput();
        }

        if(empty($request->fasttag) && $request->fasttag == ''){
             return redirect()->back()->with('error', 'Please select Fasttag')->withInput();
        }

        if(empty($request->detail_field)){
            $request->detail_field = [];
        }

        if(empty($request->value_field)){
            $request->value_field = [];
        }

        if(empty($request->other_details_1)){
            $request->other_details_1 = [];
        }

        if(empty($request->other_details_2)){
            $request->other_details_2 = [];
        }

        $detail_value_arr = [];
        for ($i=0; $i < count($request->detail_field); $i++) { 
           if($request->detail_field[$i] != '' && $request->value_field[$i] != ''){
                $detail_value_sub_arr = [];
                $detail_value_sub_arr['detail_field'] = $request->detail_field[$i];
                $detail_value_sub_arr['value_field'] = $request->value_field[$i]; 
                $detail_value_arr[] = $detail_value_sub_arr; 
           }           
        }

        $detail_value_arr_json = json_encode($detail_value_arr);

        /*echo "<pre>";
        print_r($detail_value_arr);
        echo $detail_value_arr_json;
        die('stop');*/

     
        $branchIds = implode(',', $request->input('branch_id'));
        $data = [
            'price_list_name' => $request->price_list_name ?? NULL,
            'is_csd' => $request->is_csd == 'Yes'? 'Yes':'No',
            'rto_type' => implode(" ,",$request->rto_type) ?? null,
            'car_model' => $request->car_name ?? NULL,
            'fule_type' => $request->fule_type ?? NULL,
            'car_variant' => $request->veriant ?? NULL,
            'rto_custome_handling_charges' =>$request->rto_custome_handling_charges,
            'colour_type' => $request->color_tone ?? NULL,
            'branch_id' => $branchIds ?? NULL,
            'transmission' => $request->transmission ?? NULL,
            'basic' => $request->basic ?? NULL,
            'csd_selling_price' => $request->csd_selling_price ?? null,
            'ls_order_amount' =>$request->ls_order_amount ?? null,
            'outstanding_amount' => $request->outstanding_amount ?? null,
            'gst_percentage' => $request->gst_percentage ?? NULL,
            'gst_amount' => $request->gst_amount ?? NULL,
            'cess_percentage' => $request->cess_percentage ?? NULL,
            'cess_amount' => $request->cess_amount ?? NULL,
            'ex_showroom_price' => $request->ex_showroom_price ?? NULL,
            'tcs' => $request->tcs ?? NULL,
            'registration_individual_charges' => $request->registration_individual_charges ?? NULL,
            'registration_corporate_charges' => $request->registration_corporate_charges ?? NULL,
            'insurance' => $request->insurance ?? NULL,
            'fasttag' => $request->fasttag ?? NULL,
            'on_road_individual_charges' => $request->on_road_individual_charges ?? NULL,
            'on_road_corporate_charges' => $request->on_road_corporate_charges ?? NULL,
            'total_road_individual_charges' => $request->total_road_individual_charges ?? NULL,
            'total_road_corporate_charges' => $request->total_road_corporate_charges ?? NULL,
            'rsa_master' => $request->rsa_master ?? NULL,
            'other_details_1' => implode(" ,",$request->other_details_1) ?? null,
            'other_details_2' => implode(" ,",$request->other_details_2) ?? null,
            'extended_warranty' => $request->extended_warranty ?? NULL,
            'convinience_program' => $request->convinience_program ?? NULL,
            'detail_value' => $detail_value_arr_json,
            'on_road_price_individual' => $request->on_road_price_individual ?? NULL,
            'on_road_price_corporate' => $request->on_road_price_corporate ?? NULL,
            'product_id' => $request->product_id ?? NULL,
            'created_at' => date('Y-m-d H:i:s'),
            // 'statutory_charges' => $request->statutory_charges ?? NULL,
            //'accessories_kit' => implode(" ,",$request->accessories_kit) ?? null,      
        ];

        $last_id = DB::table('pricelist_master')->insertGetId($data);

        if ($last_id)
            return redirect()->route('pricelist')->with('success', 'Record inserted successfully');
        else
            return redirect()->back()->with('error', 'Failed to insert record')->withInput();
    }
    /** insert */

    /** view */
     public function view(Request $request)
    {
        $id = base64_decode($request->id);

        $categories = Category::select('id', 'name')->where(['status' => 'active'])->get();
        $branches = Branch::select('id', 'name')->where(['status' => 'active'])->get();
        $data = Inventory::where(['id' => $id])->first();

        return view('inventory.view')->with(['data' => $data, 'branches' => $branches, 'categories' => $categories]);
    }
    /** view */

    /** edit */
    public function edit(Request $request)
    {
        $id = base64_decode($request->id);

        // var_dump($id);
        
        $tone = Colortone::where(['status' => 'active'])->get();  
        $data = DB::table('pricelist_master')->where(['id' => $id])->first();
        $mcp = Mcp::where(['status' => 'active'])->get(); 

        $extanded_warranty = ExtandWarranty::select('id' , 'years' ,'amount')->where(['status' => 'active'])->get();

        $rsa = RSA::where(['status' => 'active','deleted_at' => 0])->get();
        /*$Carmodel = Product::select('car_model.name as car_name','products.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
                   ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                    ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                    ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
                    ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
                    ->where('products.status', '=', 'active')
                    ->get();*/

        // $fule = pricelist::select('*','fule_type.title as fule_type')
        // ->leftjoin('fule_type', 'fule_type.id', 'pricelist_master.fule_type')
        // ->where('pricelist_master.fule_type', '=', $data->fule_type)
        // ->first();

        $fule_data = Fuletype::select('*')->where('status', '=', 'active')->get();


                    // dd($data->product_id);

        $Product_data = Product::where('id',$data->product_id)->where('status', '=', 'active')->first();  

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

        $accessory = Accessory::select('id' , 'name' ,'price')->where(['status' => 'active'])->get();
        $fasttag = Fasttag::select('id' , 'brand_name' ,'amount')->where(['status' => 'active'])->get();

        $Branch_data = Branch::where(['status' => 'active'])->get();  
        
        // $car_variant = Carvarient::where(['status' => 'active','car_model' => $data->car_model,'fule_type'=>$data->fule_type])->get();  
        $car_variant = Carvarient::where([
            'car_model' => $data->car_model,
            'fule_type'=>$data->fule_type,
            'car_varient.status' => 'active'
        ])
        ->leftJoin('tex_master', 'car_varient.tex_master_id', '=', 'tex_master.id')
        ->where('tex_master.status', 'active')
        ->select('car_varient.id', 'car_varient.name', 'tex_master.gst')
        ->get();
        
        $transmission = Transmission::where(['status' => 'active'])->get();  

        $OtherOne = OtherOne::where(['status' => 'active'])->get();  
            
        $OtherTwo = OtherTwo::where(['status' => 'active'])->get();
        $branchIds = explode(',', $data->branch_id);
        
        $convinience_program = Mcp::where(['status' => 'active'])->get();  
        
        $rto_master = rto_master::select('rto_master.*')->where('rto_type',$data->rto_type)->first();
        
        
        return view('pricelist.edit')->with(['data' => $data,'car_variant'=>$car_variant, 'accessory' => $accessory ,'fasttag' => $fasttag,'Carmodel_arr' => $Carmodel_arr,'Branch_data' => $Branch_data, 'transmission' => $transmission, 'tone' => $tone, 'mcp' => $mcp, 'extanded_warranty' => $extanded_warranty, 'rsa' => $rsa, 'OtherOne' => $OtherOne, 'OtherTwo' => $OtherTwo, 'fule_data' => $fule_data,'branchIds' => $branchIds,'convinience_program'=>$convinience_program,'rto_master'=>$rto_master]);
    }
    /** edit */
    
    
    /** inventorystock */
    public function inventorystock(Request $request)
    {
        if ($request->ajax()) {
            $data = DB::table('inventory as i')
                
                ->select('b.name as branch',DB::raw('count(i.id) as total_stock'))
                ->join('branches as b', 'b.id', 'i.branch_id')
               
                ->groupby('b.id')
               
                ->get();

            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function ($data) {
                    $return = '<div class="btn-group">';

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

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

                    //     }
                    // }

                    // if (auth()->user()->can('inventory-delete')) {
                    //     if ($data->status == 'pdi_hold') {
                    //         $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">';

                    //         $return .= '<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>';
                    //     } else if ($data->status == 'sold') {
                    //         $return .= '';
                    //     } else {
                    //         $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">';

                    //         if ($data->status == 'active') {
                    //             $return .= '<li><a class="dropdown-item" href="' . route('inventory.accept', ['id' => base64_encode($data->id)]) . '">Assign</a></li>';
                    //         }

                    //         $return .= '<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('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-info">PDI Hold</span>';
                //     } else if ($data->status == 'sold') {
                //         return '<span class="badge badge-pill badge-danger">Sold</span>';
                //     } else {
                //         return '-';
                //     }
                // })
                // ->rawColumns(['action', 'status'])
                ->make(true);
        }
        return view('inventory.branchstock');
    }
    /** inventorystock */

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

        /*var_dump($request->accessories_kit);
        die('s');*/

       /* if(empty($request->accessories_kit)){
            $request->accessories_kit = [];
        }*/

        if(empty($request->detail_field)){
            $request->detail_field = [];
        }

        if(empty($request->value_field)){
            $request->value_field = [];
        }

        if(empty($request->other_details_1)){
            $request->other_details_1 = [];
        }

        if(empty($request->other_details_2)){
            $request->other_details_2 = [];
        }

        $detail_value_arr = [];
        for ($i=0; $i < count($request->detail_field); $i++) { 
           if($request->detail_field[$i] != '' && $request->value_field[$i] != ''){
                $detail_value_sub_arr = [];
                $detail_value_sub_arr['detail_field'] = $request->detail_field[$i];
                $detail_value_sub_arr['value_field'] = $request->value_field[$i]; 
                $detail_value_arr[] = $detail_value_sub_arr; 
           }           
        }

        $detail_value_arr_json = json_encode($detail_value_arr);

        $branchIds = implode(',', $request->input('branch_id'));
        $data = [
            'price_list_name' => $request->price_list_name ?? NULL,
            'is_csd' => $request->is_csd == 'Yes'? 'Yes':'No',
            'rto_type' => implode(" ,",$request->rto_type) ?? null,
            'car_model' => $request->car_name ?? NULL,
            'fule_type' => $request->fule_type ?? NULL,
            'car_variant' => $request->veriant ?? NULL,
            'rto_custome_handling_charges' =>$request->rto_custome_handling_charges,
            'colour_type' => $request->color_tone ?? NULL,
            'branch_id' => $branchIds ?? NULL,
            'transmission' => $request->transmission ?? NULL,
            'basic' => $request->basic ?? NULL,
            'csd_selling_price' => $request->csd_selling_price ?? null,
            'ls_order_amount' =>$request->ls_order_amount ?? null,
            'outstanding_amount' => $request->outstanding_amount ?? null,
            'gst_percentage' => $request->gst_percentage ?? NULL,
            'gst_amount' => $request->gst_amount ?? NULL,
            'cess_percentage' => $request->cess_percentage ?? NULL,
            'cess_amount' => $request->cess_amount ?? NULL,
            'ex_showroom_price' => $request->ex_showroom_price ?? NULL,
            'tcs' => $request->tcs ?? NULL,
            'registration_individual_charges' => $request->registration_individual_charges ?? NULL,
            'registration_corporate_charges' => $request->registration_corporate_charges ?? NULL,
            'insurance' => $request->insurance ?? NULL,
            'fasttag' => $request->fasttag ?? NULL,
            'on_road_individual_charges' => $request->on_road_individual_charges ?? NULL,
            'on_road_corporate_charges' => $request->on_road_corporate_charges ?? NULL,
            'total_road_individual_charges' => $request->total_road_individual_charges ?? NULL,
            'total_road_corporate_charges' => $request->total_road_corporate_charges ?? NULL,
            'rsa_master' => $request->rsa_master ?? NULL,
            'other_details_1' => implode(" ,",$request->other_details_1) ?? null,
            'other_details_2' => implode(" ,",$request->other_details_2) ?? null,
            'extended_warranty' => $request->extended_warranty ?? NULL,
            'convinience_program' => $request->convinience_program ?? NULL,
            'detail_value' => $detail_value_arr_json,
            'on_road_price_individual' => $request->on_road_price_individual ?? NULL,
            'on_road_price_corporate' => $request->on_road_price_corporate ?? NULL,
            'product_id' => $request->product_id ?? NULL,
            'created_at' => date('Y-m-d H:i:s'),
            // 'statutory_charges' => $request->statutory_charges ?? NULL,
            //'accessories_kit' => implode(" ,",$request->accessories_kit) ?? null,
        ];
        
        // \DB::enableQueryLog(); 
        $update = DB::table('pricelist_master')->where(['id' => $request->id])->update($data);

        /*var_dump($update);    
        die('s');*/

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

        if ($update)
            return redirect()->route('pricelist')->with('success', 'Record updated successfully');
        else
            return redirect()->back()->with('error', 'Failed 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 = pricelist::where(['id' => $id])->first();

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

      /** Import */
        public function import(Request $request){
            $import = Excel::import(new ImportPriceList(), $request->file('file'));    
            if($import){
                Excel::store(new ImportPriceList(), 'Pricelist_'.Date('YmdHis').'.xlsx' ,'excel_import');
                return redirect()->route('pricelist')->with('sucess' ,'File Imported Sucessfully');
            }
        }
    /** Import */
    
    /** Export */
        public function export(Request $request){
            $slug = $request->slug;
            $name = 'Pricelist'.Date('YmdHis').'.xlsx';
    
            try {
                return Excel::download(new ExportPriceList($slug), $name);
            }catch(\Exception $e){
                return redirect()->back()->with('error', $e->getMessage());
            }
        }
    /** Export */

    /** accept */
    public function accept(Request $request, $id = '')
    {
        if (isset($id) && $id != '' && $id != null)
            $id = base64_decode($id);
        else
            return redirect()->back()->with('error', 'Something went wrong');
        $product = Product::select('products.id')->leftjoin('inventory', 'products.name', 'inventory.name')->where(['inventory.id' => $id])->get();

        if ($product->isNotEmpty()) {
            $product = $product->toArray();
            $ids = array_map(
                function ($element) {
                    return $element['id'];
                },
                $product
            );

            $data = OBF::select('obf.id', 'obf.customer_name as name')->where(['obf.status' => 'account_accepted'])->whereIn('obf.product_id', $ids)->get();

            if ($data->isNotEmpty()) {
                return view('inventory.accept')->with(['data' => $data, 'id' => $id]);
            } else {
                return redirect()->route('inventory')->with('error', 'No Data Found In User!');
            }
        } else {
            return redirect()->route('inventory')->with('error', 'No Data Found For This Car!');
        }
    }
    /** accept */

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

        DB::beginTransaction();
        try {
            $inventory = Inventory::where(['id' => $request->id])->update(['status' => 'sold', 'updated_by' => auth()->user()->id, 'updated_at' => date('Y-m-d H:i:s')]);

            if (!$inventory)
                return redirect()->back()->with(['error' => 'something went wrong, please try later']);

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

            if (!$obf)
                return redirect()->back()->with(['error' => 'something went wrong, please try later']);

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

            if (!$order)
                return redirect()->back()->with(['error' => 'something went wrong, please try later']);

            DB::commit();
            return redirect()->route('inventory')->with(['success' => 'Assign completed']);
        } catch (\Throwable $th) {
            DB::rollback();
            return redirect()->back()->with('error', 'something went wrong, please try again later')->withInput();
        }
    }
    /** accepted */
    /**carvarient */
        public function car_drop_down_get(Request $request){ 
            $id = ($request->id);

            $data = [];

            $Carvarient_arr = [];
            if($request->option_table == 'rsa'){
                $RSA = RSA::where(['car_model' => $request->id,'status' => 'active'])->get();
                
                foreach ($RSA as $value) {
                    $color_data = [];
                    $color_data['id'] = $value->id;
                    $color_data['name'] = $value->name;
                    $color_data['amount'] = $value->amount;
                    $Carvarient_arr[] = $color_data;
                }  
            }
            $data['Carvarient_arr'] = $Carvarient_arr;

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

    /** Get Fule Type */
        public function car_fuel_type_get(Request $request){ 
            $id = ($request->id);

            $fuel_type_id = Carvarient::select('fule_type')
            ->where('id', $id)
            ->where('status', '=', 'active')
            ->first();

            die($fuel_type_id);
            /*$data = [];

            $Carvarient_arr = [];
            if($request->option_check == 'Carvarient'){
                $Carvarient = Carvarient::where(['car_model' => $request->id,'status' => 'active'])->get();
                
                foreach ($Carvarient as $value) {
                    $color_data = [];
                    $color_data['id'] = $value->id;
                    $color_data['name'] = $value->name;
                    $Carvarient_arr[] = $color_data;                    
                }  
            }
            $data['Carvarient_arr'] = $Carvarient_arr;  */

            
            
            return json_encode(array('status'=> true ,'data' => $data));
        }
    /** Get Fule Type */
    
    public function getpricelist(Request $request)
    {
        $pricelist_data = DB::table('pricelist_master')->where('id', $request->id)->first();
        $rto_custome_handling_charges = $pricelist_data->rto_custome_handling_charges ?? 0;
        if (isset($request->customer_type)) {
            
            if ($rto_custome_handling_charges == 0) {
                $pricelist_data = DB::table('rto_master')
                    ->select('rto_type', 'rto_tax_individual', 'rto_tax_company', 'totali_individual_charges', 'totalcharges')
                    ->where('rto_type', 'like', $request->customer_type . '%')
                    ->orderBy('id', 'DESC')
                    ->first();
            } else {
                $rto_data = DB::table('rto_master')
                    ->select('rto_type', 'rto_tax_individual', 'rto_tax_company', 'totali_individual_charges', 'totalcharges','temporary_registration', 'smart_card_fee', 'hypothecation', 'fresh_permit', 'new_registion', 'crtem', 'agent_charges')
                    ->where('rto_type', 'like', $request->customer_type . '%')
                    ->orderBy('id', 'DESC')
                    ->first();
    
                $totalcharges = ($rto_data->temporary_registration ?? 0) +
                                ($rto_data->smart_card_fee ?? 0) +
                                ($rto_data->hypothecation ?? 0) +
                                ($rto_data->fresh_permit ?? 0) +
                                ($rto_data->new_registion ?? 0) +
                                ($rto_data->crtem ?? 0) +
                                ($rto_data->agent_charges ?? 0);
                $pricelist_data = [
                    'rto_type' => $rto_data->rto_type,
                    'rto_tax_individual' => $rto_data->rto_tax_individual,
                    'rto_tax_company' => $rto_data->rto_tax_company,
                    'totali_individual_charges' => $rto_data->totali_individual_charges,
                    'totalcharges' => $totalcharges,
                    'rto_custome_handling_charges' => $rto_custome_handling_charges,
                ];
            }
        }
    
        return response()->json($pricelist_data);
    }
}
