<?php



namespace App\Http\Controllers;

 

use Illuminate\Http\Request; 

use App\Models\Accessory;

use App\Models\Allocation; 

use App\Models\Approval;

use App\Models\Branch;

use App\Models\CarExchange; 

use App\Models\ExtandWarranty;

use App\Models\Fasttag;

use App\Models\Finance;

use App\Models\Insurance;

use App\Models\Lead;

use App\Models\Sublead;

use App\Models\OBF;

use App\Models\User;

use App\Models\Product;

use App\Models\Carmodel;

use App\Models\Interiorcolor;

use App\Models\Exteriorcolor;

use App\Models\Carvarient;

use App\Models\pricelist;

use App\Models\Mcp;

use App\Models\Tax;

use App\Models\OtherOne;

use App\Models\OtherTwo;

use App\Models\Inventory;

use App\Models\CashReceipt;

use App\Models\Texmaster;

use App\Models\Fuletype;

use App\Models\ObfInsurance;

use App\Models\CustomerTypeMaster;

use App\Models\RSA;

use App\Models\Setting;

use App\Models\rto_master;

use App\Models\offer;

use App\Models\MakeDeal;

use App\Models\CancellationReason;

use Spatie\Permission\Models\Role;

use Spatie\Permission\Models\Permission;

use Maatwebsite\Excel\Facades\Excel; 

use App\Imports\ImportObf;

use App\Exports\ExportObf;

use Carbon\Carbon;

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

use Session; 

use PDF;

use App\Models\State;

use App\Models\District;

use App\Models\City;

use App\Models\Occupation;

use App\Models\DMS;

use App\Models\discount;



class ObfController extends Controller{

    /** construct */
        public function __construct(){

            $this->middleware('permission:obf-create', ['only' => ['create']]);

            $this->middleware('permission:obf-edit', ['only' => ['edit']]);

            $this->middleware('permission:obf-view', ['only' => ['view']]);

            $this->middleware('permission:obf-insuranceview', ['only' => ['insuranceview']]);

            $this->middleware('permission:obf-rtoview', ['only' => ['rtoview']]);

            $this->middleware('permission:obf-fasttagview', ['only' => ['fasttagview']]);

            $this->middleware('permission:obf-delete', ['only' => ['delete']]);

            $this->middleware('permission:obf-finance', ['only' => ['finance']]);

            $this->middleware('permission:obf-policy_view', ['only' => ['finance']]);

        }
    /** construct */

    /** index */
        public function index(Request $request){
            
            $permission_get = '';
            $data_v = auth()->user()->roles->pluck('data_permission');
            if (!empty($data_v)) {
                $permission_get = $data_v[0];
            }
            
            // Pre-fetch dropdown data (these do not need optimization):
            $customer_name = OBF::select('id', 'customer_name')->get();
            $kec_name = User::select(DB::raw("CONCAT(first_name,' ',last_name) AS kec_name"), '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();
            $date = OBF::select('booking_date', 'id')->get();
            $cash_status = CashReceipt::select('cash_receipt.status')->join('obf', 'obf.id', '=', 'cash_receipt.obf_id')->get();
            $cash_total = CashReceipt::select('amount', 'receipt_type', 'obf.id as obf_id')
                ->join('obf', 'obf.id', '=', 'cash_receipt.obf_id')
                ->whereIn('receipt_type', ['booking_receipt', 'downpayment_receipt'])
                ->get();
            $cancel_reason = CancellationReason::select('name', 'id')->where('status', 'active')->get();
            
            // Filters
            $cust_name = $request->client;
            $kec = $request->kec;
            $products = $request->product;
            $road_price = $request->road_price;
            $variants = $request->varient;
            $locations = $request->location;
            $startdates = $request->start_date;
            $enddates = $request->end_date;
            
            if ($request->ajax()) {
                $cashSummary = DB::table('cash_receipt')
                    ->select(
                        'obf_id',
                        DB::raw('SUM(CASE WHEN receipt_type="booking_receipt" AND status!="rejected" THEN amount ELSE 0 END) AS booking_amount'),
                        DB::raw('SUM(CASE WHEN receipt_type="downpayment_receipt" AND status!="rejected" THEN amount ELSE 0 END) AS dp_amount'),
                        DB::raw('SUM(CASE WHEN receipt_type="disbusment_receipt" AND status!="rejected" THEN amount ELSE 0 END) AS net_disbusment'),
                        DB::raw('SUM(CASE WHEN receipt_type="access_sort_receipt" AND status!="rejected" THEN amount ELSE 0 END) AS access_sort_amount'),
                        DB::raw('SUM(CASE WHEN status!="rejected" THEN amount ELSE 0 END) AS received_amount')
                    )
                    ->groupBy('obf_id');
                
                // Aggregate exchange purchase
                $exchangeSummary = DB::table('exchange_purchase')
                    ->select('obf_id', DB::raw('total_exchange_amount'))
                    ->whereIn('status', ['active','sell']);
                
                $data = OBF::select(
                    'obf.id', 
                    'obf.customer_name', 
                    'obf.ship_to_customer_name',
                    'obf.booking_date',
                    'car_model.name AS product',
                    'obf.status',
                    'obf.ew_status',
                    'obf.mcp_status',
                    'obf.rsa_status',
                    'obf.yodepartment_status',
                    'obf.rto_status',
                    'obf.insurance_status',
                    'obf.accesories_status',
                    'obf.fasttag_status',  
                    'obf.municipal_tax_status', 
                    'obf.on_road_price',
                    // 'car_varient.name AS car_varient_name',
                    DB::raw("CONCAT(car_varient.name, ' - ', tex_master.gst, ' - ',tex_master.compensation_cess,  ' %') AS car_varient_name"),
                    'branches.name as branch_name',
                    'cash_receipt.status as receipt_status',
                    'orders.status as order_status',
                    'orders.invoice_no as order_invoice_no',
                    DB::raw("CASE WHEN orders.invoice_no IS NOT NULL AND orders.invoice_date IS NOT NULL THEN orders.invoice_no ELSE '---' END as invoice_no"),
                    DB::raw("COALESCE(MAX(orders.invoice_date), '--') as invoice_date"),
                    DB::raw('(SELECT vin_number FROM inventory WHERE inventory.status != "inactive" AND inventory.status != "deleted" AND inventory.status != "sold" AND inventory.id = obf.inventory_id) as vin_number'),
                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                    DB::raw('cash_summary.received_amount'),
                    'obf.gst',
                    'exteriorcolor.name as exterior_color',
                    'obf.address',
                    'obf.registration',
                    'obf_finance.loan_amount',
                    'obf_finance.finance_discount',
                    DB::raw('cash_summary.net_disbusment'),
                    'obf.way_off',
                    'obf.foc_accessories',
                    'obf.offer_ib_amount',
                    'obf.offer_kin_amount',
                    'obf.approval_status',
                    DB::raw('cash_summary.booking_amount'),
                    DB::raw('cash_summary.dp_amount'),
                    DB::raw('cash_summary.access_sort_amount'),
                    'Team_master.team_name',
                    DB::raw('(exchange.total_exchange_amount) as total_exchange_amount'),
                    DB::raw("(
                        COALESCE(cash_summary.booking_amount, 0) +
                        COALESCE(cash_summary.dp_amount, 0) +
                        COALESCE(cash_summary.net_disbusment, 0) +
                        COALESCE(exchange.total_exchange_amount, 0)
                    ) as final_total"),
                    DB::raw("( obf.on_road_price - (COALESCE(obf_finance.finance_discount, 0) + COALESCE(obf.way_off, 0) + COALESCE(obf.foc_accessories, 0) + COALESCE(obf.offer_ib_amount, 0) + COALESCE(obf.offer_kin_amount, 0))) as net_total"),
                    DB::raw("(
                        obf.on_road_price - 
                        (
                            COALESCE(cash_summary.booking_amount, 0) + 
                            COALESCE(cash_summary.dp_amount, 0) + 
                            COALESCE(cash_summary.net_disbusment, 0) + 
                            COALESCE(exchange.total_exchange_amount, 0) + 
                            COALESCE(obf_finance.finance_discount, 0) + 
                            COALESCE(obf.way_off, 0) + 
                            COALESCE(obf.tl_discount, 0) + 
                            COALESCE(obf.sm_discount, 0) + 
                            COALESCE(obf.gm_discount, 0) + 
                            COALESCE(obf.bh_discount, 0) + 
                            COALESCE(obf.ceo_discount, 0) + 
                            COALESCE(obf.md_discount, 0) + 
                            COALESCE(obf.foc_accessories, 0) + 
                            COALESCE(obf.offer_ib_amount, 0) + 
                            COALESCE(obf.offer_kin_amount, 0)
                        ) + 
                        CASE 
                            WHEN (
                                (
                                    COALESCE(cash_summary.booking_amount, 0) + 
                                    COALESCE(cash_summary.dp_amount, 0) + 
                                    COALESCE(cash_summary.net_disbusment, 0) + 
                                    COALESCE(exchange.total_exchange_amount, 0) + 
                                    COALESCE(obf_finance.finance_discount, 0) + 
                                    COALESCE(obf.way_off, 0) + 
                                    COALESCE(obf.tl_discount, 0) + 
                                    COALESCE(obf.sm_discount, 0) + 
                                    COALESCE(obf.gm_discount, 0) + 
                                    COALESCE(obf.bh_discount, 0) + 
                                    COALESCE(obf.ceo_discount, 0) + 
                                    COALESCE(obf.md_discount, 0) + 
                                    COALESCE(obf.foc_accessories, 0) + 
                                    COALESCE(obf.offer_ib_amount, 0) + 
                                    COALESCE(obf.offer_kin_amount, 0)
                                ) < obf.on_road_price
                            ) 
                            THEN -COALESCE(cash_summary.access_sort_amount, 0) 
                            ELSE COALESCE(cash_summary.access_sort_amount, 0) 
                        END
                    ) as due_amount
                "),
                DB::raw('(COALESCE(obf_finance.finance_discount, 0) + COALESCE(obf.way_off, 0) + COALESCE(obf.foc_accessories, 0) + COALESCE(obf.offer_ib_amount, 0) + COALESCE(obf.offer_kin_amount, 0)) AS total_finance_discount'),
                'obf.discount_flag',
                'obf.tl_discount',
                'obf.sm_discount',
                'obf.gm_discount',
                'obf.bh_discount',
                'obf.ceo_discount',
                'obf.md_discount',
                )
                ->leftjoin('products', 'obf.product_id', 'products.id')
                ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                ->leftjoin('users','users.id','=','obf.sales_person_id')
                ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                ->leftjoin('branches','branches.id','=','obf.branch_id')
                ->leftjoin('cash_receipt','cash_receipt.obf_id','=','obf.id') // required for cash_receipt.status only
                ->leftjoin('orders','orders.obf_id','=','obf.id')
                ->leftJoin('inventory','inventory.name','=','products.id')
                ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
                ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
                ->leftJoin('obf_finance','obf_finance.obf_id','=','obf.id')
                ->leftjoin('Team_master','Team_master.id','users.team_name')
                ->leftjoin('tex_master', 'car_varient.tex_master_id', '=', 'tex_master.id')
                ->leftJoinSub($cashSummary, 'cash_summary', 'cash_summary.obf_id', '=', 'obf.id')
                ->leftJoinSub($exchangeSummary, 'exchange', 'exchange.obf_id', '=', 'obf.id')
                ->where('obf.status','!=','delete')
                ->where(function ($q) {
                    $q->whereIn('obf.discount_flag', 
                        ['0','1','2','3','4','5','6','7','8','9']
                    )
                    ->orWhereNull('obf.discount_flag');
                });
                
            
                // Role-specific filters
                if (auth()->user()->roles && isset(auth()->user()->roles[0]['id'])) {
                    $roleId = auth()->user()->roles[0]['id'];
            
                    if (in_array($roleId, [33, 36, 37, 32])) {
                        $columns = [
                            33 => 'obf.extanded_warranty_id',
                            36 => 'obf.convinience_program',
                            37 => 'obf.rsa_master_obf',
                            32 => 'obf.accessory_id'
                        ];
                        $data = $data->groupBy('orders.obf_id')->whereIn('orders.status', ['all_payment_done', 'invoice_create'])->whereNotNull($columns[$roleId]);
                    } elseif ($roleId == 22) {
                        $data = $data->groupBy('obf.id');
                    } elseif ($roleId == 34) {
                        $data = $data->groupBy('obf.id')->where('obf.trade_car_value', '=', 'yes');
                    } else {
                        $data = $data->groupBy('obf.id');
                    }
                }
            
                // Permissions and branch restrictions
                if ($permission_get === 'ONLY_MY_DATA') {
                    $data = $data->whereRaw('FIND_IN_SET(obf.created_by, "' . auth()->id() . '")');
                }
                if (!empty(auth()->user()->branch)) {
                    $data = $data->whereRaw('FIND_IN_SET(obf.branch_id, "' . auth()->user()->branch . '")');
                }
                if ($permission_get === 'MY_TEAM_DATA' && auth()->user()->team_name !== null) {
                    $teamIds = User::where('team_name', auth()->user()->team_name)->pluck('id');
                    $data = $data->whereIn('obf.created_by', $teamIds);
                }
                
                $data->orderByDesc('obf.id');

                return Datatables::of($data)
                    ->addIndexColumn()
    
                    ->addColumn('action', function ($data) {
    
                        $return = '<div class="btn-group">';
                        
                        /*$roleFlags = [
                            "0" => 'KEC',
                            "1" => 'Team leader',
                            "2" => 'Sales Manager',
                            "3" => 'General Manager - Sales',
                            "4" => 'Accountant',
                        ];
                        
                        $user = auth()->user();
                        $assignFlag = $user->flag ?? null;
                        
                        // Check if the user is KEC (flag 0)
                        $isKEC = $assignFlag === "0";
                        $isTL = $assignFlag === "1";
                        $isSM = $assignFlag === "2";
                        $isGM = $assignFlag === "3";
                        
                        $tlAccepted = $data->approval_status == 'obf_tl_accepted';
                        $smAccepted = $data->approval_status == 'obf_sm_accepted';
                        $gmAccepted = $data->approval_status == 'obf_gm_accepted';
                        $accountantAccepted = $data->approval_status == 'obf_accountant_accepted';
                        
                        // If SM accepted then no one can edit
                        $lockEdit = $smAccepted;
                        
                        // If any status is accepted, restrict KEC from editing
                        $restrictKEC = $isKEC && ($tlAccepted || $smAccepted || $gmAccepted || $accountantAccepted);
                        $restrictTL = $isTL && ($tlAccepted || $smAccepted || $gmAccepted || $accountantAccepted);
                        $restrictSM = $isSM && ($smAccepted || $gmAccepted || $accountantAccepted);
                        $restrictGM = $isGM && ($gmAccepted || $accountantAccepted);
                        
                        // Status checks
                        $smAccepted = $data->approval_status == 'obf_sm_accepted';
                        
                        // ❌ Lock only when SM approved
                        $lockEdit = $smAccepted;
                        
                        // ✅ Allow only KEC & TL if not locked
                        $allowEdit = ($isKEC || $isTL) && !$lockEdit;
                        
                        $role = auth()->user()->roles;
    
                        $roleName = "";
            
                        if ($role) {
            
                            $roleName = $role[0]->name;
            
                        }
                        
                        if (auth()->user()->can('obf-edit')) {
                            // if (!$lockEdit && !$restrictKEC && !$restrictTL && !$restrictSM && !$restrictGM) {
                            if (empty($data->order_invoice_no)) {
                                if ($allowEdit || $roleName == 'admin' || $roleName == 'Accounts Manager') {
                                    $return .= '<a href="'.route('obf.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                    <i class="fa fa-edit"></i>
                                                </a> &nbsp;';
                                }                
                            }
                        }*/
                        
                        
                        $roleFlags = [
                            "0" => 'KEC',
                            "1" => 'Team leader',
                            "2" => 'Sales Manager',
                            "3" => 'General Manager - Sales',
                            "4" => 'Accountant',
                        ];
                        
                        $user = auth()->user();
                        $assignFlag = $user->flag ?? null;
                        
                        // Role flags
                        $isKEC = $assignFlag === "0";
                        $isTL  = $assignFlag === "1";
                        $isSM  = $assignFlag === "2";
                        $isGM  = $assignFlag === "3";
                        
                        // Approval checks
                        $tlAccepted         = $data->approval_status == 'obf_tl_accepted';
                        $smAccepted         = $data->approval_status == 'obf_sm_accepted';
                        $gmAccepted         = $data->approval_status == 'obf_gm_accepted';
                        $accountantAccepted = $data->approval_status == 'obf_accountant_accepted';
                        
                        // Lock after SM approval
                        $lockEdit = $smAccepted;
                        
                        $restrictKEC = $isKEC && ($tlAccepted || $smAccepted || $gmAccepted || $accountantAccepted);
                        $restrictTL = $isTL && ($tlAccepted || $smAccepted || $gmAccepted || $accountantAccepted);
                        $restrictSM = $isSM && ($smAccepted || $gmAccepted || $accountantAccepted);
                        $restrictGM = $isGM && ($gmAccepted || $accountantAccepted);
                        
                        // Allow KEC & TL only if not locked
                        $allowEdit = ($isKEC || $isTL) && !$lockEdit;
                        
                        // Role name
                        $role = auth()->user()->roles;
                        $roleName = '';
                        
                        if ($role) {
                            $roleName = $role[0]->name;
                        }
                        
                        // Check if invoice exists
                        $invoiceExists = !empty($data->order_invoice_no);
                        
                        if (auth()->user()->can('obf-edit')) {
                        
                            // Admin & Accounts Manager can always edit
                            if ($roleName == 'admin' || $roleName == 'Accounts Manager') {
                                $return .= '<a href="'.route('obf.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-edit"></i>
                                            </a> &nbsp;';
                            }
                        
                            // KEC / TL can edit only if invoice not created
                            elseif (!$invoiceExists && $allowEdit) {
                                $return .= '<a href="'.route('obf.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-edit"></i>
                                            </a> &nbsp;';
                            }
                        }
                        
                        $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(!$restrictKEC && !$restrictTL && !$restrictSM && !$restrictGM){ 
                                            $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="pending" data-id="' . base64_encode($data->id) . '">Pending</a></li>';
                                        }
                                        
                                        if (auth()->user()->can('obf-delete')) {
                                            $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="cancel_reason(this);" data-status="delete" data-id="' . base64_encode($data->id) . '">Delete</a></li>';
                                        } 
                                        
                                        $return .= '<li><a class="dropdown-item" href="' . route('obf.obf_print', ['id' => base64_encode($data->id)]) . '" target="_blank">OBF Print</a></li>
    
                                        <li><a class="dropdown-item" href="' . route('obf.obf_summary', ['id' => base64_encode($data->id)]) . '" target="_blank">OBF Summary</a></li>';
                                        
                                        if (auth()->user()->can('Process Finance')) {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processfinance', ['id' => base64_encode($data->id)]) . '" target="_blank">Process Finance</a></li>';
    
                                        } 
                                        
                                        if (auth()->user()->can('Process EW') && $data->ew_status != 'EW COMPLETED') {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processew', ['id' => base64_encode($data->id)]) . '" target="_blank">Process EW</a></li>';
    
                                        } 
                                        
                                        if (auth()->user()->can('Process MCP') && $data->mcp_status != 'MCP COMPLETED') {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processmcp', ['id' => base64_encode($data->id)]) . '" target="_blank">Process MCP</a></li>';
    
                                        } 
                                        
                                        if (auth()->user()->can('Process RSA') && $data->rsa_status != 'RSA COMPLETED') {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processrsa', ['id' => base64_encode($data->id)]) . '" target="_blank">Process RSA</a></li>';
    
                                        } 
                                        
                                        if (auth()->user()->can('Process CCS') && $data->rsa_status != 'CCS COMPLETED') {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processccs', ['id' => base64_encode($data->id)]) . '" target="_blank">Process CCS</a></li>';
    
                                        } 
                                        
                                        if (auth()->user()->can('Process FastTag')) {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processfasttag', ['id' => base64_encode($data->id)]) . '" target="_blank">Process FastTag</a></li>';
    
                                        }
                                        
                                        if (auth()->user()->can('Process Municipal Tax')) {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processmunicipletax', ['id' => base64_encode($data->id)]) . '" target="_blank">Process Municipal Tax</a></li>';
    
                                        }
                                        
                                        if (auth()->user()->can('Process YO Department')) {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processyodepartment', ['id' => base64_encode($data->id)]) . '" target="_blank">Process YO Department</a></li>';
    
                                        } 
                                        
                                        if (auth()->user()->can('Process Accessories') && $data->accesories_status != 'ACCESORIES COMPLETED') {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processaccesories', ['id' => base64_encode($data->id)]) . '" target="_blank">Process Accessories</a></li>';
    
                                        } 
                                        
                                        if (auth()->user()->can('Process RTO') && $data->rto_status != 'RTO COMPLETED') {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processrto', ['id' => base64_encode($data->id)]) . '" target="_blank">Process RTO</a></li>';
    
                                        } 
                                        
                                        if (auth()->user()->can('Process Insurance') && $data->insurance_status != 'INSURANCE COMPLETED' || auth()->user()->can('Process Insurance') && $data->insurance_status != 'Not Completed') {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.processinsurance', ['id' => base64_encode($data->id)]) . '" target="_blank">Process Insurance</a></li>';
    
                                        } 
                                        
                                        if (auth()->user()->can('Process EW') && $data->ew_status != 'EW COMPLETED' || auth()->user()->can('Process MCP') && $data->mcp_status != 'MCP COMPLETED' || auth()->user()->can('Process RSA') && $data->rsa_status != 'RSA COMPLETED' || auth()->user()->can('Process FastTag') || auth()->user()->can('Process YO Department') || auth()->user()->can('Process Accessories') && $data->accesories_status != 'ACCESORIES COMPLETED' || auth()->user()->can('Process RTO') && $data->rto_status != 'RTO COMPLETED') {
    
                                            $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="cancel_reason(this);" data-status="pending" data-id="' . base64_encode($data->id) . '">Cancel</a></li>';
    
                                        }
                                        
                                        if (auth()->user()->can('obf-make-deal')) {
                                            
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.make-deal', ['id' => base64_encode($data->id)]) . '" target="_blank">Make Deal</a></li>';
    
                                        }
                                        
                                        if (auth()->user()->can('Undertaking')) {
    
                                            $return .= '<li><a class="dropdown-item" href="' . route('obf.undertaking', ['id' => base64_encode($data->id)]) . '" target="_blank">Undertaking</a></li>';
    
                                        }
                                        
                                        if (auth()->user()->can('Liquidation Process')) {
                                            if($data->net_disbusment > 0 || $data->booking_amount > 0 || $data->dp_amount > 0){
                                                $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="liquidation_process(this);" data-status="cancel_refund" data-id="' . base64_encode($data->id) . '">Process Refund Requisition</a></li>';    
                                            }
                                        }
                                        
                                        $return .= '<li><a class="dropdown-item" href="' . route('obf.obf_accessory_form', ['id' => base64_encode($data->id)]) . '" target="_blank">Accessory Form</a></li>';
                                        
                                        // if (auth()->user()->can('Discount Process')) { 
                                        //     $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="discount_process(this);" data-id="' . base64_encode($data->id) . '">Process Discount</a></li>';
                                        // }
                                        
                                        if (auth()->user()->can('Discount Process')){
                                            $return .= '<li><a class="dropdown-item" href="javascript:void(0);" onclick="discount_process(this);" data-id="' . base64_encode($data->id) . '" data-fetch-url="' . route("obf.discount_process_fetch", ":id") . '">Process Discount</a></li>';
                                        }
    
                        $return .= '</ul></div>';
    
                        return $return;
                    })
    
                    ->editColumn('booking_date', function($data) {
                        return (!empty($data->booking_date))
                            ? \Carbon\Carbon::parse($data->booking_date)->format('d-m-Y H:i:s')
                            : '--';
                    })
    
                    ->editColumn('final_total',function($data){
    
                        $book_amt = $data->booking_amount + $data->dp_amount + $data->net_disbusment + $data->total_exchange_amount;
    
                        return $book_amt;
    
                    })
    
                    ->editColumn('net_total',function($data){
                        
                        // $finance_dis = ($data->finance_discount ?? 0) + ($data->way_off ?? 0) + ($data->foc_accessories ?? 0) + ($data->offer_ib_amount ?? 0) + ($data->offer_kin_amount ?? 0);
                        
                        // $net_amt = $data->on_road_price - $finance_dis;
    
                        // return $net_amt;
                        
                        /*$finance_dis = floatval($data->finance_discount) 
                                     + floatval($data->way_off)
                                     + floatval($data->tl_discount)
                                     + floatval($data->gm_discount)
                                     + floatval($data->sm_discount)
                                     + floatval($data->bh_discount)
                                     + floatval($data->ceo_discount)
                                     + floatval($data->md_discount)
                                     + floatval($data->foc_accessories) 
                                     + floatval($data->offer_ib_amount) 
                                     + floatval($data->offer_kin_amount);
                        
                        $net_amt = floatval($data->on_road_price) - $finance_dis;
                    
                        return $net_amt;*/
                    })

                    
                    ->editColumn('finance_discount',function($data){
    
                        $finance_dis = ($data->finance_discount ?? 0) + ($data->way_off ?? 0) + ($data->tl_discount ?? 0) + ($data->gm_discount ?? 0) + ($data->sm_discount ?? 0) + ($data->bh_discount ?? 0) + ($data->ceo_discount ?? 0) + ($data->md_discount ?? 0) + ($data->foc_accessories ?? 0) + ($data->offer_ib_amount ?? 0) + ($data->offer_kin_amount ?? 0);
                        
                        return $finance_dis;
                        
                        /*$finance_dis = floatval($data->finance_discount) 
                                     + floatval($data->way_off) 
                                     + floatval($data->foc_accessories) 
                                     + floatval($data->offer_ib_amount) 
                                     + floatval($data->offer_kin_amount);
                        
                        $finance_dis = floatval($data->$finance_dis);
                    
                        return $finance_dis;*/
    
                    })
                    
                    ->editColumn('access_sort_amount',function($data){
                        return (isset($data->access_sort_amount) && !empty($data->access_sort_amount)) ? $data->access_sort_amount : '0';
                    })
    
                    /*->editColumn('due_amount',function($data){
                        $finance_dis = ($data->finance_discount ?? 0) + ($data->way_off ?? 0) + ($data->foc_accessories ?? 0) + ($data->offer_ib_amount ?? 0) + ($data->offer_kin_amount ?? 0);
                        
                        $book_amt = $data->booking_amount + $data->dp_amount + $data->net_disbusment + $data->total_exchange_amount;
                        
                        $total_amt = $book_amt + $finance_dis;
                        $on_road_amount = $data->on_road_price;
                        $due_amount = $on_road_amount - $total_amt;
                        if ($total_amt < $on_road_amount) {
                            $due_amount -= ($data->access_sort_amount ?? 0);
                        } else {
                            $due_amount += ($data->access_sort_amount ?? 0);
                        }
                        return $due_amount;
    
                    })*/
                    
                    ->editColumn('due_amount', function($data) {

                        // Safely cast all values to float
                        $finance_dis = floatval($data->finance_discount) 
                                     + floatval($data->way_off) 
                                     + floatval($data->tl_discount)
                                     + floatval($data->gm_discount)
                                     + floatval($data->sm_discount)
                                     + floatval($data->bh_discount)
                                     + floatval($data->ceo_discount)
                                     + floatval($data->md_discount)
                                     + floatval($data->foc_accessories) 
                                     + floatval($data->offer_ib_amount) 
                                     + floatval($data->offer_kin_amount);
                    
                        $book_amt = floatval($data->booking_amount) 
                                  + floatval($data->dp_amount) 
                                  + floatval($data->net_disbusment) 
                                  + floatval($data->total_exchange_amount);
                    
                        $total_amt = $book_amt + $finance_dis;
                        $on_road_amount = floatval($data->on_road_price);
                    
                        $due_amount = $on_road_amount - $total_amt;
                    
                        if ($total_amt < $on_road_amount) {
                            $due_amount -= floatval($data->access_sort_amount);
                        } else {
                            $due_amount += floatval($data->access_sort_amount);
                        }
                    
                        return $due_amount;
                    
                    })

                    
                    ->editColumn('status', function ($data) {
    
                        if($data->receipt_status == 'accepted' && $data->status == 'account_accepted' && $data->order_status == 'waiting'){
                    
                            return '<span class="badge badge-pill badge-success">Order'. '-'.$data->order_status .'</span>';
                    
                        }elseif($data->status == 'account_accepted' && $data->order_status == 'finance_apporve'){
                    
                            return '<span class="badge badge-pill badge-success">Finance Apporved</span>';
                    
                        }elseif($data->status == 'account_accepted' && $data->order_status == 'disbursement'){
                    
                            return '<span class="badge badge-pill badge-success">Disbursement</span>';
                    
                        }elseif($data->status == 'account_accepted' && $data->order_status == 'all_payment_done'){
                    
                            return '<span class="badge badge-pill badge-success">All Payment Done</span>';
                    
                        }elseif($data->order_status == 'pdi_approve'){
                    
                            return '<span class="badge badge-pill badge-success">PDI Approve</span>';
                    
                        }elseif($data->order_status == 'pdi_reject'){
                    
                            return '<span class="badge badge-pill badge-danger">PDI Reject</span>';
                    
                        }elseif($data->order_status == 'ready_to_deliver'){
                    
                            return '<span class="badge badge-pill badge-success">Ready to Deliver</span>';
                    
                        }elseif($data->order_status == 'delivered'){
                    
                            return '<span class="badge badge-pill badge-success">Delivered</span>';
                    
                        }elseif($data->order_status == 'invoice_create'){
                    
                            return '<span class="badge badge-pill badge-success">Invoice Created</span>';
                    
                        }elseif($data->order_status == 'invoice_cancel'){
                    
                            return '<span class="badge badge-pill badge-danger">Invoice Cancelled</span>';
                    
                        }elseif($data->receipt_status == 'accepted' && $data->status == 'account_accepted'){
                    
                            return '<span class="badge badge-pill badge-success">Receipt Created</span>';
                    
                        }elseif ($data->status == 'accepted') {
                    
                            return '<span class="badge badge-pill badge-success">Active</span>';
                    
                        }elseif ($data->status == 'pending') {
                    
                            return '-';
                    
                        }elseif ($data->status == 'deleted') {
                    
                            return '<span class="badge badge-pill badge-danger">Deleted</span>';
                    
                        }elseif ($data->status == 'account_rejected') {
                    
                            return '<span class="badge badge-pill badge-danger">Account Rejected</span>';
                    
                        }elseif ($data->status == 'rejected') {
                    
                            return '<span class="badge badge-pill badge-danger">Rejected</span>';
                    
                        }elseif ($data->status == 'account_accepted') {
                    
                            return '<span class="badge badge-pill badge-success">Account Accepted</span>';
                    
                        }elseif($data->status == 'completed'){
                    
                            return '<span class="badge badge-pill badge-success">Completed</span>'; 
                    
                        }elseif ($data->status == 'cancel') {
                    
                            return '<span class="badge badge-pill badge-danger">Cancel</span>';
                    
                        }elseif ($data->status == 'deal_generated') {
                    
                            return '<span class="badge badge-pill badge-success">Deal Generated</span>';
                    
                        }elseif ($data->status == 'delete') {
                    
                            return '<span class="badge badge-pill badge-danger">Deleted</span>';
                    
                        }elseif ($data->status == 'refund_process') {
                    
                            return '<span class="badge badge-pill badge-danger">Refund Process</span>';
                    
                        }else{
                    
                            return '-';
                    
                        }                            
                    
                    })
                    
                    ->editColumn('approval_status', function ($data) {
    
                        if ($data->approval_status == 'pending') {
    
                            return '<span class="badge badge-pill badge-warning">Pending From TL</span>';
    
                        }elseif ($data->approval_status == 'obf_tl_rejected') {
    
                            return '<span class="badge badge-pill badge-danger">OBF Rejected By TL</span>';
    
                        }elseif ($data->approval_status == 'obf_sm_rejected') {
    
                            return '<span class="badge badge-pill badge-danger">OBF Rejected By SM</span>';
    
                        }elseif ($data->approval_status == 'obf_gm_rejected') {
    
                            return '<span class="badge badge-pill badge-danger">OBF Rejected By GM</span>';
    
                        }elseif ($data->approval_status == 'obf_accountant_rejected') {
    
                            return '<span class="badge badge-pill badge-danger">OBF Rejected By Accountant</span>';
    
                        }elseif ($data->approval_status == 'obf_tl_accepted') {
    
                            return '<span class="badge badge-pill badge-success">Obf Accepted By TL</span>';
    
                        }elseif ($data->approval_status == 'obf_sm_accepted') {
    
                            return '<span class="badge badge-pill badge-success">Obf Accepted By SM</span>';
    
                        }elseif ($data->approval_status == 'obf_gm_accepted') {
    
                            return '<span class="badge badge-pill badge-success">Obf Accepted By GM</span>';
    
                        }elseif ($data->approval_status == 'obf_accountant_accepted') {
    
                            return '<span class="badge badge-pill badge-success">Obf Accepted By Accountant</span>';
    
                        }elseif ($data->approval_status == 'delete') {
    
                            return '<span class="badge badge-pill badge-danger">Deleted</span>';
    
                        }else{
    
                            return '-';
    
                        }                            
    
                    })
                    
                    ->editColumn('discount_flag', function ($data) {

                        if (is_null($data->discount_flag) || $data->discount_flag === '') {
                            return '<span class="badge badge-pill badge-warning">
                                        No Discount Required
                                    </span>';
                        }
                    
                        $approvedBadges = [
                            '2' => 'KEC Discount Approved',
                            '3' => 'TL Discount Approved',
                            '4' => 'SM Discount Approved',
                            '5' => 'GM Discount Approved',
                            '6' => 'BH Discount Approved',
                            '7' => 'CEO Discount Approved',
                            '8' => 'MD Discount Approved',
                        ];
                    
                        if (isset($approvedBadges[$data->discount_flag])) {
                            return '<span class="badge badge-pill badge-success">'
                                    . $approvedBadges[$data->discount_flag] .
                                   '</span>';
                        }
                    
                        return '-';
                    })
                    
                    ->editColumn('ew_status', function ($data) {
                        return ucwords(str_replace('_', ' ', $data->ew_status));
                    })
                    
                    ->editColumn('mcp_status', function ($data) {
                        return ucwords(str_replace('_', ' ', $data->mcp_status));
                    })
                    
                    ->editColumn('rsa_status', function ($data) {
                        return ucwords(str_replace('_', ' ', $data->rsa_status));
                    })
                    
                    ->editColumn('accesories_status', function ($data) {
                        return ucwords(str_replace('_', ' ', $data->accesories_status));
                    })
                    
                    ->editColumn('rto_status', function ($data) {
                        return ucwords(str_replace('_', ' ', $data->rto_status));
                    })
                    
                    ->editColumn('insurance_status', function ($data) {
                        return ucwords(str_replace('_', ' ', $data->insurance_status));
                    })
                    
                    ->rawColumns(['action' ,'status','approval_status','discount_flag'])
    
                    ->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('branch_name',false)) {
                            $query->where('branches.name', "like", "%".request()->get("branch_name")."%");
                        }
                        if (request()->filled('customer_name')) {
                            $name = request()->input('customer_name');
                        
                            if (is_array($name)) {
                                $query->where(function ($q) use ($name) {
                                    foreach ($name as $n) {
                                        $q->orWhere('obf.customer_name', 'like', "%{$n}%");
                                    }
                                });
                            } else {
                                $query->where('obf.customer_name', 'like', "%{$name}%");
                            }
                        }
                        if (request()->get('gst',false)) {
                            $query->where('obf.gst', "like", "%".request()->get("gst")."%");
                        }
                        if (request()->get('ship_to_customer_name',false)) {
                            $query->where('obf.ship_to_customer_name', "like", "%".request()->get("ship_to_customer_name")."%");
                        }
                        if (request()->get('team_name',false)) {
                            $query->where('Team_master.team_name', "like", "%".request()->get("team_name")."%");
                        }
                        if (request()->get('sales_person_name',false)) {
                            $salesPersonName = request()->get('sales_person_name');
                            $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%{$salesPersonName}%"]);
                        }
                        if (request()->get('product',false)) {
                            $query->where('car_model.name', "like", "%".request()->get("product")."%");
                        }
                        if (request()->get('car_varient_name',false)) {
                            $query->where('car_varient.name', "like", "%".request()->get("car_varient_name")."%");
                        }
                        if (request()->get('exterior_color',false)) {
                            $query->where('exteriorcolor.name', "like", "%".request()->get("exterior_color")."%");
                        }
                        if (request()->get('vin_number',false)) {
                            $query->where('inventory.vin_number', "like", "%".request()->get("vin_number")."%");
                        }
                        if (request()->get('on_road_price',false)) {
                            $query->where('obf.on_road_price', "like", "%".request()->get("on_road_price")."%");
                        }
                        if (request()->get('booking_amount', false)) {
                            $bookingAmount = request()->get('booking_amount');
                            $query->having('booking_amount', 'LIKE', "%{$bookingAmount}%");
                        }
                        if (request()->get('dp_amount', false)) {
                            $dpAmount = request()->get("dp_amount");
                            $query->having('dp_amount', 'LIKE', "%{$dpAmount}%");
                        }
                        if (request()->get('loan_amount',false)) {
                            $query->where('obf_finance.loan_amount', "like", "%".request()->get("loan_amount")."%");
                        }
                        if (request()->get('net_disbusment',false)) {
                            $query->where('obf_finance.net_disbusment', "like", "%".request()->get("net_disbusment")."%");
                        }
                        if (request()->get('total_exchange_amount',false)) {
                            $query->where('exchange_purchase.total_exchange_amount', "like", "%".request()->get("total_exchange_amount")."%");
                        }
                        if ($finalTotal = request()->get('final_total')) {
                            $query->havingRaw("final_total LIKE ?", ["%{$finalTotal}%"]);
                        }
                        if ($discount = request()->get('finance_discount')) {
                            $query->havingRaw('CAST(total_finance_discount AS CHAR) LIKE ?', ["%{$discount}%"]);
                        }
    
                        if ($netTotal = request()->get('net_total')) {
                            $query->havingRaw("net_total LIKE ?", ["%{$netTotal}%"]);
                        }
                        if ($accessSort = request()->get('access_sort_amount')) {
                            $query->havingRaw("access_sort_amount LIKE ?", ["%{$accessSort}%"]);
                        }
                        if ($dueAmount = request()->get('due_amount')) {
                            $query->havingRaw("due_amount LIKE ?", ["%{$dueAmount}%"]);
                        }
                        if (request()->get('status',false)) {
                            $query->where('obf.status', "like", "%".request()->get("status")."%");
                        }
                        if (request()->get('approval_status',false)) {
                            $query->where('obf.approval_status', "like", "%".request()->get("approval_status")."%");
                        }
                        if (request()->filled('discount_flag')) {

                            $flag = request('discount_flag');
                        
                            if ($flag === 'null') {
                                // For NULL values in DB
                                $query->whereNull('obf.discount_flag');
                            } else {
                                // For actual numeric string values
                                $query->whereRaw('TRIM(obf.discount_flag) = ?', [$flag]);
                            }
                        }
                        
                        if (request()->get('invoice_no',false)) {
                            $query->where('orders.invoice_no', "like", "%".request()->get("invoice_no")."%");
                        }
                        if (request()->get('invoice_date',false)) {
                            $query->where('orders.invoice_date', "like", "%".request()->get("invoice_date")."%");
                        }
                    })   
    
                    ->make(true);
                }

            

                $role = auth()->user()->roles;
    
                $roleName = "";
    
                if ($role) {
    
                    $roleName = $role[0]->name;
    
                }

            return view('obf.index')->with(['customer_name'=>$customer_name,'kec_name'=>$kec_name,'product'=>$product,'price'=>$price,'varient'=>$varient,'branch'=>$branch,'date'=>$date,'roleName'=>$roleName,'cancel_reason'=>$cancel_reason,'cash_total'=>$cash_total]);

        }
    /** index */

    /** Create */
        public function create(Request $request){
            
            ini_set('memory_limit', '1024M');   
            
            $sales = User::role(['sales','KEC'])->select('id' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active','id'=>auth()->user()->id])->get();

            $product = Product::select('id' , 'name' ,'veriant' ,'is_applicable_for_mcp')->where(['status' => 'active'])->get();

            $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

            $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

            $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

            $branch = Branch::select('*');
            $states = State::select('id','name')->where(['status' => 'active'])->orderBy('name', 'asc')->get();
            $districts = District::select('id','name')->where(['status' => 'active'])->orderBy('name', 'asc')->get();
            $cities = City::select('id','name')->where(['status' => 'active'])->orderBy('name', 'asc')->get();
            $passing_code = Db::table('rto_codes')->select('id',DB::raw("CONCAT(code, ' - ', area) as code_area"))->orderBy('code_area', 'asc')->get();
            
            if(!empty(auth()->user()->branch) && auth()->user()->branch != '' && auth()->user()->branch != NULL){

                $branch_arr = explode(',', auth()->user()->branch);

                if(!empty($branch_arr)){

                    $branch = $branch->whereIn('id',$branch_arr);    

                }

            }                        

            $branch = $branch->where(['status' => 'active'])->get(); 

            //branch selection





            $pricelist_master = DB::table('pricelist_master')->select('id','car_model')->get();

            $occupation_lists = Occupation::select('id', 'occupation_title')->where('status', 'active')->get();

            $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

            $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

            $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

            $car_exchange = CarExchange::select('car_exchange.id','car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->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();



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

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

            

            $user = auth()->user();

            $user_role = $user->getRoleNames();

            

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

            

            $mcp = Mcp::where(['status' => 'active'])->get();  

            

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

            

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

            

            $finance = Finance::where(['status' => 'active'])->get();  

            

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



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

            $auth = User::select('department.name')->join('department','department.id','users.department_id')->where('users.id',auth()->user()->id)->first();

            $depart = !empty($auth->name) ? $auth->name : "";

            

            $rto_master = rto_master::select('amount')->where('status','=','active')->first();

            $rto_amount = $rto_master->amount;

            $fuel_type = Fuletype::select('*')->where('status','=','active')->get();
            
            
            return view('obf.create')->with(['sales' => $sales ,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'Cardata' => $Cardata,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'finance' => $finance ,'lead' => $lead,'pricelist_master' =>$pricelist_master,'occupation_lists' =>$occupation_lists,'Carmodel'=>$Carmodel,'Carvarient'=>$Carvarient,'user_role'=> $user_role[0],'Carmodel_arr' => $Carmodel_arr,'mcp' => $mcp,'OtherOne' => $OtherOne,'OtherTwo' => $OtherTwo, 'finance' => $finance, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'ccs' => $ccs,'depart'=>$depart,'rto_amount'=>$rto_amount,'fuel_type'=>$fuel_type,'states' => $states,'districts' => $districts,'cities' => $cities,'passing_code' => $passing_code]);

        }
    /** Create */
    
    
    /** KEC Discount Limit Check */
    public function kec_discount_limit(Request $request)
    {
        $enteredDiscount = $request->discount; // amount user entered
        $model   = $request->model;
        $fuel    = $request->fuel;
        $veriant = $request->veriant;
        $discount_year = $request->discount_year;
        
        $today = Carbon::today()->toDateString();
    
        // Get active discount row
        $discountData = Discount::where('car_model_id', $model)
            ->where('fuel_id', $fuel)
            ->whereRaw('FIND_IN_SET(?, car_varient_id)', [$veriant])
            ->where('discount.discount_year',$discount_year)
            ->where('status', 'active')
            ->whereDate('start_date', '<=', $today)
            ->whereDate('end_date', '>=', $today)
            ->latest()
            ->first();
    
        if (!$discountData) {
            return response()->json([
                'status' => 'no_discount_found'
            ]);
        }
    
        // Role mapping
        $roleDiscountMap = [
            'KEC'                     => 'kec_discount',
            'Team leader'             => 'tl_discount',
            'Sales Manager'           => 'sm_discount',
            'General Manager - Sales' => 'gm_discount',
            'Business Head'           => 'bh_discount',
            'CEO'                     => 'ceo_discount',
            'Managing director'       => 'md_discount',
        ];
    
        $userRole = trim(auth()->user()->roles()->pluck('name')->first());
    
        if (!isset($roleDiscountMap[$userRole])) {
            return response()->json([
                'status' => 'role_not_allowed'
            ]);
        }
    
        $limitColumn = $roleDiscountMap[$userRole];
        $limit = $discountData->$limitColumn ?? 0;
    
        if ($enteredDiscount > $limit) {
            return response()->json([
                'status' => 'exceed',
                'limit'  => $limit
            ]);
        }
    
        return response()->json([
            'status' => 'ok',
            'limit'  => $limit
        ]);
    }


    /**carvarient */
        public function car_drop_down_get(Request $request){ 

            

            $id = ($request->id);

            //dd($id);

            $fuel = $request->fuel;

            $data = [];



            $Carvarient_arr = [];

            $ExtandWarranty_arr = [];

            $Mcp_arr_new = [];

            if($request->option_check == 'Carvarient'){

                // $Carvarient = Carvarient::where(['car_model' => $request->id,'fule_type'=>$fuel,'status' => 'active'])->get();
                // $tex_master_nm = Texmaster::where(['status','active','id'=>$Carvarient->tex_master_id])->get();

                

                // foreach ($Carvarient as $value) {

                //     $color_data = [];

                //     $color_data['id'] = $value->id;

                //     $color_data['name'] = $value->name;

                //     $Carvarient_arr[] = $color_data;                    

                // }  
                
                $Carvarient = Carvarient::where([
                    'car_model' => $request->id,
                    'fule_type' => $fuel,
                    '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();
                
                foreach ($Carvarient as $value) {
                    $color_data = [];
                    $color_data['id'] = $value->id;
                    $color_data['name'] = $value->name . ' - ' . $value->gst . ' %'; // show GST after name
                    $Carvarient_arr[] = $color_data;
                }



                $ExtandWarranty_data = ExtandWarranty::where(['car_model' => $request->id,'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;                    

                }



                $Mcp_data = Mcp::where(['car_model' => $request->id,'status' => 'active'])->get();

                foreach ($Mcp_data as $value) {

                    $arr_sub = [];

                    $arr_sub['id'] = $value->id;

                    $arr_sub['amount'] = $value->amount;

                    $arr_sub['name'] = $value->name;

                    $Mcp_arr_new[] = $arr_sub;                    

                }  

            }

            $data['Carvarient_arr'] = $Carvarient_arr;  

            $data['ExtandWarranty_arr'] = $ExtandWarranty_arr;  



          /*  */

            $data['Mcp_arr_new'] = $Mcp_arr_new;  



            // var_dump($data['Mcp_arr']);

                        // die('s');



            $Pricelist_arr = [];

            if($request->pricelist == 'pricelist_master'){

                if(!empty(auth()->user()->branch) && auth()->user()->branch != '' && auth()->user()->branch != NULL){

                $branch_arr = explode(',', auth()->user()->branch);

                if(!empty($branch_arr)){

                    $branch = Branch::select('id')->whereIn('id',$branch_arr);    

                }

            }    
            
                
            $from = $request->from;
            $branch_id = $request->branch_id ?? '';
            if($from == "create"){
                $pricelist = pricelist::where(['is_csd'=>$request->is_csd,'car_variant' => $request->id,'status' => 'active'])->whereRaw("FIND_IN_SET(?, branch_id)",[$branch_id])->get();
            } else {
                $pricelist = pricelist::where(['is_csd'=>$request->is_csd,'car_variant' => $request->id,'status' => 'active'])->get();
            }
            
            
            // $pricelist = pricelist::where(['is_csd'=>$request->is_csd,'car_variant' => $request->id,'status' => 'active'])->get();

                foreach ($pricelist as $value) {

                    $price = [];

                    $price['id'] = $value->id;

                    $price['price_list_name'] = $value->price_list_name;

                    $Pricelist_arr[] = $price;                    

                }

            }



            $data['Pricelist_arr'] = $Pricelist_arr;



            $carname_arr = [];

            $tex_master_gst = 1;

            if($request->option_check == 'carname'){

                $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.veriant', '=', $request->id)

                    ->where('products.status', '=', 'active')

                    ->get();

                

                foreach ($Carmodel as $value) {

                    $color_data = [];

                    $color_data['id'] = $value->car_id;

                    $color_data['car_name'] = $value->car_name;

                    $color_data['varient_name'] = $value->varient_name;

                    $color_data['exterior_color'] = $value->exterior_color;

                    $color_data['interior_color'] = $value->interior_color;

                    $carname_arr[] = $color_data;                    

                }  

                $Carvarient_data = Carvarient::where(['id' => $request->id,'status' => 'active'])->first();



                $tex_master_id = 0;

                if($Carvarient_data)

                    $tex_master_id = $Carvarient_data->tex_master_id;



                if($tex_master_id > 0){

                    $Texmaster_data = Texmaster::where(['id' => $tex_master_id,'status' => 'active'])->first();    

                    if($Texmaster_data->gst != null) 

                         $tex_master_gst = $Texmaster_data->gst;

                }

                

            }





             $Mcp_arr = [];



            if($request->new_mcp == 'Mcp'){

                $new_mcp = Mcp::where(['car_model' => $request->id,'status' => 'active'])->get();



                foreach ($new_mcp as $value) {

                    $mcp = [];

                    $mcp['id'] = $value->id;

                    $mcp['name'] = $value->name;

                    $mcp['amount'] = $value->amount;

                    $Mcp_arr[] = $mcp;                    

                }

            }



            $data['Mcp_arr'] = $Mcp_arr;



            $data['carname_arr'] = $carname_arr;  

            $data['tex_master_gst'] = $tex_master_gst;  



            // var_dump($data);

            // die('stop');

            

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

        }
    /** carvarient */

    public function sub_lead_html(Request $request){ 

       $id = ($request->id);



       $data = [];



       $sub_lead_html = [];

       

       $lead_data = Sublead::where(['lead_id' => $id,'status' => 'active'])->get();

       

       foreach ($lead_data as $value) {

           $color_data_arr = [];

           $color_data_arr['id'] = $value->id;

           $color_data_arr['name'] = $value->name;

           $sub_lead_html[] = $color_data_arr;                    

       }  

      

       $data['sub_lead_html'] = $sub_lead_html;  

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

    }

    public function color_select(Request $request){ 

        $data = [];



        $exterior_color_arr = [];

        if($request->option_check == 'exterior_color'){

            

            $arr = Product::select('exterior_color')

                ->where('products.car_model', '=', $request->car_model)

                ->where('products.veriant', '=', $request->id)

                ->where('products.status', '=', 'active')

                ->distinct()

                ->get();

            
            

            foreach ($arr as $value) {

                $color_data = [];

                $color_data['id'] = $value->exterior_color;

                $Exteriorcolor_data = Exteriorcolor::select('name')->where('id', $value->exterior_color)->first();



                $color_data['name'] = '';

                if($Exteriorcolor_data){

                    $color_data['name'] = $Exteriorcolor_data->name;

                }

                $exterior_color_arr[] = $color_data;                    

            }  

        }

        $data['exterior_color_arr'] = $exterior_color_arr;  



        $interior_color_arr = [];

        if($request->option_check == 'interior_color'){

            // die('stop');



           /* var_dump($request->car_model);

            var_dump($request->veriant);

            var_dump($request->id);*/



            $arr = Product::select('products.id','interiorcolor.name as interior_color','interiorcolor.id as interior_color_id')

                    ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')

                    ->where('products.car_model', '=', $request->car_model)

                    ->where('products.veriant', '=', $request->veriant)

                    ->where('products.exterior_color', '=', $request->id)

                    ->where('products.status', '=', 'active')

                    ->get();

            

            foreach ($arr as $value) {

                $color_data = [];

                $color_data['id'] = $value->interior_color_id;

                $color_data['name'] = $value->interior_color;

                $color_data['product_id'] = $value->id;

                $interior_color_arr[] = $color_data;                    

            }  

        }

        $data['interior_color_arr'] = $interior_color_arr;  

        

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

    }

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

                $id = ($request->id);



           /* $cardeails = Carmodel::select('car_model.name as car_name','car_model.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

                        ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

                        ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                        ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                        ->where('car_model.id', '=', $id)

                        ->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')

                        ->where('products.id', '=', $id)

                        ->get();



                

                $data_new = Product::select('products.*','pricelist_master.id as price_id','pricelist_master.price_list_name as price_list_name','pricelist_master.transmission as transmission','pricelist_master.car_variant as price_car_var')

                        ->leftjoin('pricelist_master', 'pricelist_master.car_variant', 'products.veriant')

                        ->where('products.status', '=', 'active')

                        ->where('products.id', '=', $id)

                        ->get();



                $pricelist_arr = [];

                foreach ($data_new as $value) {

                    $color_data = [];

                    $color_data['id'] = $value->price_id;

                    $color_data['price_list_name'] = $value->price_list_name;

                    $color_data['transmission'] = $value->transmission;

                    $pricelist_arr[] = $color_data;

                    

                }

                $data = [];

                $data['pricelist_arr'] = $pricelist_arr;

            

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

        }
    /** carvarient */

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

            if(request()->ajax()){

                return true;

            } 

                $obf = OBF::count();

                $temp_number = sprintf('%04d',$obf+1);





                

                /*$product_id = 0;

                if($request->product_id != null && $request->product_id != ''){

                    $product_id = $request->product_id;

                }



                  DB::enableQueryLog();



                  

               



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







                if(empty($request->accessories)){

                    $request->accessories = [];

                }



                if(empty($request->priclist_detail)){

                    $request->priclist_detail = [];

                }



                if(empty($request->other_details_1)){

                    $request->other_details_1 = [];

                }



                if(empty($request->other_details_2)){

                    $request->other_details_2 = [];

                }



                $detail_value_arr = [];

               if(!empty($request->priclist_detail)){

                   foreach ($request->priclist_detail as $value) {

                       $arr_value = explode('__', $value);

                       $detail_value_sub_arr = [];

                       $detail_value_sub_arr['detail_field'] = $arr_value[0];

                       $detail_value_sub_arr['value_field'] = $arr_value[1]; 

                       $detail_value_arr[] = $detail_value_sub_arr; 

                   }

               }

               $detail_value_arr_json = json_encode($detail_value_arr);



                /*echo "<pre>";

                var_dump($detail_value_arr_json);

                die('s');*/



                if(!empty($request->dob) && $request->dob != '' && $request->dob != NULL)

                {

                   $request->dob = date("Y-m-d",strtotime($request->dob));        

                }



                if(!empty($request->nominee_dob) && $request->nominee_dob != '' && $request->nominee_dob != NULL)

                {

                   $request->nominee_dob = date("Y-m-d",strtotime($request->nominee_dob));        

                }



                //offer type



                $offer_type = $request->offer_type;



                $offer_kin = $request->offer_kin;                

                if($offer_kin != null){

                    $offerkin = implode(',',$offer_kin);

                }

                else{

                    $offerkin = null;

                }



                $offer_ib = $request->offer_ib;

                if($offer_ib != null){

                    $offerib = implode(',',$offer_ib);

                }

                else{

                    $offerib = null;

                }

                if($request->offer_amount != null){

                   // $ex_showroom_price = $request->with_offer_ex_showroom_price;

                    $ex_showroom_price = $request->deal_price;

                }else{

                    $ex_showroom_price = $request->ex_showroom_price;

                }



                $crud = [

                    'temporary_id' => $temp_number,

                    // 'booking_date' => Carbon::parse($request->booking_date),
                    'booking_date' => date('Y-m-d H:i:s'),

                    'customer_name' => strtoupper($request->customer_name),

                    'customer_birthdate' => $request->customer_birthdate ?? null,

                    'customer_type' => $request->customer_type,

                    'customer_type_new' => $request->customer_type_new,

                    'branch_id' => $request->branch,

                    'company_name' => $request->company_name ?? null,

                    'einvoicing_applicable' => $request->einvoapp ?? null,
                    
                    'gst_required' => $request->gst_required === 'yes' ? 'yes' : 'no',
 
                    'gst' => $request->gst ?? null,

                    'address' => $request->address_1 ?? null,

                    'registration' => $request->address_2 ?? null,

                    'email' => $request->email ?? null,

                    'pan_number' => $request->pan_number ?? null,

                    'adhar_number' => $request->adhar_number ?? null,

                    'licance_number' => $request->license_number ?? null,

                    'contact_number' => $request->contact_number ?? null,

                    'dob' => $request->dob ?? null,

                    'nominee_dob' => $request->nominee_dob ?? null,

                    'nominee_name' => $request->nominee_name ?? null,

                    'nominee_reletion' => $request->nominee_relation ?? null,

                    'nominee_age' => $request->nominee_age ?? null,

                    'occupation' => $request->occupation ?? null,

                    'sales_person_id' => $request->sales_person_name ?? null,

                    //'product_id' => $request->name ?? null,
                    'car_model' => $request->car_name ??null,

                    'product_id' => $request->product_id ?? null,

                    'fuel_type' => $request->fuel_type ?? null,

                   /* 'varient_id' => $request->veriant ?? null,

                    'exterior_color' => $request->exterior_color ?? null,

                    'interior_color' => $request->interior_color ?? null,*/

                    'offer_type' => $offer_type ?? null,

                    'offer_kin'=>$offerkin ?? null,

                    'offer_ib'=>$offerib ?? null,

                    'offer_ib_amount'=>$request->offers_ib_amount ?? null,

                    'offer_kin_amount'=>$request->offers_kin_amount ?? null,

                    'offer_amount' => $request->offe_amount ?? null,

                    'deal_price' =>$request->deal_price ?? null,

                    'way_off'=>$request->way_off ?? null,
                    
                    'foc_accessories' => $requeest->foc_accessories ?? null,
                    
                    'discount_flag' => $request->discount_flag ?? null,

                    'final_on_road_price_after_way_off' =>$request->final_on_road_price_after_way_off ?? null,

                    'ex_showroom_price' => $request->ex_showroom_price ?? null,

                    'registration_tax_id' => $request->registration_tax ?? null,
                    
                    'rto_custom_handling_charges' => $request->pl_rto_custom_handling_charges ?? null,

                    'insurance_id' => $request->insurance ?? null,

                    'municipal_tax_id' => $request->municipal_tax ?? null,

                    'municipal_tax_applicable' => $request->municipal_tax_applicable ?? 2,
                    
                    'municipal_tax_type' => $request->municipal_tax_type ?? null,
                    
                    'municipal_custom_handling_charges' => $request->municipal_custom_handling_charges ?? null,

                    'tcs_tax_id' => $request->tcs_tax ?? null,

                    'accessory_id' => implode(" ,",$request->accessories) ?? null,

                    'priclist_detail' => $detail_value_arr_json,

                    'extanded_warranty_id' => $request->extended_warranty ?? null,

                    'fasttag_brand_name' => $request->fasttag_brand_name ?? null,

                    'trade_car_name' => $request->trade_car_name ?? null,

                    'trade_car_value' => $request->trade_car_value ?? null,

                    'on_road_price' => $request->on_road_price ?? null,

                    'on_road_price_word' => $request->on_road_price_word ?? null,

                    // 'finance_id' => $request->finance_name ?? null,

                    // 'finance_branch_id' => $request->finance_branch_name ?? null,

                    'lead_id' => $request->lead ?? null,

                    'sub_lead_id' => $request->sub_lead_id ?? null,

                    'booking_amount' => $request->booking_amount ?? null,

                    'mode_of_payment' => $request->mode_of_payment ?? null,

                    'pricelist_id' => $request->pricelist_manager_id ?? null,                    

                    'convinience_program' => $request->convinience_program ?? null,                    

                    'other_details_1' => implode(" ,",$request->other_details_1) ?? null,

                    'other_details_2' => implode(" ,",$request->other_details_2) ?? null,

                    'rsa_master_obf' => $request->rsa_master_obf ?? null,
                    
                    'ccs_master_obf' => $request->ccs_master_obf ?? null,

                    'step1_remarks' => $request->step1_remarks ?? null,

                    'step2_remarks' => $request->step2_remarks ?? null,

                    'step3_remarks' => $request->step3_remarks ?? null,

                    'step4_remarks' => $request->step4_remarks ?? null,

                    'step5_remarks' => $request->step5_remarks ?? null,

                    'status' => 'pending',
                    
                    'aadhar_pan_link' => $request->aadhar_pan_link === 'yes' ? 'yes' : 'no',
                    
                    'other_accesssories_detail' => $request->other_accesssories_detail,

                    'other_accesssories_prise' => $request->other_accesssories_prise,

                    'is_csd' => $request->is_csd == 'Yes'?1:0,

                    'number_plate'=> $request->number_plate??null,

                    'municipal_tax_handling' => $request->municipal_tax_handling??null,

                    '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,
                    
                    'state_id' => $request->state_id??null,

                    'district_id' => $request->district_id??null,
                    
                    'city_id' => $request->city_id??null,
                    
                    'ship_to_required' => $request->ship_to_required === 'yes' ? 'yes' : 'no',
                    
                    'ship_to_customer_name' => $request->ship_to_customer_name??null,
                    
                    'ship_to_address' => $request->ship_to_address??null,
                    
                    'ship_to_state_id' => $request->ship_to_state_id??null,
                    
                    'ship_to_district_id' => $request->ship_to_district_id??null,
                    
                    'ship_to_city_id' => $request->ship_to_city_id??null,
                    
                    'anniversary_date' => $request->anniversary_date ?? null,
                    
                    'tentetive_delivery_date' => $request->tentative_delivery_date ?? null,
                    
                    'passport_document' => $request->passport_document ?? null,
                    
                    'gst_certificate' => $request->gst_certificate ?? null,
                    
                    'insurance_company_name' => $request->insurance_company_name ?? null,
                    
                    'discount_year' => $request->discount_year ?? null,
                    
                    'rto_passing_id' => $request->rto_passing_id ?? null,

                ];
                
            
                // other documents

                $other_documents = '';

                $other_documents_name_arr = [];

                if(!empty($request->file('other_documents'))){

                    $other_documents_arr = $request->file('other_documents');

                    foreach($other_documents_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "other_documents_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($other_documents_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn))

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($other_documents_name_arr)){

                        $other_documents = implode(",",$other_documents_name_arr);

                    }

                    $crud['other_documents'] = $other_documents;

                }else{

                   // $other_documents_name_arr = [];

                }





                // pan_image  

                if(!empty($request->file('pan_image'))){

                    $pan_image = '';

                    $pan_image_name_arr = [];



                    $pan_image_arr = $request->file('pan_image');

                    foreach($pan_image_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "pan_image_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($pan_image_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn)) 

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($pan_image_name_arr)){

                        $pan_image = implode(",",$pan_image_name_arr);

                    }

                    $crud['pan_image'] = $pan_image;

                }



                // adhar_image        

                if(!empty($request->file('adhar_image'))){

                    $adhar_image = '';

                    $adhar_image_name_arr = [];



                    $adhar_image_arr = $request->file('adhar_image');

                    foreach($adhar_image_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "adhar_image_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($adhar_image_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn))

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($adhar_image_name_arr)){

                        $adhar_image = implode(",",$adhar_image_name_arr);

                    }

                    $crud['adhar_image'] = $adhar_image;

                }
                
                
                // offer_image
                if(!empty($request->file('offer_image'))){

                    $offer_image = '';

                    $offer_image_name_arr = [];



                    $offer_image_arr = $request->file('offer_image');

                    foreach($offer_image_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "offer_image_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($offer_image_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn)) 

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($offer_image_name_arr)){

                        $offer_image = implode(",",$offer_image_name_arr);

                    }

                    $crud['offer_image'] = $offer_image;

                }



                // licance_image        

                if(!empty($request->file('licance_image'))){

                    $licance_image = '';

                    $licance_image_name_arr = [];



                    $licance_image_arr = $request->file('licance_image');

                    foreach($licance_image_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "licance_image_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($licance_image_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn))

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($licance_image_name_arr)){

                        $licance_image = implode(",",$licance_image_name_arr);

                    }

                    $crud['licance_image'] = $licance_image;

                }

                // Licance Image
                
                
                //Aadhar Pan Image
                
                if(!empty($request->file('aadhar_pan_image'))){

                    $aadhar_pan_image = '';

                    $aadhar_pan_image_name_arr = [];



                    $aadhar_pan_image_arr = $request->file('aadhar_pan_image');

                    foreach($aadhar_pan_image_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "aadhar_pan_image_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($aadhar_pan_image_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn))

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($aadhar_pan_image_name_arr)){

                        $aadhar_pan_image = implode(",",$aadhar_pan_image_name_arr);

                    }

                    $crud['aadhar_pan_image'] = $aadhar_pan_image;

                }
                
                // Upload image in finance 
                if(!empty($request->file('finance_image'))){
                    $finance_image = '';
                    $finance_image_name_arr = [];
                    $finance_image_arr = $request->file('finance_image');
                    foreach($finance_image_arr as $key => $file_value){
                        $filenameWithExtension_three = $file_value->getClientOriginalName();
                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                        $extension_three = $file_value->getClientOriginalExtension();
                        $filenameToStore_three_new = "finance_image_".time()."_".$filename_three.'.'.$extension_three;
                        array_push($finance_image_name_arr, $filenameToStore_three_new);                        
                        $folder_to_upload_sn = public_path().'/uploads/kyc/';
                        if(!\File::exists($folder_to_upload_sn))
                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                    }
                    if(!empty($finance_image_name_arr)){
                        $finance_image = implode(",",$finance_image_name_arr);
                    }
                    $crud['finance_image'] = $finance_image;
                
                }

                if(!empty($request->file('rto_image'))){
                    $rto_image = '';
                    $rto_image_name_arr = [];
                    $rto_image_arr = $request->file('rto_image');
                    foreach($rto_image_arr as $key => $file_value){
                        $filenameWithExtension_three = $file_value->getClientOriginalName();
                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                        $extension_three = $file_value->getClientOriginalExtension();
                        $filenameToStore_three_new = "rto_image_".time()."_".$filename_three.'.'.$extension_three;
                        array_push($rto_image_name_arr, $filenameToStore_three_new);                        
                        $folder_to_upload_sn = public_path().'/uploads/kyc/';
                        if(!\File::exists($folder_to_upload_sn))
                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                    }
                    if(!empty($rto_image_name_arr)){
                        $rto_image = implode(",",$rto_image_name_arr);
                    }
                    $crud['rto_image'] = $rto_image;
                }
                        
                if(!empty($request->file('fasttag_image'))){
                            $fasttag_image = '';
                            $fasttag_image_name_arr = [];
                            $fasttag_image_arr = $request->file('fasttag_image');
                            foreach($fasttag_image_arr as $key => $file_value){
                                $filenameWithExtension_three = $file_value->getClientOriginalName();
                                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                                $extension_three = $file_value->getClientOriginalExtension();
                                $filenameToStore_three_new = "fasttag_image_".time()."_".$filename_three.'.'.$extension_three;
                                array_push($fasttag_image_name_arr, $filenameToStore_three_new);                        
                                $folder_to_upload_sn = public_path().'/uploads/kyc/';
                                if(!\File::exists($folder_to_upload_sn))
                                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                            }
                            if(!empty($fasttag_image_name_arr)){
                                $fasttag_image = implode(",",$fasttag_image_name_arr);
                            }
                            $crud['fasttag_image'] = $fasttag_image;
                            
                    
                    //passport document
                    if(!empty($request->file('passport_document'))){
                        $passport_document = '';
                        $passport_document_name_arr = [];
                        $passport_document_arr = $request->file('passport_document');
                        foreach($passport_document_arr as $key => $file_value){
                            $filenameWithExtension_three = $file_value->getClientOriginalName();
                            $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                            $extension_three = $file_value->getClientOriginalExtension();
                            $filenameToStore_three_new = "passport_document_".time()."_".$filename_three.'.'.$extension_three;
                            array_push($passport_document_name_arr, $filenameToStore_three_new);                        
                            $folder_to_upload_sn = public_path().'/uploads/kyc/';
                            if(!\File::exists($folder_to_upload_sn))
                                \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                             $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                        }
                        if(!empty($passport_document_name_arr)){
                            $passport_document = implode(",",$passport_document_name_arr);
                        }
                        $crud['passport_document'] = $passport_document;
                    
                    }
                    
                    //gst certificate
                    if(!empty($request->file('gst_certificate'))){
                        $gst_certificate = '';
                        $gst_certificate_name_arr = [];
                        $gst_certificate_arr = $request->file('gst_certificate');
                        foreach($gst_certificate_arr as $key => $file_value){
                            $filenameWithExtension_three = $file_value->getClientOriginalName();
                            $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                            $extension_three = $file_value->getClientOriginalExtension();
                            $filenameToStore_three_new = "gst_certificate_".time()."_".$filename_three.'.'.$extension_three;
                            array_push($gst_certificate_name_arr, $filenameToStore_three_new);                        
                            $folder_to_upload_sn = public_path().'/uploads/kyc/';
                            if(!\File::exists($folder_to_upload_sn))
                                \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                             $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                        }
                        if(!empty($gst_certificate_name_arr)){
                            $gst_certificate = implode(",",$gst_certificate_name_arr);
                        }
                        $crud['gst_certificate'] = $gst_certificate;
                    
                    }
                }
                DB::beginTransaction();

                try {

                    $last_id = '';

                      // \DB::enableQueryLog(); 

                    // DB::enableQueryLog();

                    $last_id = OBF::insertGetId($crud);    
                    
                    $crud = [
                        'module_nm' => 'obf_create',
                        'module_id' => $last_id,
                        'status' => 'pending',
                        'remark' => $request->step1_remarks,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => auth()->user()->id,
                    ];
                    \DB::table('logs')->insert($crud);

                    if($last_id) {



                        //notification insert

                        $notification_template_master_data = DB::table('notification_template_master')->select('*')->where(['template_name' => 'obf_created','status' => 'active'])->first();

                        if(!empty($notification_template_master_data)){

                            $customer_name = $request->customer_name ?? null;

                            

                            $car_name_get = '';

                            $product_id = 0;

                            if($request->product_id != null && $request->product_id != ''){

                                $product_id = $request->product_id;

                            }



                            if($product_id != null){

                                $Cardata_get = 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')

                              ->where('products.id', '=', $product_id)  

                              ->first();

                                

                                if(!empty($Cardata_get)){

                                    if(!empty($Cardata_get->car_name) && $Cardata_get->car_name != '' && $Cardata_get->car_name != NULL){

                                        $car_name_get .= '('.$Cardata_get->car_name;    

                                        $car_name_get .= ' , '.$Cardata_get->varient_name.')';   

                                    }

                                }    

                            }



                            $customer_name_with_car_detail = '';     



                            if($customer_name != null){

                                $customer_name_with_car_detail = $customer_name;

                            }   



                            if($customer_name != null){

                                $customer_name_with_car_detail .= ' '.$car_name_get;

                            }                  

                            

                            $data_new = str_replace("[customer_name_with_car_detail]",$customer_name_with_car_detail,$notification_template_master_data->template_data);



                            $notification_data = [

                                'user_id' => auth()->user()->id,

                                'notification_text' => $data_new,

                                'notification_link' => route('obf.view', ['id' => base64_encode($last_id)]),

                                'created_by' => auth()->user()->id,

                            ];

                            DB::table('notifications')->insert($notification_data);

                        }

                        //notification insert











                        // insert rto data

                        // die('stpo');

                        // $rto = [

                        // 'obf_id' => $last_id,

                        // 'rto_type' => $request->rto_type ?? null,

                        // 'registration_date' => $request->registration_date ?? null,

                        // 'application_number' => $request->application_number ?? null,

                        // 'temporary_number' => $request->temporary_number ?? null,

                        // 'final_amount' => $request->final_amount ?? null,

                        // 'vehicle_number' => $request->vehicle_number ?? null,

                        // 'rto_type' => $request->rto_type ?? null,

                        // ];

                        // DB::table('obf_rto')->insert($rto);

                        // $rto_log_crud = [
                        //     'module_nm' => 'obf_rto_create',
                        //     'module_id' => $last_id,
                        //     'status' => 'rto_process',
                        //     'remark' => 'RTO Process',
                        //     'created_at' => date('Y-m-d H:i:s'),
                        //     'created_by' => auth()->user()->id,
                        // ];
                        // \DB::table('logs')->insert($rto_log_crud);

                        // // insert Insurance data
                        

                        // $fasttag = [

                        // 'obf_id'=>$last_id,

                        // 'fasttag_number' => $request->fasttag_number ?? null,

                        // 'fasttag_brand' => $request->fasttag_brand ?? null,

                        // 'date_of_issue' => $request->date_of_issue ?? null,

                        // 'fasttag_amount' => $request->fasttag_amount ?? null,

                        // 'opening_stock' => $request->opening_stock ?? null,

                        // ];

                        // // DB::enableQueryLog();

                        

                        //     DB::table('obf_fasttag')->insert($fasttag);
                        
                        // $fasttag_log_crud = [
                        //     'module_nm' => 'obf_fasttag_create',
                        //     'module_id' => $last_id,
                        //     'status' => 'fasttag_process',
                        //     'remark' => 'Fasttag Process',
                        //     'created_at' => date('Y-m-d H:i:s'),
                        //     'created_by' => auth()->user()->id,
                        // ];
                        // \DB::table('logs')->insert($fasttag_log_crud);    

  

                         $obf_finance = [

                        'obf_id'=>$last_id,

                        'finance_required' => $request->finance_required ?? null,

                        ];

                        // DB::enableQueryLog();

                        

                        DB::table('obf_finance')->insert($obf_finance);


                        // Move Files to Folder

                           /* if (!empty($request->file('pan_image'))){

                                $file->move($folder_to_upload, $filenameToStore);

                            }

                            if (!empty($request->file('adhar_image'))){

                                $file_two->move($folder_to_upload, $filenameToStore_two);

                            }

                            if (!empty($request->file('licance_image'))){

                                $file_three->move($folder_to_upload, $filenameToStore_three);

                            }*/

                            // Move Files to Folder

                            DB::commit();

                            return redirect()->route('obf')->with('success', 'Record inserted successfully');



                           // var_dump($insurance);

                //die();

                    } else {

                        DB::rollback();

                        return redirect()->back()->with('error', 'Failed to insert record')->withInput();

                    }

                }catch (\Throwable $th){

                    DB::rollback();

                    var_dump($th); 

                    return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();

                }

            

        }
    /** insert */



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

            if(auth()->user()->can('obf-view')){

                $id = base64_decode($request->id);               

                $path = URL('/uploads/kyc').'/';



                

                $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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



                $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

                $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

                $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

                

                

                        

                $data = OBF::select('obf.id','obf.sales_person_id',

                                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type' ,'obf.customer_type_new' ,'obf.convinience_program' ,'branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name','obf.fasttag_brand_name AS fasttag_brand_name' ,'obf.einvoicing_applicable', 'obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id' ,'products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.id AS fasttag_id' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS brand_name','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','obf.gst_required', 'obf.aadhar_pan_link','obf.aadhar_pan_image','obf.finance_image','obf.rto_image','insurance_image','fasttag_image','obf.issue_date','obf.risk_start_date','obf.risk_end_date','obf.handicap','obf.handicap_image','obf.tyre_company_1','obf.tyre_year_1','obf.tyre_company_2','obf.tyre_year_2','obf.tyre_company_3','obf.tyre_year_3','obf.tyre_company_4','obf.tyre_year_4','obf.tyre_company_5','obf.tyre_year_5','obf.passport_document','obf.gst_certificate',

                'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',



                'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id',



                'obf_finance.finance_name','obf.other_accesssories_prise','obf.other_accesssories_detail','obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.pricelist_id','obf.rsa_master_obf'



                               /* DB::Raw("CASE

                                            WHEN ".'obf_insurance.documents'." != '' THEN CONCAT("."'".$path."'".", ".'obf_insurance.documents'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as documents"),

                                DB::Raw("CASE

                                            WHEN ".'pan_image'." != '' THEN CONCAT("."'".$path."'".", ".'pan_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as pan_image"),

                                DB::Raw("CASE

                                            WHEN ".'adhar_image'." != '' THEN CONCAT("."'".$path."'".", ".'adhar_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as adhar_image"),

                                DB::Raw("CASE

                                            WHEN ".'licance_image'." != '' THEN CONCAT("."'".$path."'".", ".'licance_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as licance_image"),*/

                                )

                    

                            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                            ->leftjoin('products' ,'obf.product_id' ,'products.id')

                            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                            //->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')

                            ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

                            ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')

                            ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')

                            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

                            ->leftjoin('other_one' ,'obf.other_details_1' ,'other_one.id')

                            ->leftjoin('other_two' ,'obf.other_details_2' ,'other_two.id')

                            ->leftjoin('mcp' ,'mcp.id' ,'obf.convinience_program')

                            ->where(['obf.id' => $id])

                            ->first();      

            }





          /*  'obf_insurance.ncb','obf_insurance.documents','obf_insurance.date_of_insurance','obf_insurance.last_time_of_insurance','obf_insurance.time_of_insurance','obf_insurance.company_name','obf_insurance.ncb_amount','obf_insurance.policy_number','obf_insurance.status as insurance_status','obf_insurance.documents',*/







             $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();



                    // dd($carmodel);





        $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.id as varient_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

                            ->leftJoin('car_model','car_model.id','=','obf.product_id')

                            ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

                            ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                            ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                            ->where('obf.id', '=', $id)  

                            ->first();



        $fule = Obf::select('fule_type.title as fule_name')

        ->leftJoin('products','products.id','=','obf.product_id')

        ->leftJoin('car_varient','car_varient.id','=','products.veriant')

        ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')

        ->where('obf.id', '=', $id)  

        ->first();



         $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();



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

            

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



         $Inventory_data = [];

         if($data->inventory_id != NULL){

             $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    

         }



        $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  



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



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



        $accessory_sum = 0;

        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){

            $accessory_id_arr = explode(' ,', $data->accessory_id);

            if(!empty($accessory_id_arr)){

                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           

            }

        }



        // $sales = User::role('sales')->select('id' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active'])->get();



         $sales = User::role(['sales','KEC'])->select('id' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active'])->get();



         $user = auth()->user();

         $user_role = $user->getRoleNames();



         



        return view('obf.view')->with(['data' =>$data,'sales' => $sales ,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'user_role'=> $user_role[0],'accessory_sum' => $accessory_sum]);

        }

    /** view */  

    

    /** insurance view */

        public function insuranceview(Request $request){

            if(auth()->user()->can('obf-insuranceview')){

                $id = base64_decode($request->id);

                $path = URL('/uploads/kyc').'/';



                $sales = User::role('sales')->select('id' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active'])->get();

                $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

                $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

                $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

                $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

                

                $data = OBF::select('obf.id','obf.sales_person_id',

                                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type','obf.customer_type_new' ,'branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' ,'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id' ,'products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS fasttag_brand_name','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','obf.issue_date','obf.risk_start_date','obf.risk_end_date','obf.handicap','obf.handicap_image','obf.tyre_company_1','obf.tyre_year_1','obf.tyre_company_2','obf.tyre_year_2','obf.tyre_company_3','obf.tyre_year_3','obf.tyre_company_4','obf.tyre_year_4','obf.tyre_company_5','obf.tyre_year_5','obf.passport_document','obf.gst_certificate',

                                DB::Raw("CASE

                                            WHEN ".'pan_image'." != '' THEN CONCAT("."'".$path."'".", ".'pan_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as pan_image"),

                                DB::Raw("CASE

                                            WHEN ".'adhar_image'." != '' THEN CONCAT("."'".$path."'".", ".'adhar_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as adhar_image"),

                                DB::Raw("CASE

                                            WHEN ".'licance_image'." != '' THEN CONCAT("."'".$path."'".", ".'licance_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as licance_image"),
                                
                                DB::Raw("CASE WHEN ".'finance_image'." != '' THEN CONCAT("."'".$path."'".", ".'finance_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as finance_image"),
                                DB::Raw("CASE WHEN ".'rto_image'." != '' THEN CONCAT("."'".$path."'".", ".'rto_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as rto_image"),

                                
                                DB::Raw("CASE WHEN ".'insurance_image'." != '' THEN CONCAT("."'".$path."'".", ".'insurance_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as insurance_image"),
                                
                                DB::Raw("CASE WHEN ".'handicap_image'." != '' THEN CONCAT("."'".$path."'".", ".'handicap_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as handicap_image"),
                                
                                DB::Raw("CASE WHEN ".'passport_document'." != '' THEN CONCAT("."'".$path."'".", ".'passport_document'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as passport_document"),
                                
                                DB::Raw("CASE WHEN ".'gst_certificate'." != '' THEN CONCAT("."'".$path."'".", ".'gst_certificate'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as gst_certificate"),
                                
                                DB::Raw("CASE WHEN ".'fasttag_image'." != '' THEN CONCAT("."'".$path."'".", ".'fasttag_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as fasttag_image"),

                                )

                            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                            ->leftjoin('products' ,'obf.product_id' ,'products.id')

                            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

                            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                            ->where(['obf.id' => $id])

                            ->first();      

            }

            return view('obf.insurance')->with(['data' =>$data,'sales' => $sales ,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'finance' => $finance ,'lead' => $lead]);

        }

    /** insurance view */

    

    /** RTO view */

        public function rtoview(Request $request){

            if(auth()->user()->can('obf-rtoview')){

                $id = base64_decode($request->id);

                $path = URL('/uploads/kyc').'/';



                $sales = User::role('sales')->select('id' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active'])->get();

                $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

                $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

                $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

                $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

                

                $data = OBF::select('obf.id','obf.sales_person_id',

                                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type' ,'obf.customer_type_new','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' ,'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id' ,'products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS fasttag_brand_name','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','obf.rto_custom_handling_charges',

                                DB::Raw("CASE

                                            WHEN ".'pan_image'." != '' THEN CONCAT("."'".$path."'".", ".'pan_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as pan_image"),

                                DB::Raw("CASE

                                            WHEN ".'adhar_image'." != '' THEN CONCAT("."'".$path."'".", ".'adhar_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as adhar_image"),

                                DB::Raw("CASE

                                            WHEN ".'licance_image'." != '' THEN CONCAT("."'".$path."'".", ".'licance_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as licance_image"),
                                
                                DB::Raw("CASE WHEN ".'finance_image'." != '' THEN CONCAT("."'".$path."'".", ".'finance_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as finance_image"),
                                
                                DB::Raw("CASE WHEN ".'rto_image'." != '' THEN CONCAT("."'".$path."'".", ".'rto_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as rto_image"),
                                
                                DB::Raw("CASE WHEN ".'insurance_image'." != '' THEN CONCAT("."'".$path."'".", ".'insurance_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as insurance_image"),
                                
                                DB::Raw("CASE WHEN ".'fasttag_image'." != '' THEN CONCAT("."'".$path."'".", ".'fasttag_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as fasttag_image"),
                                
                                DB::Raw("CASE WHEN ".'handicap_image'." != '' THEN CONCAT("."'".$path."'".", ".'handicap_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as handicap_image"),
                                
                                DB::Raw("CASE WHEN ".'passport_document'." != '' THEN CONCAT("."'".$path."'".", ".'passport_document'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as passport_document"),
                                
                                DB::Raw("CASE WHEN ".'gst_certificate'." != '' THEN CONCAT("."'".$path."'".", ".'gst_certificate'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as gst_certificate"),

                                )

                            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                            ->leftjoin('products' ,'obf.product_id' ,'products.id')

                            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

                            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                            ->where(['obf.id' => $id])

                            ->first();      

            }

            return view('obf.rto')->with(['data' =>$data,'sales' => $sales ,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'finance' => $finance ,'lead' => $lead,'states' => $states,'districts' => $districts,'cities' => $cities]);

        }

    /** RTO view */

    

    /** fasttag view */

        public function fasttagview(Request $request){

            if(auth()->user()->can('obf-fasttagview')){

                $id = base64_decode($request->id);

                $path = URL('/uploads/kyc').'/';



                $sales = User::role('sales')->select('id' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active'])->get();

                $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

                $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

                $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

                $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

                

                $data = OBF::select('obf.id','obf.sales_person_id',

                                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type','obf.customer_type_new','obf.fuel_type' ,'branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' ,'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id' ,'products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS fasttag_brand_name','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at',

                                DB::Raw("CASE

                                            WHEN ".'pan_image'." != '' THEN CONCAT("."'".$path."'".", ".'pan_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as pan_image"),

                                DB::Raw("CASE

                                            WHEN ".'adhar_image'." != '' THEN CONCAT("."'".$path."'".", ".'adhar_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as adhar_image"),

                                DB::Raw("CASE

                                            WHEN ".'licance_image'." != '' THEN CONCAT("."'".$path."'".", ".'licance_image'.")

                                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                                        END as licance_image"),
                                        
                                DB::Raw("CASE WHEN ".'finance_image'." != '' THEN CONCAT("."'".$path."'".", ".'finance_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as finance_image"),
                                
                                DB::Raw("CASE WHEN ".'rto_image'." != '' THEN CONCAT("."'".$path."'".", ".'rto_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as rto_image"),
                                
                                DB::Raw("CASE WHEN ".'insurance_image'." != '' THEN CONCAT("."'".$path."'".", ".'insurance_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as insurance_image"),
                                
                                DB::Raw("CASE WHEN ".'handicap_image'." != '' THEN CONCAT("."'".$path."'".", ".'handicap_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as handicap_image"),
                                
                                DB::Raw("CASE WHEN ".'passport_document'." != '' THEN CONCAT("."'".$path."'".", ".'passport_document'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as passport_document"),
                                
                                DB::Raw("CASE WHEN ".'gst_certificate'." != '' THEN CONCAT("."'".$path."'".", ".'gst_certificate'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as gst_certificate"),
                                
                                DB::Raw("CASE WHEN ".'fasttag_image'." != '' THEN CONCAT("."'".$path."'".", ".'fasttag_image'.") ELSE CONCAT("."'".$path."'".", 'default.jpg') END as fasttag_image"),

                                )

                            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                            ->leftjoin('products' ,'obf.product_id' ,'products.id')

                            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

                            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                            ->where(['obf.id' => $id])

                            ->first();      

            }

            return view('obf.fasttag')->with(['data' =>$data,'sales' => $sales ,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'finance' => $finance ,'lead' => $lead]);

        }

    /** fasttag view */



    /** Edit */

        public function edit(Request $request){

            ini_set('memory_limit', '1024M');   

            $id = base64_decode($request->id);

            $path = URL('/uploads/kyc').'/';

            $obf_created_by_id = OBF::where('id',$id)->first();

            $sales = User::role(['sales','KEC'])->select('id' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active','id'=>$obf_created_by_id->created_by])->get();



            

                $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

                //$branch = Branch::select('id' , 'name' ,'city','tax_percentage')->where(['status' => 'active'])->get();

                //$branch = Branch::select('*')->where(['status' => 'active'])->get();



                //branch selection

                $branch = Branch::select('*');

                if(!empty(auth()->user()->branch) && auth()->user()->branch != '' && auth()->user()->branch != NULL){

                    $branch_arr = explode(',', auth()->user()->branch);

                    if(!empty($branch_arr)){

                        $branch = $branch->whereIn('id',$branch_arr);    

                    }

                }                        

                $branch = $branch->where(['status' => 'active'])->get(); 

                //branch selection






                $states = State::select('id','name')->where(['status' => 'active'])->orderBy('name', 'asc')->get();
                $districts = District::select('id','name')->where(['status' => 'active'])->orderBy('name', 'asc')->get();
                $cities = City::select('id','name')->where(['status' => 'active'])->orderBy('name', 'asc')->get();
                $passing_code = Db::table('rto_codes')->select('id',DB::raw("CONCAT(code, ' - ', area) as code_area"))->orderBy('code_area', 'asc')->get();
                $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();    

                $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                $pricelist_master = DB::table('pricelist_master')->select('id','car_model')->get();

                $occupation_lists = Occupation::select('id', 'occupation_title')->where('status', 'active')->get();


                $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

                $data = OBF::select('obf.id','obf.sales_person_id',

                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id','obf.car_model as obf_car_model','obf.booking_date' ,'obf.customer_name' ,'obf.customer_type','obf.customer_type_new' ,'branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' , 'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id','obf.fuel_type','products.veriant','products.car_model','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'obf.fasttag_brand_name AS fasttag_brand_name','registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount' ,'fasttags.id AS fasttag_id','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','obf.offer_kin','obf.offer_ib', 'obf.offer_ib_amount', 'obf.offer_kin_amount','obf.gst_required', 'obf.aadhar_pan_link','obf.aadhar_pan_image','obf.state_id','obf.district_id','obf.city_id','obf.ship_to_required','obf.ship_to_customer_name','obf.ship_to_address',
                                    'obf.ship_to_state_id','obf.ship_to_district_id','obf.ship_to_city_id','obf.finance_image','obf.rto_image','obf.insurance_image','obf.fasttag_image','obf.is_csd','obf.rto_custom_handling_charges','obf.tentetive_delivery_date','obf.passport_document','obf.gst_certificate',

                'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status','obf.way_off','obf.final_on_road_price_after_way_off','obf.foc_accessories',

                'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.pricelist_id','obf.registration_tax_id','obf.municipal_tax_id','obf.municipal_tax_applicable','obf.tcs_tax_id','obf.nominee_dob','obf.convinience_program','obf.offer_image',


                    'obf.step1_remarks','obf.step3_remarks','obf.step4_remarks','obf.step5_remarks','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id',



                 'obf_finance.finance_name','obf_finance.repo_rate','obf.other_accesssories_prise','obf.other_accesssories_detail','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.rsa_master_obf','obf.ccs_master_obf','obf_finance.disbursement','obf_finance.finance_type','obf.step2_remarks','obf.step1_remarks','obf_finance.payout_amount','obf_finance.lumsum_amount','obf_finance.total_payout_amount','obf.number_plate AS number_plate','mcp.id as mcp_id','mcp.name as mcp_name','mcp.amount as mcp_amount','obf.anniversary_date','obf.municipal_tax_type','obf.municipal_custom_handling_charges','obf.discount_flag','obf.tl_discount','obf.sm_discount','obf.gm_discount','obf.bh_discount','obf.ceo_discount','obf.md_discount','obf.discount_year',


               /* DB::Raw("CASE

                            WHEN ".'obf_insurance.documents'." != '' THEN CONCAT("."'".$path."'".", ".'obf_insurance.documents'.")

                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                        END as documents"),*/

               /* DB::Raw("CASE

                            WHEN ".'pan_image'." != '' THEN CONCAT("."'".$path."'".", ".'pan_image'.")

                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                        END as pan_image"),*/

             /*   DB::Raw("CASE

                            WHEN ".'adhar_image'." != '' THEN CONCAT("."'".$path."'".", ".'adhar_image'.")

                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                        END as adhar_image"),

                DB::Raw("CASE

                            WHEN ".'licance_image'." != '' THEN CONCAT("."'".$path."'".", ".'licance_image'.")

                            ELSE CONCAT("."'".$path."'".", 'default.jpg')

                        END as licance_image"),*/

                )

                        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                        ->leftjoin('products' ,'obf.product_id' ,'products.id')

                        ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                        ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                        ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                        ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                        ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

                        ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                        ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                        ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                        ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                        ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                        //->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')

                        ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

                        ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')

                        ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
                        
                        ->leftjoin('mcp','obf.convinience_program','mcp.id')

                        ->where(['obf.id' => $id])

                        ->first();    



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





                        /*'obf_insurance.ncb','obf_insurance.date_of_insurance','obf_insurance.last_time_of_insurance','obf_insurance.time_of_insurance','obf_insurance.company_name AS insurance_company_name','obf_insurance.ncb_amount','obf_insurance.policy_number','obf_insurance.status as insurance_status',

                        'obf_insurance.documents',

                */

                $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  



                /*echo "<pre>";

                print_r($ObfInsurance);

                die('s');*/







                        

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

           //$Carvarient = Carvarient::where(['status' => 'active'])->get();  



                /*$Carmodel = Carmodel::select('car_model.name as car_name','car_model.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

                    ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

                    ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                    ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                    ->where('car_model.status', '=', 'active')

                    ->get();*/



                   /* car_model

                    Variant*/







            $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();



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

            

            // $Carvarient = Carvarient::where(['status' => 'active','car_model'=>$data->car_model,'fule_type'=>$data->fuel_type])->get(); 
            
            $Carvarient = Carvarient::where([
                'car_model' => $data->car_model,
                'fule_type' => $data->fuel_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();


            //dd($data->car_model);

            $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color','car_varient.id as varient_id','fule_type.id as fuel_id')

                        ->leftJoin('products','products.id','=','obf.product_id')

                        ->leftJoin('car_model','car_model.id','=','products.car_model')

                        ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
                        
                        ->leftJoin('fule_type','fule_type.id','=','obf.fuel_type')

                        ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                        ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                        ->where('obf.id', '=', $id)  

                        ->first();
                       



            $Inventory_data = [];

            if($data->inventory_id != NULL){

                $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    

            }



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



            $user = auth()->user();

            

            $user_role = $user->getRoleNames();

        
            
            $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->first();
                


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

        

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



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

            $rsa_all = RSA::where(['rsa_ccs'=>'RSA','rsa.status' => 'active','deleted_at' => 0])->get();
            $ccs_all = RSA::where(['rsa_ccs'=>'RSA','rsa.status' => 'active','deleted_at' => 0])->get();
            
            view()->share('rsa_all',$rsa_all);
            view()->share('ccs_all',$ccs_all);

            $rsa = RSA::select('rsa.id','rsa.name','rsa.amount','rsa.car_model')->where(['rsa_ccs'=>'RSA','rsa.status' => 'active','car_model' => $data->obf_car_model,'deleted_at' => 0])->get();
            
            $ccs = RSA::select('rsa.id','rsa.name','rsa.amount','rsa.car_model')->where(['rsa_ccs'=>'CCS','rsa.status' => 'active','car_model' => $data->obf_car_model,'deleted_at' => 0])->get();
            
            $accessory_sum = 0;

            if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){

                $accessory_id_arr = explode(' ,', $data->accessory_id);

                if(!empty($accessory_id_arr)){

                    $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           

                }

            }

            

            $auth = User::select('department.name')->join('department','department.id','users.department_id')->where('users.id',auth()->user()->id)->first();

            $depart = $auth->name ?? ''; 

            $rto_master = rto_master::select('amount')->where('status','=','active')->first();

            $rto_amount = $rto_master->amount;

            $offers = OBF::select('offer_kin','offer_ib')->where('obf.id','=',$id)->first();

            //dd($offers->offer_ib);

            $kin = $offers->offer_kin;

            $kin_o = explode(',', $kin);

            //dd($kin);

            //dd(explode(',', $kin));

            foreach($kin_o as $k){

                $kin_title = Offer::select('title')->where('id','=',$k)->first();           

            }

            //dd($kin_title->title);



            $ib = $offers->offer_ib;

            $ib_o = explode(',', $ib);



            foreach($ib_o as $i){

              $ib_title = Offer::select('title')->where('id','=',$i)->first();

            }
            
            // Code For Make-deal Data Show Only in Insurance & RTO Form
            $make_deal_data = OBF::select('obf.id','obf.sales_person_id',

            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.final_on_road_price_after_way_off' ,'obf.customer_type','obf.customer_type_new' ,'obf.booking_date','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' , 'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id','products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'obf.fasttag_brand_name AS fasttag_brand_name','registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount_new' ,'fasttags.id AS fasttag_id','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','allocation.tentetive_delivery_date','Team_master.team_name','obf.other_accesssories_prise','obf.municipal_custom_handling_charges','obf.rto_custom_handling_charges',
    
            'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',
    
            'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.pricelist_id','obf.registration_tax_id','obf.municipal_tax_id','obf.municipal_tax_applicable','obf.tcs_tax_id','obf.nominee_dob', 'obf.convinience_program',
    
            'obf.step1_remarks','obf.step3_remarks','obf.step4_remarks','obf.step5_remarks','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id',
    
            'obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.rsa_master_obf',
    
            'car_model.name AS car_model_name','car_varient.name AS car_varient_name','interiorcolor.name AS interiorcolor_name','exteriorcolor.name AS exteriorcolor_name','inventory.key_number','inventory.engine_number','inventory.chassis_number','inventory.vin_number', 'obf_insurance.company_name AS insurance_company_name','obf_insurance.ncb_amount','obf.offer_ib_amount','obf.offer_kin_amount','obf.offer_amount','inventory.purchase_price','inventory.aging_days','inventory.remark',
            
            'make_deal.obf_id','make_deal.purchase_gst_tax_deal','make_deal.final_deal_amt','make_deal.deal_amt','make_deal.gst_tax_deal','make_deal.cess_tax_deal','make_deal.tcs_tax_deal','make_deal.municipal_tax_deal','make_deal.municipal_custom_handling_charges_deal','make_deal.rto_deal','make_deal.insurance_deal','make_deal.rto_cutom_handling_charges_deal','make_deal.created_by','make_deal.remark','pricelist_master.rto_custome_handling_charges','mcp.id as mcp_id','mcp.name as mcp_name','mcp.amount as mcp_amount','rsa.id as rsa_id','rsa.name as rsa_name','rsa.amount as rsa_amount','rsa.rsa_ccs as rsa_type')
    
            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
            ->leftjoin('products', 'obf.product_id', 'products.id')
            ->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')
            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
            ->leftjoin('allocation' ,'obf.id' ,'allocation.obf_id')
            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')
            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')
            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
            ->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')
            ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
            ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')
            ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
            ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
            ->leftjoin('Team_master','Team_master.id','users.team_name')
            ->leftjoin('make_deal','obf.id','make_deal.obf_id')
            ->leftjoin('pricelist_master', 'obf.pricelist_id', 'pricelist_master.id')
            ->leftjoin('mcp','obf.convinience_program','mcp.id')
            ->leftjoin('rsa','obf.rsa_master_obf','rsa.id')
            ->where(['obf.id' => $id])->first(); 
    
            $make_deal_branch = Branch::select('start_value1', 'end_value1', 'tax_percentage1', 'start_value2', 'end_value2', 'tax_percentage2')->where(['status' => 'active','id' => $make_deal_data->branch_id])->first();
           
            $price_list_name_data = DB::table('pricelist_master')->select('basic','price_list_name','gst_percentage','gst_amount','cess_percentage','cess_amount')->where('id',  $make_deal_data->pricelist_id)->first();
    
            $make_deal_rto_data = DB::table('rto_master')->select('rto_type', 'rto_tax_individual', 'rto_tax_company', 'totali_individual_charges','totalcharges')->Where('rto_type', 'like', $make_deal_data->customer_type . '%')->orderBy('id', 'DESC')->first();
    
            $make_deal_accessory_sum = 0;
    
            if(!empty($make_deal_data->accessory_id) && $make_deal_data->accessory_id != NULL && $make_deal_data->accessory_id != ''){
                $accessory_id_arr = explode(' ,', $make_deal_data->accessory_id);
                if(!empty($accessory_id_arr)){
                    $make_deal_accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');           
                }
            }
            
            $my_con_program = Mcp::where(['status' => 'active','car_model' => $Cardata->car_id])->get();

            return view('obf.edit')->with(['data' =>$data,'sales' => $sales ,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'finance' => $finance ,'lead' => $lead,'pricelist_master' => $pricelist_master,'Carmodel'=>$Carmodel,'Cardata'=>$Cardata,'user_role'=> $user_role[0],'Carmodel_arr'=>$Carmodel_arr,'Product_data' => $Product_data, 'mcp' => $mcp, 'OtherOne' => $OtherOne, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule_data' => $fule_data, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'ccs' => $ccs,'accessory_sum' => $accessory_sum,'depart'=>$depart,'rto_amount'=>$rto_amount,'kin_title'=>$kin_title,'ib_title'=>$ib_title,'Carvarient'=>$Carvarient, 'make_deal_data'=>$make_deal_data, 'make_deal_branch' => $make_deal_branch, 'price_list_name_data' => $price_list_name_data, 'make_deal_rto_data'=>$make_deal_rto_data, 'make_deal_accessory_sum'=>$make_deal_accessory_sum,'states' => $states,'districts' => $districts,'cities' => $cities,'occupation_lists'=> $occupation_lists,'my_con_program'=>$my_con_program,'passing_code'=>$passing_code] );

        }

    /** Edit */



    /** update */

        public function update(Request $request){

            if($request->ajax()){ 

                return true;

            }



            if(empty($request->accessories)){

                $request->accessories = [];

            }



            if(empty($request->priclist_detail)){

                $request->priclist_detail = [];

            }



            if(empty($request->other_details_1)){

                $request->other_details_1 = [];

            }



            if(empty($request->other_details_2)){

                $request->other_details_2 = [];

            }
            
            $detail_value_arr = [];

            if(!empty($request->priclist_detail)){

                foreach ($request->priclist_detail as $value) {

                    $arr_value = explode('__', $value);

                    $detail_value_sub_arr = [];

                    $detail_value_sub_arr['detail_field'] = $arr_value[0];

                    $detail_value_sub_arr['value_field'] = $arr_value[1]; 

                    $detail_value_arr[] = $detail_value_sub_arr; 

                }

            }

            $detail_value_arr_json = json_encode($detail_value_arr);



            /*echo "<pre>";

            var_dump($detail_value_arr_json);

            die('s');*/

            

            if(isset($request->id)){

                $ext_record = OBF::find($request->id);

            }



            if(!empty($request->dob) && $request->dob != '' && $request->dob != NULL)

            {

               $request->dob = date("Y-m-d",strtotime($request->dob));        

            }



            if(!empty($request->nominee_dob) && $request->nominee_dob != '' && $request->nominee_dob != NULL)

            {

               $request->nominee_dob = date("Y-m-d",strtotime($request->nominee_dob));        

            }



            /*var_dump($request->convinience_program );

            die('s');*/


            //offer type



                $offer_type = $request->offer_type;



                $offer_kin = $request->offer_kin;                

                if($offer_kin != null){

                    $offerkin = implode(',',$offer_kin);

                }

                else{

                    $offerkin = null;

                }



                $offer_ib = $request->offer_ib;

                if($offer_ib != null){

                    $offerib = implode(',',$offer_ib);

                }

                else{

                    $offerib = null;

                }

                if($request->offer_amount != null){

                   // $ex_showroom_price = $request->with_offer_ex_showroom_price;

                    $ex_showroom_price = $request->deal_price;

                }else{

                    $ex_showroom_price = $request->ex_showroom_price;

                }
                
            $old_status = $request->old_status ?? null;
            if((isset($old_status) && !empty($old_status)) && $old_status === 'obf_tl_rejected'){
                $status = 'pending';
            } else if((isset($old_status) && !empty($old_status)) && $old_status === 'obf_sm_rejected') {
                $status = 'obf_tl_accepted';
            } else if((isset($old_status) && !empty($old_status)) && $old_status === 'obf_gm_rejected') {
                $status = 'obf_sm_accepted';
            } else if((isset($old_status) && !empty($old_status)) && $old_status === 'obf_accountant_rejected') {
                $status = 'obf_gm_accepted';
            } else {
                $status = $request->obf_status;
            }
            $crud = [

                'booking_date' => \Carbon\Carbon::parse($request->created_at_stamp)->format('Y-m-d H:i:s'),

                'customer_name' => strtoupper($request->customer_name),

                'customer_birthdate' => $request->customer_birthdate ?? null,
                
                'is_csd' => $request->is_csd == 'Yes'?1:0,

                'customer_type' => $request->customer_type,

                'customer_type_new' => $request->customer_type_new,

                'branch_id' => $request->branch,

                'company_name' => $request->company_name ?? null,

                'einvoicing_applicable' => $request->einvoapp ?? null,
                
                'gst_required' => $request->gst_required === 'yes' ? 'yes' : 'no',

                'gst' => $request->gst ?? null,

                'address' => $request->address_1 ?? null,

                'registration' => $request->address_2 ?? null,

                'email' => $request->email ?? null,

                'pan_number' => $request->pan_number ?? null,

                'adhar_number' => $request->adhar_number ?? null,

                'licance_number' => $request->license_number ?? null,

                'contact_number' => $request->contact_number ?? null,

                'dob' => $request->dob ?? null,

                'nominee_dob' => $request->nominee_dob ?? null,

                'nominee_name' => $request->nominee_name ?? null,

                'nominee_reletion' => $request->nominee_relation ?? null,

                'nominee_age' => $request->nominee_age ?? null,

                'occupation' => $request->occupation ?? null,

                'sales_person_id' => $request->sales_person_name ?? null,
                
                'car_model' => $request->car_name ??null,

                'product_id' => $request->product_id ?? null,

                'fuel_type' => $request->fuel_type ?? null,

                'offer_type' => $offer_type ?? null,

                //'offer_kin'=>$offerkin ?? null,
                'offer_kin' => $offerkin ?? $request->offers_kin_id ?? null,

                //'offer_ib'=>$offerib ?? null,
                'offer_ib' => $offerib ?? $request->offers_ib_id ?? null,

                'offer_ib_amount'=>$request->offers_ib_amount ?? null,

                'offer_kin_amount'=>$request->offers_kin_amount ?? null,

                'offer_amount' => $request->offe_amount ?? null,

                'deal_price' =>$request->deal_price ?? null,

                'way_off'=>$request->way_off ?? null,
                
                'discount_flag' => $request->discount_flag ?? null,
                
                'foc_accessories' => $request->foc_accessories ?? null, 

                'final_on_road_price_after_way_off' =>$request->final_on_road_price_after_way_off ?? null,

                'ex_showroom_price' => $request->ex_showroom_price ?? null,

                'registration_tax_id' => $request->registration_tax ?? null,
                
                'rto_custom_handling_charges' => $request->rto_custom_handling_charges ?? null,

                'insurance_id' => $request->insurance ?? null,

                'municipal_tax_id' => $request->municipal_tax ?? null,

                'municipal_tax_applicable' => $request->municipal_tax_applicable ?? 2,
                
                'municipal_tax_type' => $request->municipal_tax_type ?? null,
                    
                'municipal_custom_handling_charges' => $request->municipal_custom_handling_charges ?? null,

                'tcs_tax_id' => $request->tcs_tax ?? null,

                'accessory_id' => implode(" ,",$request->accessories) ?? null,

                'priclist_detail' => $detail_value_arr_json,

                'extanded_warranty_id' => $request->extended_warranty ?? null,

                'fasttag_brand_name' => $request->fasttag_brand_name ?? null,

                'trade_car_name' => $request->trade_car_name ?? null,

                'trade_car_value' => $request->trade_car_value ?? null,

                'convinience_program' => $request->convinience_program ?? null,

                'other_details_1' => implode(" ,",$request->other_details_1) ?? null,

                'other_details_2' => implode(" ,",$request->other_details_2) ?? null,

                'rsa_master_obf' => $request->rsa_master_obf ?? null,
                
                'ccs_master_obf' => $request->ccs_master_obf ?? null,

                'on_road_price' => $request->on_road_price ?? null,

                'on_road_price_word' => $request->on_road_price_word ?? null,

                // 'finance_id' => $request->finance_name ?? null,

                // 'finance_branch_id' => $request->finance_branch_name ?? null,

                'lead_id' => $request->lead ?? null,

                'sub_lead_id' => $request->sub_lead_id ?? null,

                'booking_amount' => $request->booking_amount ?? null,

                'mode_of_payment' => $request->mode_of_payment ?? null,

                'pricelist_id' => $request->pricelist_manager_id ?? null,

                'step1_remarks' => $request->step1_remarks ?? null,

                'step2_remarks' => $request->step2_remarks ?? null,

                'step3_remarks' => $request->step3_remarks ?? null,

                'step4_remarks' => $request->step4_remarks ?? null,

                'step5_remarks' => $request->step5_remarks ?? null,

                //'status' => 'finance_apporve',

                'status'=> $status,
                
                'aadhar_pan_link' => $request->aadhar_pan_link === 'yes' ? 'yes' : 'no',

                'other_accesssories_detail' => $request->other_accesssories_detail,

                 'other_accesssories_prise' => $request->other_accesssories_prise,

                'created_at' => $request->created_at_stamp,

                'created_by' => $request->created_by_id,

                'updated_at' => date('Y-m-d H:i:s'),

                'updated_by' => auth()->user()->id,
                
                'state_id' => $request->state_id??null,

                'district_id' => $request->district_id??null,
                
                'city_id' => $request->city_id??null,
                
                'ship_to_required' => $request->ship_to_required === 'yes' ? 'yes' : 'no',
                
                'ship_to_customer_name' => $request->ship_to_customer_name??null,
                
                'ship_to_address' => $request->ship_to_address??null,
                
                'ship_to_state_id' => $request->ship_to_state_id??null,
                
                'ship_to_district_id' => $request->ship_to_district_id??null,
                
                'ship_to_city_id' => $request->ship_to_city_id??null,
                
                'anniversary_date' => $request->anniversary_date ?? null,
                
                'number_plate'=> $request->number_plate??null,
                
                'tentetive_delivery_date' => $request->tentative_delivery_date ?? null,
                
                'passport_document' => $request->passport_document ?? null,
                
                'gst_certificate' => $request->gst_certificate ?? null,
                
                'insurance_company_name' => $request->insurance_company_name ?? null,
                
                'discount_year' => $request->discount_year ?? null,
                
                'rto_passing_id' => $request->rto_passing_id ?? null,

            ];
            
           
            

            // dd($request->file('pan_image'));

            // Pan Image

                /*if(!empty($request->file('pan_image'))){

                    $file = $request->file('pan_image');

                    $filenameWithExtension = $request->file('pan_image')->getClientOriginalName();

                    $filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);

                    $extension = $request->file('pan_image')->getClientOriginalExtension();

                    $filenameToStore = time()."_".$filename.'.'.$extension;

    

                    $folder_to_upload = public_path().'/uploads/kyc/';

    

                    if(!\File::exists($folder_to_upload))

                        \File::makeDirectory($folder_to_upload, 0777, true, true);

    

                    $crud['pan_image'] = $filenameToStore;

                }else{

                    $crud['pan_image'] = $ext_record->pan_image;

                }*/

               /* var_dump($data['pan_image']);

                die('s');*/

            // Pan Image



            // Aadhar Image

                /*if(!empty($request->file('adhar_image'))){

                    $file_two = $request->file('adhar_image');

                    $filenameWithExtension_two = $request->file('adhar_image')->getClientOriginalName();

                    $filename_two = pathinfo($filenameWithExtension_two, PATHINFO_FILENAME);

                    $extension_two = $request->file('adhar_image')->getClientOriginalExtension();

                    $filenameToStore_two = time()."_".$filename_two.'.'.$extension_two;

    

                    $folder_to_upload = public_path().'/uploads/kyc/';

    

                    if(!\File::exists($folder_to_upload))

                        \File::makeDirectory($folder_to_upload, 0777, true, true);

    

                    $crud['adhar_image'] = $filenameToStore_two;

                }else{

                    $crud['adhar_image'] = $ext_record->adhar_image;

                }*/





            // Aadhar Image



            // Licance Image

               /* if(!empty($request->file('licance_image'))){

                    $file_three = $request->file('licance_image');

                    $filenameWithExtension_three = $request->file('licance_image')->getClientOriginalName();

                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                    $extension_three = $request->file('licance_image')->getClientOriginalExtension();

                    $filenameToStore_three = time()."_".$filename_three.'.'.$extension_three;

    

                    $folder_to_upload = public_path().'/uploads/kyc/';

    

                    if(!\File::exists($folder_to_upload))

                        \File::makeDirectory($folder_to_upload, 0777, true, true);

    

                    $crud['licance_image'] = $filenameToStore_three;

                }else{

                    $crud['licance_image'] = $ext_record->licance_image;

                }*/



                // other documents

                $other_documents = '';

                $other_documents_name_arr = [];

                if(!empty($request->file('other_documents'))){

                    $other_documents_arr = $request->file('other_documents');

                    foreach($other_documents_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "other_documents_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($other_documents_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn))

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($other_documents_name_arr)){

                        $other_documents = implode(",",$other_documents_name_arr);

                    }

                    $crud['other_documents'] = $other_documents;

                }else{

                   // $other_documents_name_arr = [];

                }



                // pan_image  

                if(!empty($request->file('pan_image'))){

                    $pan_image = '';

                    $pan_image_name_arr = [];



                    $pan_image_arr = $request->file('pan_image');

                    foreach($pan_image_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "pan_image_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($pan_image_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn))

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($pan_image_name_arr)){

                        $pan_image = implode(",",$pan_image_name_arr);

                    }

                    $crud['pan_image'] = $pan_image;

                }



                // adhar_image        

                if(!empty($request->file('adhar_image'))){

                    $adhar_image = '';

                    $adhar_image_name_arr = [];



                    $adhar_image_arr = $request->file('adhar_image');

                    foreach($adhar_image_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "adhar_image_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($adhar_image_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn))

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($adhar_image_name_arr)){

                        $adhar_image = implode(",",$adhar_image_name_arr);

                    }

                    $crud['adhar_image'] = $adhar_image;

                }
                
                
                
                // offer_image  

                if(!empty($request->file('offer_image'))){

                    $offer_image = '';

                    $offer_image_name_arr = [];



                    $offer_image_arr = $request->file('offer_image');

                    foreach($offer_image_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "offer_image_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($offer_image_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn))

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($offer_image_name_arr)){

                        $offer_image = implode(",",$offer_image_name_arr);

                    }

                    $crud['offer_image'] = $offer_image;

                }



                // licance_image        

                if(!empty($request->file('licance_image'))){

                    $licance_image = '';

                    $licance_image_name_arr = [];



                    $licance_image_arr = $request->file('licance_image');

                    foreach($licance_image_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "licance_image_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($licance_image_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn))

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($licance_image_name_arr)){

                        $licance_image = implode(",",$licance_image_name_arr);

                    }

                    $crud['licance_image'] = $licance_image;

                }


                //Aadhar Pan Image
                
                if(!empty($request->file('aadhar_pan_image'))){

                    $aadhar_pan_image = '';

                    $aadhar_pan_image_name_arr = [];



                    $aadhar_pan_image_arr = $request->file('aadhar_pan_image');

                    foreach($aadhar_pan_image_arr as $key => $file_value){

                        $filenameWithExtension_three = $file_value->getClientOriginalName();

                        $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);

                        $extension_three = $file_value->getClientOriginalExtension();

                        $filenameToStore_three_new = "aadhar_pan_image_".time()."_".$filename_three.'.'.$extension_three;



                        array_push($aadhar_pan_image_name_arr, $filenameToStore_three_new);                        

                        $folder_to_upload_sn = public_path().'/uploads/kyc/';

                        

                        if(!\File::exists($folder_to_upload_sn))

                            \File::makeDirectory($folder_to_upload_sn, 0777, true, true);

                         $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);

                    }

                    if(!empty($aadhar_pan_image_name_arr)){

                        $aadhar_pan_image = implode(",",$aadhar_pan_image_name_arr);

                    }

                    $crud['aadhar_pan_image'] = $aadhar_pan_image;

                }
                    
                //upload finance image
                $finance_image = '';
                if (!empty($request->file('finance_image'))) {
                    $finance_image_name_arr = [];
                    $finance_image_arr = $request->file('finance_image');
                    foreach ($finance_image_arr as $key => $file_value) {
                        $filenameWithExtension = $file_value->getClientOriginalName();
                        $filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
                        $extension = $file_value->getClientOriginalExtension();
                        $filenameToStore = "finance_image_" . time() . "_" . $filename . '.' . $extension;
                        $finance_image_name_arr[] = $filenameToStore;
                
                        $uploadPath = public_path('/uploads/kyc/');
                        if (!\File::exists($uploadPath)) {
                            \File::makeDirectory($uploadPath, 0777, true, true);
                        }
                        $file_value->move($uploadPath, $filenameToStore);
                    }
                    $finance_image = implode(",", $finance_image_name_arr);
                } else {
                    $finance_image = $existingRecord->finance_image ?? '';
                }
                $crud['finance_image'] = $finance_image;
                
                //upload rto image
                $rto_image = '';
                if (!empty($request->file('rto_image'))) {
                $rto_image_name_arr = [];
                $rto_image_arr = $request->file('rto_image');
                foreach ($rto_image_arr as $key => $file_value) {
                    $filenameWithExtension = $file_value->getClientOriginalName();
                    $filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
                    $extension = $file_value->getClientOriginalExtension();
                    $filenameToStore = "rto_image_" . time() . "_" . $filename . '.' . $extension;
                    $rto_image_name_arr[] = $filenameToStore;
                    $uploadPath = public_path('/uploads/kyc/');
                    if (!\File::exists($uploadPath)) {
                        \File::makeDirectory($uploadPath, 0777, true, true);
                    }
                    $file_value->move($uploadPath, $filenameToStore);
                }
                    $rto_image = implode(",", $rto_image_name_arr);
                    } else {
                    $rto_image = $existingRecord->rto_image ?? '';
                    }
                $crud['rto_image'] = $rto_image;
                
                //upload fasttag image
                $fasttag_image = '';
                if (!empty($request->file('fasttag_image'))) {
                $fasttag_image_name_arr = [];
                $fasttag_image_arr = $request->file('fasttag_image');
                foreach ($fasttag_image_arr as $key => $file_value) {
                    $filenameWithExtension = $file_value->getClientOriginalName();
                    $filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
                    $extension = $file_value->getClientOriginalExtension();
                    $filenameToStore = "fasttag_image_" . time() . "_" . $filename . '.' . $extension;
                    $fasttag_image_name_arr[] = $filenameToStore;
                    $uploadPath = public_path('/uploads/kyc/');
                    if (!\File::exists($uploadPath)) {
                        \File::makeDirectory($uploadPath, 0777, true, true);
                    }
                    $file_value->move($uploadPath, $filenameToStore);
                }
                    $fasttag_image = implode(",", $fasttag_image_name_arr);
                    } else {
                    $fasttag_image = $existingRecord->fasttag_image ?? '';
                    }
                $crud['fasttag_image'] = $fasttag_image;
                
                //upload passport document
                $passport_document = '';
                if (!empty($request->file('passport_document'))) {
                $passport_document_name_arr = [];
                $passport_document_arr = $request->file('passport_document');
                foreach ($passport_document_arr as $key => $file_value) {
                    $filenameWithExtension = $file_value->getClientOriginalName();
                    $filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
                    $extension = $file_value->getClientOriginalExtension();
                    $filenameToStore = "passport_document_" . time() . "_" . $filename . '.' . $extension;
                    $passport_document_name_arr[] = $filenameToStore;
                    $uploadPath = public_path('/uploads/kyc/');
                    if (!\File::exists($uploadPath)) {
                        \File::makeDirectory($uploadPath, 0777, true, true);
                    }
                    $file_value->move($uploadPath, $filenameToStore);
                }
                    $passport_document = implode(",", $passport_document_name_arr);
                    } else {
                    $passport_document = $existingRecord->passport_document ?? '';
                    }
                $crud['passport_document'] = $passport_document;
                
                //upload gst certificate
                $gst_certificate = '';
                if (!empty($request->file('gst_certificate'))) {
                $gst_certificate_name_arr = [];
                $gst_certificate_arr = $request->file('gst_certificate');
                foreach ($gst_certificate_arr as $key => $file_value) {
                    $filenameWithExtension = $file_value->getClientOriginalName();
                    $filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
                    $extension = $file_value->getClientOriginalExtension();
                    $filenameToStore = "gst_certificate_" . time() . "_" . $filename . '.' . $extension;
                    $gst_certificate_name_arr[] = $filenameToStore;
                    $uploadPath = public_path('/uploads/kyc/');
                    if (!\File::exists($uploadPath)) {
                        \File::makeDirectory($uploadPath, 0777, true, true);
                    }
                    $file_value->move($uploadPath, $filenameToStore);
                }
                    $gst_certificate = implode(",", $gst_certificate_name_arr);
                    } else {
                    $gst_certificate = $existingRecord->gst_certificate ?? '';
                    }
                $crud['gst_certificate'] = $gst_certificate;

                        // $rto = [

                        // 'obf_id'=>$request->id,

                        // 'rto_type' => $request->rto_type ?? null,

                        // 'registration_date' => $request->registration_date ?? null,

                        // 'application_number' => $request->application_number ?? null,

                        // 'temporary_number' => $request->temporary_number ?? null,

                        // 'final_amount' => $request->final_amount ?? null,

                        // 'vehicle_number' => $request->vehicle_number ?? null,

                        // 'rto_type' => $request->rto_type ?? null,

                        // 'status' => $request->rto_status ?? null,

                        // ];

                        // // DB::enableQueryLog();

                        // if(DB::table('obf_rto')->where("obf_id", "=", $request->id)->exists()){

                        //     DB::table('obf_rto')->where(['obf_id' => $request->id])->update($rto);
                            
                        //     $rto_crud = [
                        //         'module_nm' => 'obf_rto_update',
                        //         'module_id' => $request->id,
                        //         'status' => 'rto_update',
                        //         'remark' => 'rto_update',
                        //         'created_at' => date('Y-m-d H:i:s'),
                        //         'created_by' => auth()->user()->id,
                        //     ];
                        //     \DB::table('logs')->insert($rto_crud);

                        // }else{

                        //     DB::table('obf_rto')->insert($rto);
                            
                        //     $rto_crud = [
                        //         'module_nm' => 'obf_rto_create',
                        //         'module_id' => $request->id,
                        //         'status' => 'rto_create',
                        //         'remark' => 'rto_create',
                        //         'created_at' => date('Y-m-d H:i:s'),
                        //         'created_by' => auth()->user()->id,
                        //     ];
                        //     \DB::table('logs')->insert($rto_crud);

                        // }

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


                        // $fasttag = [

                        // 'obf_id'=>$request->id,

                        // 'fasttag_number' => $request->fasttag_number ?? null, 

                        // 'fasttag_brand' => $request->fasttag_brand ?? null,

                        // 'date_of_issue' => $request->date_of_issue ?? null,

                        // 'fasttag_amount' => $request->fasttag_amount ?? null,

                        // 'opening_stock' => $request->opening_stock ?? null,

                        // 'status' => $request->fasttag_status ?? null,

                        // ];

                        // // DB::enableQueryLog();

                        // if(DB::table('obf_fasttag')->where("obf_id", "=", $request->id)->exists()){

                        //     DB::table('obf_fasttag')->where(['obf_id' => $request->id])->update($fasttag);
                            
                        //     $fasttag_crud = [
                        //         'module_nm' => 'obf_fasttag_update',
                        //         'module_id' => $request->id,
                        //         'status' => 'fasttag_update',
                        //         'remark' => 'Fasttag Update',
                        //         'created_at' => date('Y-m-d H:i:s'),
                        //         'created_by' => auth()->user()->id,
                        //     ];
                        //     \DB::table('logs')->insert($fasttag_crud);

                        // }else{

                        //     DB::table('obf_fasttag')->insert($fasttag);
                            
                        //     $fasttag_crud = [
                        //         'module_nm' => 'obf_fasttag_create',
                        //         'module_id' => $request->id,
                        //         'status' => 'fasttag_create',
                        //         'remark' => 'Fasttag Create',
                        //         'created_at' => date('Y-m-d H:i:s'),
                        //         'created_by' => auth()->user()->id,
                        //     ];
                        //     \DB::table('logs')->insert($fasttag_crud);

                        // }

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



                         /*$obf_finance = [

                        'obf_id'=>$request->id,

                        'finance_name' => $request->finance_name ?? null,

                        'finance_required' => $request->finance_required ?? null,

                        'repo_rate' => $request->repo_rate ?? null,

                        'net_disbusment' => $request->net_disbusment ?? null,

                        'loan_amount' => $request->loan_amount ?? null,

                        'processing_fee' => $request->processing_fee ?? null,

                        'finance_discount' => $request->finance_discount ?? null,

                        'payout' => $request->payout ?? null,

                        'pay_booster' => $request->pay_booster ?? null,

                        'booster_percentage' => $request->booster_percentage ?? null,

                        'finance_type' => $request->finance_type ?? null,

                        'delivery_on_d_o' => $request->delivery_on_d_o ?? null,

                        'disbursement' => $request->disbursement ?? null,

                        'payout_amount'=>$request->payout_amount ?? null,

                        'lumsum_amount'=>$request->lumsum_amount ?? null,

                        'total_payout_amount'=>$request->total_payout_amount ?? null,

                        'boostamt'=>$request->boostamt ?? null,

                        ];

                        // DB::enableQueryLog();

                         if(DB::table('obf_finance')->where("obf_id", "=", $request->id)->exists()){

                            DB::table('obf_finance')->where(['obf_id' => $request->id])->update($obf_finance);
                            
                            $finance_crud = [
                                'module_nm' => 'obf_finance_update',
                                'module_id' => $request->id,
                                'status' => 'finance_update',
                                'remark' => 'Finance Update',
                                'created_at' => date('Y-m-d H:i:s'),
                                'created_by' => auth()->user()->id,
                            ];
                            \DB::table('logs')->insert($finance_crud);

                        }else{

                            DB::table('obf_finance')->insert($obf_finance);
                            
                            $finance_crud = [
                                'module_nm' => 'obf_finance_create',
                                'module_id' => $request->id,
                                'status' => 'finance_create',
                                'remark' => 'Finance Create',
                                'created_at' => date('Y-m-d H:i:s'),
                                'created_by' => auth()->user()->id,
                            ];
                            \DB::table('logs')->insert($finance_crud);

                        }*/ 



                DB::beginTransaction();

                try {
                    
                    $update = OBF::where(['id' => $request->id])->update($crud);
                    
                    $obf_crud = [
                        'module_nm' => 'obf_update',
                        'module_id' => $request->id,
                        'status' => 'obf_update',
                        'remark' => 'OBF Update',
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => auth()->user()->id,
                    ];
                    \DB::table('logs')->insert($obf_crud);

                    if ($update) {
                        DB::commit();
                        return redirect()->route('obf')->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 = OBF::where(['id' => $id])->first();



            if (!empty($data)) {

                $update = OBF::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
                
                $crud = [
                    'module_nm' => 'obf',
                    'module_id' => $id,
                    'status' => $request->status,
                    'remark' => '',
                    'created_at' => date('Y-m-d H:i:s'),
                    'created_by' => auth()->user()->id,
                ];
                \DB::table('logs')->insert($crud);

                if ($update) {

                    return response()->json(['code' => 200]);

                } else {

                    return response()->json(['code' => 201]);

                }

            } else {

                return response()->json(['code' => 201]);

            }

            

        }

    /** change-status */



    /** remove-profile */

        public function obf_profile_remove(Request $request){

            if(!$request->ajax()) { exit('No direct script access allowed'); }



            if(!empty($request->all())){

                $id = base64_decode($request->id);

                $data = OBF::find($id);



                if($data){

                    if($data->pan_image != ''){

                        $file_path = public_path().'/uploads/kyc/'.$data->pan_image;



                        if(File::exists($file_path) && $file_path != ''){

                            if($data->pan_image != 'user-icon.jpg') {

                                @unlink($file_path);

                            }

                        }



                        $update = OBF::where(['id' => $id])->update(['pan_image' => '']);



                        if($update)

                            return response()->json(['code' => 200]);

                        else

                            return response()->json(['code' => 201]);

                    }else{

                        return response()->json(['code' => 200]);

                    }

                }else{

                    return response()->json(['code' => 201]);

                }

            }else{

                return response()->json(['code' => 201]);

            }

        }

    /** remove-profile */



    /** Import */

        public function import(Request $request){

                /*$import = Excel::import(new ImportObf(), $request->file('file'));    

                if($import){

                    Excel::store(new ImportObf(), 'OBF_'.Date('YmdHis').'.xlsx' ,'excel_import');

                    return redirect()->route('obf')->with('sucess' ,'File Imported Sucessfully');

                }*/



                if(Excel::import(new ImportObf, $request->file('file')->store('file'))){

                    return redirect()->route('obf')->with('sucess' ,'File Imported Sucessfully');

                }else{

                    return redirect()->route('obf')->with('error' ,'Faild To Import File!');

                }

        }

    /** Import */



    /** Export */

        public function export(Request $request){

            $slug = $request->slug;

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



            try {

                return Excel::download(new ExportOBF($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

           

        } 

    /** Export */

    /** Get pricelist */

        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')
                        ->where('rto_type', 'like', $request->customer_type . '%')
                        ->orderBy('id', 'DESC')
                        ->first();
                } else {*/
                    if($request->customer_type == 'bh_parsing'){
                        $fuel_type = '';
                        if($request->fuel_type == 1){
                            $fuel_type = 'petrol_cng';    
                        } else if($request->fuel_type == '2'){
                            $fuel_type = 'diesel';
                        } else if($request->fuel_type == '3'){
                            $fuel_type = 'ev';
                        }
                        
                        $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','fuel_type','below_1_lac','10_20_lac','above_20_lac','parsing_percentage','bh_parsing_validity','total_parsing_validity')
                            ->where('rto_type', 'like', $request->customer_type . '%')
                            ->where('fuel_type', 'like', $fuel_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,
                            'below_1_lac' => $rto_data->below_1_lac,
                            '10_20_lac' => $rto_data->{'10_20_lac'},
                            'above_20_lac' => $rto_data->above_20_lac,
                            'parsing_percentage' => $rto_data->parsing_percentage,
                            'bh_parsing_validity' => $rto_data->bh_parsing_validity,
                            'total_parsing_validity' => $rto_data->total_parsing_validity,
                        ];   
                    } 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','fuel_type','below_1_lac','10_20_lac','above_20_lac','parsing_percentage','bh_parsing_validity','total_parsing_validity')
                            ->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,
                            'rto_master_custom_handling_charges' => $rto_data->totalcharges,
                        ];   
                    }
                /*}*/
            }
        
            return response()->json($pricelist_data);
        }
        

         public function rtolist(Request $request)

         {

              return "xcdc";

            //$rto_master_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();



              //return $rto_master_data;

         }

    

    /** Get Pricelist */



    /**product_data_get */

        public function product_data_get(Request $request){ 

            $model = ($request->model);

            $veriant = ($request->veriant);



            $exterior_color = ($request->exterior_color);

            $interior_color = ($request->interior_color);

            /*echo "<pre>";

            print_r($_REQUEST);

            die('S');*/

            $Product = Product::where(['car_model' => $model])

            ->where(['veriant' => $veriant])

            ->where(['interior_color' => $interior_color])

            ->where(['exterior_color' => $exterior_color])

            ->where(['status' => 'active'])->get();



            $data = [];

            if(!empty($Product) && $Product->count() > 0){

                $data['ex_showroom_price'] = $Product[0]->ex_showroom_price;        

            }

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

        }

    /** carvarient */



    /** OBF validation */

        public function obf_validation(Request $request)
        {
            $response = array();
            $response['status'] = 200;
            $response['message'] = '';
            $response['data'] = (object)array();
        
            $data = $request->input('data');
            $content = json_decode($data);
        
            $contact_number = isset($content->contact_number) ? $content->contact_number : '';
            $pan_number = isset($content->pan_number) ? $content->pan_number : '';
            $aadhar_number = isset($content->aadhar_number) ? $content->aadhar_number : '';
            $customer_type = isset($content->customer_type) ? $content->customer_type : '';
            $branch = isset($content->branch) ? $content->branch : '';
            $customer_name = isset($content->customer_name) ? $content->customer_name : '';
            $einvoapp = isset($content->einvoapp) ? $content->einvoapp : '';
            $gst_required = isset($content->gst_required) ? $content->gst_required : '';
            $gst = isset($content->gst) ? $content->gst : '';
            $address_1 = isset($content->address_1) ? $content->address_1 : '';
            $pancard = isset($content->pancard) ? $content->pancard : '';
            $aadhar = isset($content->aadhar) ? $content->aadhar : '';
            $aadhar_pan_link = isset($content->aadhar_pan_link) ? $content->aadhar_pan_link : '';
            $aadhar_pan = isset($content->aadhar_pan) ? $content->aadhar_pan : '';
            $pan_image_multi = isset($content->pan_image_multi) ? $content->pan_image_multi : '';
            $adhar_image_multi = isset($content->adhar_image_multi) ? $content->adhar_image_multi : '';
            $customer_type_new = isset($content->customer_type_new) ? $content->customer_type_new : '';
           
            $params = [
                'customer_name' => $customer_name,
                'rto_type' => $customer_type,
                'branch' => $branch,
                'e-Invoice_Applicable' => $einvoapp,
                'gst_required' => $gst_required,
                'gst' => $gst,
                'Address_Correspondence' => $address_1,
                'Mobile_number' => $contact_number,
                'pan_number' => $pan_number,
                'aadhar_number' => $aadhar_number,
                'aadhar_pan_link' => $aadhar_pan_link,
                'aadhar_pan_image' => $aadhar_pan,
                'pan_image' => $pancard,
                'adhar_image' => $aadhar,
                'pan_image_multi' => $pan_image_multi,
                'adhar_image_multi' => $adhar_image_multi,
                'customer_type_new' => $customer_type_new,
            ];
            if ($customer_type_new != 4) {
                // Define validation rules
                $rules = [
                    'customer_name' => 'required',
                    'rto_type' => 'required',
                    'branch' => 'required',
                    'e-Invoice_Applicable' => 'required',
                    'gst_required' => 'required|in:yes,no',
                    'gst' => [
                        'required_if:gst_required,yes',
                        'regex:/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/',
                    ],
                    'Address_Correspondence' => 'required',
                    'Mobile_number' => 'required|digits:10',
                    'pan_number' => [
                        'required',
                        'regex:/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/',
                    ],
                    /*'aadhar_number' => [
                        'required',
                        'regex:/^\d{12}$/',
                    ],*/
                    'aadhar_number' => [
                        ($customer_type_new == 2) ? 'nullable' : 'required',
                        'regex:/^\d{12}$/',
                    ],
                    'aadhar_pan_link' => 'required|in:yes,no',  
                ];
                
                
                $rules['aadhar_pan_image'] = [
                    'required_if:aadhar_pan_link,yes|max:10240',
                ];
            
                // $rules['pan_image'] = 'required|max:10240';
                if (empty($pan_image_multi)) {
                    $rules['pan_image'] = 'required|max:10240';
                } else {
                    $rules['pan_image'] = 'max:10240';
                }
                
                /*if(empty($adhar_image_multi)) {
                    $rules['adhar_image'] = 'required|max:10240';    
                } else {
                    $rules['adhar_image'] = 'max:10240';
                }*/
                if ($customer_type_new != 2) {
                    if(empty($adhar_image_multi)) {
                        $rules['adhar_image'] = 'required|max:10240';    
                    } else {
                        $rules['adhar_image'] = 'max:10240';
                    }
                } else {
                    $rules['adhar_image'] = 'max:10240';
                }
            } else if ($customer_type_new == 4) {
                // Define validation rules
                $rules = [
                    'customer_name' => 'required',
                    'rto_type' => 'required',
                    'branch' => 'required',
                    'e-Invoice_Applicable' => 'required',
                    'gst_required' => 'required|in:yes',
                    'Address_Correspondence' => 'required',
                    'Mobile_number' => 'required|digits:10',
                ];
            }   
            
            
        
            $validator = Validator::make($params, $rules);
        
            if ($validator->fails()) {
                $response['status'] = 404;
                $response['message'] = $validator->errors()->first();
                return response($response, 200);
            }
        
            return response($response, 200);
        }
        
        // public function obf_validation(Request $request)
        // {
        //     $response = array();
        //     $response['status'] = 200;
        //     $response['message'] = '';
        //     $response['data'] = (object)array();
        
        //     $data = $request->input('data');
        //     $content = json_decode($data);
        
        //     $contact_number = $content->contact_number ?? '';
        //     $pan_number = $content->pan_number ?? '';
        //     $aadhar_number = $content->aadhar_number ?? '';
        //     $customer_type = $content->customer_type ?? '';
        //     $branch = $content->branch ?? '';
        //     $customer_name = $content->customer_name ?? '';
        //     $einvoapp = $content->einvoapp ?? '';
        //     $gst_required = $content->gst_required ?? '';
        //     $gst = $content->gst ?? '';
        //     $address_1 = $content->address_1 ?? '';
        //     $pancard = $content->pancard ?? '';
        //     $aadhar = $content->aadhar ?? '';
        //     $aadhar_pan_link = $content->aadhar_pan_link ?? '';
        //     $aadhar_pan = $content->aadhar_pan ?? '';
        //     $pan_image_multi = $content->pan_image_multi ?? '';
        //     $adhar_image_multi = $content->adhar_image_multi ?? '';
        //     $customer_type_new = $content->customer_type_new ?? '';
        //     $params = [
        //         'customer_name' => $customer_name,
        //         'rto_type' => $customer_type,
        //         'branch' => $branch,
        //         'e-Invoice_Applicable' => $einvoapp,
        //         'gst_required' => $gst_required,
        //         'gst' => $gst,
        //         'Address_Correspondence' => $address_1,
        //         'Mobile_number' => $contact_number,
        //         'pan_number' => $pan_number,
        //         'aadhar_number' => $aadhar_number,
        //         'aadhar_pan_link' => $aadhar_pan_link,
        //         'aadhar_pan_image' => $aadhar_pan,
        //         'pan_image' => $pancard,
        //         'adhar_image' => $aadhar,
        //         'pan_image_multi' => $pan_image_multi,
        //         'adhar_image_multi' => $adhar_image_multi,
        //         'customer_type_new' => $customer_type_new,
        //     ];
        
        //     // Common validation rules
        //     $rules = [
        //         'customer_name' => 'required',
        //         'rto_type' => 'required',
        //         'branch' => 'required',
        //         'e-Invoice_Applicable' => 'required',
        //         'gst_required' => 'required|in:yes,no',
        //         'gst' => [
        //             'required_if:gst_required,yes',
        //             'regex:/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/',
        //         ],
        //         'Address_Correspondence' => 'required',
        //         'Mobile_number' => 'required|digits:10',
        //         'pan_number' => $customer_type_new != 4
        //         ? ['required', 'regex:/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/']
        //         : ['nullable', 'regex:/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/'],
        //     ];
            
            
        //     // Conditional gst validation
        //     if ($customer_type_new == 4) {
        //         $rules['gst_required'] = 'required|in:yes,no';
        //         $rules['gst'] = [
        //             'required',
        //             'regex:/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/',
        //         ];
        //     } else {
        //         $rules['gst_required'] = 'nullable|in:yes,no';
        //         $rules['gst'] = [
        //             'required_if:gst_required,yes',
        //             'nullable',
        //             'regex:/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/',
        //         ];
        //     }
        
        //     // Additional validations if customer_type_new != 4
        //     if ($customer_type_new != 4) {
        //         $rules['aadhar_number'] = ['required', 'regex:/^\d{12}$/'];
        //         $rules['aadhar_pan_link'] = 'required|in:yes,no';
        //         $rules['aadhar_pan_image'] = 'required_if:aadhar_pan_link,yes|max:10240';
        
        //         if (empty($pan_image_multi)) {
        //             $rules['pan_image'] = 'required|max:10240';
        //         } else {
        //             $rules['pan_image'] = 'max:10240';
        //         }
        
        //         if (empty($adhar_image_multi)) {
        //             $rules['adhar_image'] = 'required|max:10240';
        //         } else {
        //             $rules['adhar_image'] = 'max:10240';
        //         }
        //     }
        
        //     $validator = Validator::make($params, $rules);
        
        //     if ($validator->fails()) {
        //         $response['status'] = 404;
        //         $response['message'] = $validator->errors()->first();
        //         return response($response, 200);
        //     }
        
        //     return response($response, 200);
        // }

    /** OBF validation */



    /** obf_validation_step_two */

        public function obf_validation_step_two(Request $request)

        {

            $response = array();

            $response['status'] = 200;

            $response['message'] = '';

            $response['data'] = (object)array();



            $data = $request->input('data');

            $content = json_decode($data);

            

            $sales_person_name = isset($content->sales_person_name) ? $content->sales_person_name : '';

            $car_name = isset($content->car_name) ? $content->car_name : '';

            $veriant = isset($content->veriant) ? $content->veriant : '';

            $exterior_color = isset($content->exterior_color) ? $content->exterior_color : '';

            $interior_color = isset($content->interior_color) ? $content->interior_color : '';

            $pricelist_manager_id = isset($content->pricelist_manager_id) ? $content->pricelist_manager_id : '';

            $step1_remarks = isset($content->step1_remarks) ? $content->step1_remarks : '';

            $params = [

                'sales_person_name' => $sales_person_name,

                'car_name' => $car_name,

                'veriant' => $veriant,

                'exterior_color' => $exterior_color,

                'interior_color' => $interior_color,

                'pricelist_manager_id' => $pricelist_manager_id,
                
                'step1_remarks' => $step1_remarks,

            ];



            $validator = Validator::make($params, [

                'sales_person_name' => 'required',

                'car_name' => 'required',

                'veriant' => 'required',

                'exterior_color' => 'required',

                // 'interior_color' => 'required',

                'pricelist_manager_id' => 'required',
                
                'step1_remarks' => 'required',

            ],

                ['car_name.required' => 'The car model field is required',

                'veriant.required' => 'The Car Variant field is required',

                'pricelist_manager_id.required' => 'The Pricelist field is required',
                
                'step1_remarks.required' => 'The Discount Remark field is required',

                ],

            );



            if ($validator->fails()) {

                $response['status'] = 404;

                $response['message'] = $validator->errors()->first();

                return response($response, 200);

            }

            return response($response, 200);

        }

    /** obf_validation_step_two */





    /** OBF Print */

    public function obf_print(Request $request)

    {       

        ini_set('memory_limit', '48M');



        $obf_id = base64_decode($request->id);
        


        $data = OBF::select(
            'obf.*',
            'branches.name AS branch_name',
            'branches.id AS branch_id',
            'products.name AS product_name',
            'products.veriant',
            'products.is_applicable_for_mcp',
            'registration_tax.percentage AS registration_tax',
            'insurance.name AS insurance',
            'municipal_tax.percentage AS municipal_tax',
            'tcs_tax.percentage AS tcs_tax',
            'finance.name AS finance_name',
            'finance_branch.name AS finance_branch_name',
            'lead.name AS lead_name',
            'obf.tentetive_delivery_date',
            'accessories.name as accessories_name',
            'obf_finance.repo_rate',
            // 'obf_finance.net_disbusment',
            DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.receipt_type = "disbusment_receipt" AND cash_receipt.status != "rejected") as net_disbusment'),
            'obf_finance.loan_amount',
            'obf_finance.processing_fee',
            'obf_finance.finance_discount',
            'obf_finance.payout',
            'obf_finance.pay_booster',
            'obf_finance.finance_required',
            'obf_finance.finance_type',
            'car_model.name AS car_model_name',
            'car_varient.name AS car_varient_name',
            'interiorcolor.name AS interiorcolor_name',
            'exteriorcolor.name AS exteriorcolor_name',
            'fule_type.title AS fule_type',
            'customer_type_master.name as customer_type_name',
            'other_one.name as other_one_name',
            'other_two.name as other_two_name',
            'city.name as city_name',
            'common_state.name as state_name',
            'district.name as district_name',
            'ship_to_city.name as ship_to_city_name',
            'ship_to_state.name as ship_to_state_name',
            'ship_to_district.name as ship_to_district_name',
            'inventory.key_number',
            'inventory.engine_number',
            'inventory.chassis_number',
            'inventory.vin_number', 
            'obf_insurance.company_name AS insurance_company_name',
            'obf_insurance.ncb_amount',
            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
            'Team_master.team_name',
            'rsa.rsa_ccs as rsa_type',
            'rsa.amount as rsa_amount',
            'rsa.name as rsa_name',
            'ccs.rsa_ccs as ccs_type',
            'ccs.amount as ccs_amount',
            'ccs.name as ccs_name',
            'extand_warranties.years AS extand_warranties_years',
            'extand_warranties.amount AS extand_warranties_amount',
            'mcp.name as mcp_name',
            'mcp.amount as mcp_amount',
            'fasttags.brand_name AS fasttage_name',
            'fasttags.amount AS fasttag_amount',
            DB::raw('(SELECT total_exchange_amount FROM exchange_purchase WHERE exchange_purchase.obf_id = obf.id AND exchange_purchase.status IN ("active", "sell")) as total_exchange_amount'),
            DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.receipt_type = "booking_receipt" AND cash_receipt.status != "rejected") as booking_amount'),
            DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.receipt_type = "downpayment_receipt" AND cash_receipt.status != "rejected") as dp_amount'),
            'exchange_purchase.variant as exchange_car_name',
            'exchange_purchase.company_name as exchange_company_name',
            'exchange_purchase.manufacturing_year',
            'exchange_purchase.registration_number',
            'pricelist_master.price_list_name',
            'obf.municipal_tax_type',
            'obf.municipal_custom_handling_charges',
            'obf.tl_discount',
            'obf.sm_discount',
            'obf.gm_discount',
            'obf.bh_discount',
            'obf.ceo_discount',
            'obf.md_discount',
        )   

        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

        ->leftjoin('products', 'obf.product_id', 'products.id')

        ->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')
        
        ->leftjoin('fule_type', 'fule_type.id', 'obf.fuel_type')

        ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

        ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

        ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

        ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

        ->leftjoin('allocation' ,'obf.id' ,'allocation.obf_id')

        ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

        ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

        ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

        ->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')

        ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

        ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')

        ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
        
        ->leftjoin('finance' ,'obf_finance.finance_name' ,'finance.id')

        ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
        
        ->leftjoin('customer_type_master','customer_type_master.id','obf.customer_type_new')
        
        ->leftjoin('other_one','other_one.id','obf.other_details_1')
        
        ->leftjoin('other_two','other_two.id','obf.other_details_2')
        
        ->leftjoin('common_state','common_state.id','obf.state_id')
        
        ->leftjoin('district','district.id','obf.district_id')
        
        ->leftjoin('city','city.id','obf.city_id')
        
        ->leftjoin('common_state as ship_to_state','ship_to_state.id','obf.ship_to_state_id')
        
        ->leftjoin('district as ship_to_district','ship_to_district.id','obf.ship_to_district_id')
        
        ->leftjoin('city as ship_to_city','ship_to_city.id','obf.ship_to_city_id')
        
        ->leftjoin('Team_master','Team_master.id','users.team_name')
        
        ->leftjoin('rsa','obf.rsa_master_obf','rsa.id')
        
        ->leftjoin('rsa as ccs','obf.ccs_master_obf','ccs.id')
        
        ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
        
        ->leftjoin('mcp', 'obf.convinience_program', 'mcp.id')
        
        ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
        
        ->leftjoin('exchange_purchase', 'obf.id', 'exchange_purchase.obf_id')
        
        ->leftjoin('pricelist_master', 'obf.pricelist_id', 'pricelist_master.id')

        ->where(['obf.id' => $obf_id])

        ->first();

        $userBranch = auth()->user()->branch;

        $branchArray = explode(',', $userBranch);

        $accessory_sum = 0;
        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){
            $accessory_id_arr = explode(' ,', $data->accessory_id);
            if(!empty($accessory_id_arr)){
                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');
            }
        }
        
        $accessory_ids_string = $data->accessory_id; // e.g., "1,4,13,17,48"
        $accessory_ids_array = explode(',', $accessory_ids_string); // convert to array
        $accessories_nm = DB::table('accessories')
            ->select('id', 'name as accessory_name', 'price')
            ->whereIn('id', $accessory_ids_array)
            ->get();
        if(isset($accessories_nm) && !empty($accessories_nm)){
            $accessory_names = $accessories_nm->pluck('accessory_name')->implode(', '); 
        } else {
            $accessory_names = '-';
        }
         
        
        $images = DB::table('global_configuration')->select('gatepass_logo1')->first();

        return view('obf.obf_print', compact('images','data','obf_id','accessory_sum','accessory_names'));
    }

    /** OBF Print */



    /*

    <tr>

        <td style="font-size:13px; border-bottom:1px solid black;"></td>

        <td style="text-align:right;">Dist. :</td>

        <td style="font-size:13px; text-align:center;border-bottom:1px solid black;">MORBI</td>

        <td style="border-bottom:1px solid black;">Pin Code No.:</td>

        <td style="border-bottom:1px solid black;">363641</td>

        <td style=""></td>

    </tr>







    <tr>

        <td colspan="2" style="font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">Cheque / RTGS / NEFT_01 </td>

        <td style="text-align:right;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;"><b>2,74,600.00</b></td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">Drawn On / RTGS Details</td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">AXIS BANK RTGS 062570</td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">03-Oct-22</td>

    </tr>

    <tr>

        <td colspan="2" style="font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">Cheque / RTGS / NEFT_02 </td>

        <td style="text-align:right;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;"><b>1,40,000.00</b></td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;"></td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">CASH</td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">30-Sep-22</td>

    </tr>

    <tr>

        <td colspan="2" style="font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">Cheque / RTGS / NEFT_03 </td>

        <td style="text-align:right;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;"><b>200.00</b></td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;"></td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">CASH</td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">04-Oct-22</td>

    </tr>

    <tr>

        <td colspan="2" style="font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">Cheque / RTGS / NEFT_04 </td>

        <td style="text-align:right;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;"><b>-</b></td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;"></td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">0</td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">00-Jan-00</td>

    </tr>

    <tr>

        <td colspan="2" style="font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">Cheque / RTGS / NEFT_05 </td>

        <td style="text-align:right;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;"><b>-</b></td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;"></td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">0</td>

        <td style="text-align:center;font-size:13px;border-bottom:1px solid black;border-right:1px solid black;border-left:1px solid black;">-</td>

    </tr>*/

    

    

    public function offer_asper_varient(Request $request){

        $car_name = $request->car_name;

        $varient = $request->varient;

        $fuel = $request->fuel;

        $offer_type = $request->offer_type;

        $data =[];

        $title = [];

        $titles = [];
        
        $today = Carbon::today()->toDateString();

        if($offer_type = 'KIN'){


            // $offer= offer::where(['fk_car_model_id'=>$car_name, 'fk_car_varient_id'=>$varient,'fk_fuel_id'=>$fuel,'offer_type'=>$offer_type])->get();
            
            $offer = Offer::where([
                'fk_car_model_id' => $car_name,
                'fk_fuel_id'      => $fuel,
                'offer_type'      => $offer_type
            ])
            ->whereRaw('FIND_IN_SET(?, fk_car_varient_id)', [$varient])
            ->whereDate('start_date', '<=', $today)
            ->whereDate('end_date', '>=', $today)
            ->get();
            
        foreach ($offer as $value) {

                    $color_data = [];                    

                    $color_data['id'] = $value->id;

                    $color_data['title'] = $value->title;

                    $color_data['amount'] = $value->amount;

                    $title[] = $color_data;                    

                }  

            $data['sub_offer_html'] = $title;  

        }

        if($offer_type = 'ShivamIB'){

            // $offer= offer::where(['fk_car_model_id'=>$car_name, 'fk_car_varient_id'=>$varient,'fk_fuel_id'=>$fuel,'offer_type'=>$offer_type])->get();
            
            $offer = Offer::where([
                'fk_car_model_id' => $car_name,
                'fk_fuel_id'      => $fuel,
                'offer_type'      => $offer_type
            ])
            ->whereRaw('FIND_IN_SET(?, fk_car_varient_id)', [$varient])
            ->whereDate('start_date', '<=', $today)
            ->whereDate('end_date', '>=', $today)
            ->get();

            foreach ($offer as $value) {
    
                    $color_data = [];                    

                    $color_data['id'] = $value->id;

                    $color_data['title'] = $value->title;

                    $color_data['amount'] = $value->amount;

                    $titles[] = $color_data;                    

                }  

            $data['sub_offer_ShivamIB'] = $titles;

        }

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



    public function amount_asper_offer(Request $request){

        $offer = $request->offer;

        //dd($offer);

        //$offer_ib = $request->offer_ib;

       // dd($offer_ib);

      //  $o_id = implode(',',$offer);

        //dd($o_id);

        $offers= offer::select(DB::raw('SUM(amount) AS sum_of_1'))->whereIn('id',$offer)->get();

        //dd($offers);

        //$offers_ib= offer::select(DB::raw('SUM(amount) AS sum_of_2'))->whereIn('id',$offer_ib)->get();

      //  dd($offers_ib);

        

        //dd($o);

        $data =[];

        //$title = '';

        $color_data = '';

        $colors_data = '';

        foreach ($offers as $value) {

                    $color_data = $value->sum_of_1;

                    //$color_data['amount'] = $value->sum_of_1;

                    //$title = $color_data;                    

                }  



       /* foreach ($offers_ib as $value) {

                    $colors_data = $value->sum_of_2;

                    //$color_data['amount'] = $value->sum_of_1;

                    //$title = $color_data;                    

                }   */     



        $data['offer_amount'] =  $color_data; /* + $colors_data;*/  

        //dd($data['offer_amount']);

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

    }



    public function amount_asper_offer_ib(Request $request){

        $offer = $request->offer_ib;

        

        $offers= offer::select(DB::raw('SUM(amount) AS sum_of_1'))->whereIn('id',$offer)->get();

       

        $data =[];

        $color_data = '';

        $colors_data = '';

        foreach ($offers as $value) {

                    $color_data = $value->sum_of_1;

                }  

        $data['offer_amount_ib'] =  $color_data; 

        //dd($data['offer_amount']);

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

    }

    

    public function obf_summary(Request $request){

        ini_set('memory_limit', '1024M');
        
        $id = base64_decode($request->id);               

        $path = URL('/uploads/kyc').'/';



        $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

        $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

        $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

        $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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



        $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

        $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

        $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

        $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();
        $lead = SubLead::select('id' ,'name')->where(['status' => 'active'])->get();

        $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

                

        $data = OBF::select('obf.id',
            'obf.sales_person_id',
            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
            'obf.temporary_id',
            'obf.booking_date',
            'obf.customer_name',
            'obf.customer_type',
            'obf.customer_type_new',
            'obf.booking_date',
            'branches.name AS branch_name',
            'branches.id AS branch_id',
            'obf.company_name', 
            'obf.einvoicing_applicable',
            'obf.gst',
            'obf.address',
            'obf.registration',
            'obf.email',
            'obf.pan_number',
            'obf.adhar_number',
            'obf.licance_number',
            'obf.contact_number',
            'obf.dob',
            'obf.nominee_name',
            'obf.nominee_reletion',
            'obf.nominee_age',
            'obf.occupation',
            'products.name AS product_name',
            'obf.product_id',
            'products.veriant',
            'products.is_applicable_for_mcp',
            'obf.ex_showroom_price',
            'obf.fasttag_brand_name AS fasttag_brand_name',
            'registration_tax.percentage AS registration_tax',
            'insurance.name AS insurance',
            'obf.insurance_id',
            'municipal_tax.percentage AS municipal_tax',
            'tcs_tax.percentage AS tcs_tax',
            'accessories.name AS accessory_name',
            'obf.accessory_id',
            'obf.extanded_warranty_id',
            'extand_warranties.years AS extand_warranties_years',
            'extand_warranties.amount AS extand_warranties_amount',
            'fasttags.brand_name AS brand_name',
            'fasttags.amount AS fasttag_amount_new',
            'fasttags.id AS fasttag_id',
            'obf.trade_car_name',
            'obf.trade_car_value', 
            'obf.on_road_price',
            'obf.on_road_price_word',
            'obf.on_road_price_word',
            'obf.finance_id',
            'finance.name AS finance_name',
            'finance_branch.name AS finance_branch_name',
            'lead.name AS lead_name',
            'obf.lead_id',
            'obf.mode_of_payment',
            'obf.status',
            'obf.created_by',
            'obf.updated_by',
            'obf.created_at',
            'obf.updated_at',
            'allocation.tentetive_delivery_date',
            DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.receipt_type = "booking_receipt" AND cash_receipt.status != "rejected") as booking_amount'),
            DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.receipt_type = "downpayment_receipt" AND cash_receipt.status != "rejected") as dp_amount'),
            // DB::raw('SUM(DISTINCT IF(cash_receipt.receipt_type = "downpayment_receipt" AND cash_receipt.status != "rejected", cash_receipt.amount,0)) as dp_amount'),
            // DB::raw('(SELECT total_exchange_amount FROM exchange_purchase WHERE exchange_purchase.obf_id = obf.id AND exchange_purchase.status IN ("active", "sell") LIMIT 1) as total_exchange_amount'),
            DB::raw('(SELECT total_exchange_amount 
          FROM exchange_purchase 
          WHERE exchange_purchase.obf_id = obf.id 
            AND exchange_purchase.status IN (\'active\', \'sell\') 
          LIMIT 1) as total_exchange_amount'),
            // DB::raw('(SELECT exchange_bonus FROM exchange_purchase WHERE exchange_purchase.obf_id = obf.id AND AND exchange_purchase.status IN ("active", "sell") LIMIT 1) as exchange_bonus'),
            DB::raw('(SELECT exchange_bonus 
          FROM exchange_purchase 
          WHERE exchange_purchase.obf_id = obf.id 
            AND exchange_purchase.status IN (\'active\', \'sell\') 
          LIMIT 1) as exchange_bonus'),
            'obf_rto.rto_type',
            'obf_rto.registration_date',
            'obf_rto.application_number',
            'obf_rto.temporary_number',
            'obf_rto.final_amount',
            'obf_rto.vehicle_number',
            'obf_rto.status as rto_status',
            'obf_fasttag.fasttag_number',
            'obf_fasttag.fasttag_brand',
            'obf_fasttag.date_of_issue',
            'obf_fasttag.fasttag_amount',
            'obf_fasttag.opening_stock',
            'obf_fasttag.status as fasttag_status',
            'obf.pricelist_id',
            'obf.registration_tax_id',
            'obf.municipal_tax_id',
            'obf.municipal_tax_applicable',
            'obf.tcs_tax_id',
            'obf.nominee_dob',
            'convinience_program',
            'obf.step1_remarks',
            'obf.step2_remarks',
            'obf.step3_remarks',
            'obf.step4_remarks',
            'obf.step5_remarks',
            'obf.other_documents',
            'obf.pan_image',
            'obf.adhar_image',
            'obf.licance_image',
            'obf.other_details_1',
            'obf.other_details_2',
            'obf.priclist_detail',
            'obf.inventory_id',
            'obf.aadhar_pan_link',
            'obf_finance.repo_rate',
            // 'obf_finance.net_disbusment',
            DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.receipt_type = "disbusment_receipt" AND cash_receipt.status != "rejected") as net_disbusment'),
            'obf_finance.loan_amount',
            'obf_finance.processing_fee',
            'obf_finance.finance_discount',
            'obf_finance.payout',
            'obf_finance.pay_booster',
            'obf_finance.finance_required',
            'obf.sub_lead_id',
            'obf.rsa_master_obf',
            'car_model.name AS car_model_name',
            'car_varient.name AS car_varient_name',
            'interiorcolor.name AS interiorcolor_name',
            'exteriorcolor.name AS exteriorcolor_name',
            'obf_insurance.company_name AS insurance_company_name',
            'finance.name AS finance_name',
            'inventory.key_number',
            'inventory.engine_number',
            'inventory.chassis_number',
            'inventory.vin_number',
            'inventory.manufacturing_year',
            'obf_insurance.company_name AS insurance_company_name',
            'obf_insurance.ncb_amount',
            'obf.offer_ib_amount',
            'obf.offer_kin_amount',
            'obf.offer_amount',
            'obf.nominee_dob',
            'obf.other_accesssories_prise',
            'obf.offer_type',
            'obf.offer_kin',
            'obf.offer_ib',
            'obf.offer_amount',
            'obf.deal_price',
            'obf.way_off',
            'obf.foc_accessories',
            'obf.final_on_road_price_after_way_off',
            'obf_finance.disbursement',
            'obf_finance.finance_type',
            'obf_finance.payout_amount',
            'obf_finance.lumsum_amount',
            'obf_finance.total_payout_amount',
            'obf.number_plate',
            'customer_type_master.name as customer_type_nm',
            'Team_master.team_name',
            'rsa.name as rsa_name',
            'rsa.amount as rsa_amount',
            'ccs.name as ccs_name',
            'ccs.amount as ccs_amount',
            'obf.anniversary_date',
            'obf.rto_custom_handling_charges',
            'obf.municipal_tax_type',
            'obf.municipal_custom_handling_charges',
            'obf.tl_discount',
            'obf.sm_discount',
            'obf.gm_discount',
            'obf.bh_discount',
            'obf.ceo_discount',
            'obf.md_discount',
        )
         ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

        ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')

        ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
        
        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

        ->leftjoin('products', 'obf.product_id', 'products.id')

        ->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')

        ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

        ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

        ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

        ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

        ->leftjoin('allocation' ,'obf.id' ,'allocation.obf_id')

        ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

        ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

        ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

        ->leftjoin('finance' ,'obf_finance.finance_name' ,'finance.id')

        ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

        ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

        ->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')

        ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
        
        ->leftjoin('customer_type_master','obf.customer_type_new','customer_type_master.id')
        
        ->leftjoin('exchange_purchase','exchange_purchase.obf_id','=','obf.id')
        
        ->leftjoin('cash_receipt','cash_receipt.obf_id','=','obf.id')
        
        ->leftjoin('Team_master','Team_master.id','users.team_name')
        
        ->leftjoin('rsa','obf.rsa_master_obf','rsa.id')
        
        ->leftjoin('rsa as ccs','obf.ccs_master_obf','ccs.id')

        ->where(['obf.id' => $id])

        ->first();


    
          /*  'obf_insurance.ncb','obf_insurance.documents','obf_insurance.date_of_insurance','obf_insurance.last_time_of_insurance','obf_insurance.time_of_insurance','obf_insurance.company_name','obf_insurance.ncb_amount','obf_insurance.policy_number','obf_insurance.status as insurance_status','obf_insurance.documents',*/



          $accessory_name = OBF::select('accessories.id' , 'accessories.name as accessory_name')->leftjoin('accessories' ,'accessories.id','obf.accessory_id')->where('obf.id' , $id)->get();
        
        $obf = OBF::find($id); // or OBF::where('id', $id)->first();
        
        $accessory_ids_string = $obf->accessory_id; // e.g., "1,4,13,17,48"
        $accessory_ids_array = explode(',', $accessory_ids_string); // convert to array
        
        // Step 2: Fetch accessory names and prices
        $accessories_nm = DB::table('accessories')
            ->select('id', 'name as accessory_name', 'price')
            ->whereIn('id', $accessory_ids_array)
            ->get();
            
        

           /* $fast_tags = Fasttag::select('fasttags.id', 'fasttags.brand_name' ,'fasttags.amount')->where(['fasttags.status' => 'active','obf.id' => $id])->get();*/


          $img = DB::table('global_configuration')->select('*')->where('status','active')->first();
          $img1 = $img->invoice_logo1 ?? '';
          $img2 = $img->invoice_logo2 ?? '';
          $leads = OBF::select('lead.id' ,'lead.name')->leftjoin('lead' ,'lead.id','obf.lead_id')->where('obf.id' , $id)->first();
          $sub_leads = OBF::select('sub_lead.id' ,'sub_lead.name')->leftjoin('sub_lead' ,'sub_lead.id','obf.sub_lead_id')->where('obf.id' , $id)->first();

         /* $leads = OBF::select('lead.id' ,'lead.name')->leftjoin('lead' ,'lead.id','obf.lead_id')->where('obf.id' , $id)->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();



                    // dd($carmodel);





        $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.id as varient_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

                            ->leftJoin('car_model','car_model.id','=','obf.product_id')

                            ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

                            ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                            ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                            ->where('obf.id', '=', $id)  

                            ->first();



        $fule = Obf::select('fule_type.title as fule_name')

        ->leftJoin('products','products.id','=','obf.product_id')

        ->leftJoin('car_varient','car_varient.id','=','products.veriant')

        ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')

        ->where('obf.id', '=', $id)  

        ->first();



         $mcp = Mcp::select('id' ,'name', 'amount')->where('id',$data->convinience_program)->where(['status' => 'active'])->get();



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

            

         $OtherTwo = OtherTwo::where(['status' => 'active'])->get(); 
       
        $price_list_name = DB::table('pricelist_master')
    ->select('price_list_name')
    ->where('id',  $data->pricelist_id)
    ->get();
         $Inventory_data = [];
         if($data->inventory_id != NULL){
             $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();
         } else {
             $product_id = Product::where('id',$data->product_id)->first();
             $Inventory_data = Inventory::where('name', '=', $product_id->id)->first();
         }



        $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  



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



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



        $accessory_sum = 0;

        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){

            $accessory_id_arr = explode(' ,', $data->accessory_id);

            if(!empty($accessory_id_arr)){

                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');           

            }

        }



        // $sales = User::role('sales')->select('id' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active'])->get();



         $sales = User::role(['sales','KEC'])->select('id' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active'])->get();



         $user = auth()->user();

         $user_role = $user->getRoleNames();



        $logs_data = DB::table('logs')->select([
            'logs.*',
            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS logs_creator"),
            'roles.name as designation'
        ])
        ->leftJoin("users", function ($join) {
            $join->on("users.id", "=", "logs.created_by");
            $join->where("users.status", "=", 'active');
        })
        ->leftjoin('model_has_roles' ,'users.id' ,'model_has_roles.model_id')
        ->leftjoin('roles' ,'model_has_roles.role_id' ,'roles.id')
        ->where('logs.module_id',$id)
        ->get();
        
        $make_deal_condition = MakeDeal::where('obf_id',$id)->first();
        view()->share('make_deal_condition',$make_deal_condition);
        
        $make_deal_data = OBF::select('obf.id','obf.sales_person_id',

        DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.final_on_road_price_after_way_off' ,'obf.customer_type','obf.customer_type_new' ,'obf.booking_date','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' , 'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id','products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'obf.fasttag_brand_name AS fasttag_brand_name','registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount_new' ,'fasttags.id AS fasttag_id','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','allocation.tentetive_delivery_date','Team_master.team_name','obf.other_accesssories_prise','obf.municipal_custom_handling_charges','obf.rto_custom_handling_charges',

        'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',

        'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.pricelist_id','obf.registration_tax_id','obf.municipal_tax_id','obf.municipal_tax_applicable','obf.tcs_tax_id','obf.nominee_dob', 'obf.convinience_program',

        'obf.step1_remarks','obf.step3_remarks','obf.step4_remarks','obf.step5_remarks','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id',

        'obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.rsa_master_obf',

        'car_model.name AS car_model_name','car_varient.name AS car_varient_name','interiorcolor.name AS interiorcolor_name','exteriorcolor.name AS exteriorcolor_name','inventory.key_number','inventory.engine_number','inventory.chassis_number','inventory.vin_number', 'obf_insurance.company_name AS insurance_company_name','obf_insurance.ncb_amount','obf.offer_ib_amount','obf.offer_kin_amount','obf.offer_amount','inventory.purchase_price','inventory.aging_days','inventory.remark',
        
        'make_deal.obf_id','make_deal.purchase_gst_tax_deal','make_deal.final_deal_amt','make_deal.deal_amt','make_deal.gst_tax_deal','make_deal.cess_tax_deal','make_deal.tcs_tax_deal','make_deal.municipal_tax_deal','make_deal.municipal_custom_handling_charges_deal','make_deal.rto_deal','make_deal.insurance_deal','make_deal.rto_cutom_handling_charges_deal','make_deal.created_by','make_deal.remark','pricelist_master.rto_custome_handling_charges','mcp.id as mcp_id','mcp.name as mcp_name','mcp.amount as mcp_amount','rsa.id as rsa_id','rsa.name as rsa_name','rsa.amount as rsa_amount','rsa.rsa_ccs as rsa_type','ccs.id as ccs_id','ccs.name as ccs_name','ccs.amount as ccs_amount','ccs.rsa_ccs as ccs_type')

        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
        ->leftjoin('products', 'obf.product_id', 'products.id')
        ->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')
        ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
        ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
        ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
        ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
        ->leftjoin('allocation' ,'obf.id' ,'allocation.obf_id')
        ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')
        ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
        ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
        ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
        ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')
        ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
        ->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')
        ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
        ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')
        ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
        ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
        ->leftjoin('Team_master','Team_master.id','users.team_name')
        ->leftjoin('make_deal','obf.id','make_deal.obf_id')
        ->leftjoin('pricelist_master', 'obf.pricelist_id', 'pricelist_master.id')
        ->leftjoin('mcp','obf.convinience_program','mcp.id')
        ->leftjoin('rsa','obf.rsa_master_obf','rsa.id')
        ->leftjoin('rsa as ccs','obf.ccs_master_obf','ccs.id')
        ->where(['obf.id' => $id])->first(); 
        
        view()->share('make_deal_data',$make_deal_data);
        
        $branch = Branch::select('start_value1', 'end_value1', 'tax_percentage1', 'start_value2', 'end_value2', 'tax_percentage2')->where(['status' => 'active','id' => $data->branch_id])->first();
        view()->share('branch',$branch);
       
        $price_list_name_data = DB::table('pricelist_master')->select('basic','price_list_name','gst_percentage','gst_amount','cess_percentage','cess_amount')->where('id',  $data->pricelist_id)->first();
        view()->share('price_list_name_data',$price_list_name_data); 
        
        $rto_data = DB::table('rto_master')->select('rto_type', 'rto_tax_individual', 'rto_tax_company', 'totali_individual_charges','totalcharges')->Where('rto_type', 'like', $data->customer_type . '%')->orderBy('id', 'DESC')->first();
        view()->share('rto_data',$rto_data);
        
        $accessory_sum = 0;

        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){
            $accessory_id_arr = explode(' ,', $data->accessory_id);
            if(!empty($accessory_id_arr)){
                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');           
            }
        }
        view()->share('accessory_sum',$accessory_sum);

        $user = auth()->user();

        $user_role = $user->getRoleNames(); 

        return view('obf.summary')->with(['accessories_nm'=>$accessories_nm,'price_list_name'=>$price_list_name,'data' =>$data,'sales' => $sales ,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'user_role'=> $user_role[0],'accessory_sum' => $accessory_sum,'accessory_name'=>$accessory_name,'leads'=>$leads,'logs_data'=>$logs_data]);



    }

    

    public function processew(Request $request){

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);

         

                $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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



                $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

                $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

                $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

                $data = OBF::select('obf.id','obf.sales_person_id',

                                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type' ,'obf.customer_type_new' ,'obf.convinience_program' ,'branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name','obf.fasttag_brand_name AS fasttag_brand_name' ,'obf.einvoicing_applicable', 'obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id' ,'products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.id AS fasttag_id' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS brand_name','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','obf.municipal_tax_id',
                                    'obf.tcs_tax_id',
                                    'obf.registration_tax_id',
                                    'obf.insurance_id','obf.tentetive_delivery_date',

                'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',



                'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id','inventory.vin_number as vinnumber',



                'obf_finance.finance_name','obf.other_accesssories_prise','obf.other_accesssories_detail','obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.pricelist_id','obf.rsa_master_obf')

                    

                            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                            ->leftjoin('products' ,'obf.product_id' ,'products.id')

                            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                            ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')

                            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                            //->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')

                            ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

                            ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')

                            ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')

                            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

                            ->leftjoin('other_one' ,'obf.other_details_1' ,'other_one.id')

                            ->leftjoin('other_two' ,'obf.other_details_2' ,'other_two.id')

                            ->leftjoin('mcp' ,'mcp.id' ,'obf.convinience_program')

                            ->where(['obf.id' => $id])

                            ->first();

                            

        $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();




        $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.id as varient_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

                            ->leftJoin('car_model','car_model.id','=','obf.product_id')

                            ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

                            ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                            ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                            ->where('obf.id', '=', $id)  

                            ->first();



        $fule = Obf::select('fule_type.title as fule_name')

        ->leftJoin('products','products.id','=','obf.product_id')

        ->leftJoin('car_varient','car_varient.id','=','products.veriant')

        ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')

        ->where('obf.id', '=', $id)  

        ->first();



         $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();



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

            

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



         $Inventory_data = [];

         if($data->inventory_id != NULL){

             $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    

         }



        $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  



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



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



        $accessory_sum = 0;

        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){

            $accessory_id_arr = explode(' ,', $data->accessory_id);

            if(!empty($accessory_id_arr)){

                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           

            }

        }

        return view('EW.processew')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum]);

    }

    public function processewdms(Request $request){

        /*$ewImage = $request->file('dms_ew_certificate');

        $ewImageName = $ewImage ? time().'.'.$ewImage->getClientOriginalExtension() : null;

        $ewImagePath = $request->file('dms_ew_certificate')?->storeAs('EWIMAGE',time().'.'.$request->file('dms_ew_certificate')?->getClientOriginalExtension(),'public');*/
        
        $ewImage = $request->file('dms_ew_certificate');

        $ewImageName = null;
        $ewImagePath = null;
        
        if ($ewImage) {
            $ewImageName = time() . '.' . $ewImage->getClientOriginalExtension();
            $ewImagePath = $ewImage->storeAs(
                'EWIMAGE',
                $ewImageName,
                'public'
            );
        }
    

        $ew = [

            'obf_id'=> $request->id,

            'ew_invoice' => $request->ew_invoice,

            'ew_invoice_date' => Carbon::parse($request->ew_invoice_date)->toDateString(),

            'dms_invoice_no' => $request->dms_invoice_no,

            'dms_invoice_date' => Carbon::parse($request->dms_invoice_date)->toDateString(),

            'dms_gatepass_date' => Carbon::parse($request->dms_gatepass_date)->toDateString(),

            'dms_location' => $request->dms_location,

            'dms_ew_create_date' => Carbon::parse($request->dms_ew_create_date)->toDateString(),

            'dms_ew_certificate' => $ewImagePath,

            'dms_invoice_no' => $request->dms_invoice_no,

            'status' => $request->ew_status,

        ];
        
        \DB::table('ew_process_dms')->updateOrInsert(['obf_id' => $ew['obf_id']], $ew);
        
        \DB::table('obf')->where('id',$request->id)->update(['ew_status' => $request->ew_status]);
        
        $ew_log_crud = [
            'module_nm' => 'ew_process_dms_create',
            'module_id' => $request->id,
            'status' => $request->status,
            'created_at' => now(),
            'created_by' => auth()->user()->id,
        ];
        
        \DB::table('logs')->insert($ew_log_crud);

        return redirect()->route('obf')->with('success', 'Extended Warranty Details Updated...');;

    }

    public function processmcp(Request $request){

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);

         

                $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

                $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

                $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

                $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

                

                

                        

                  $data = OBF::select('obf.id','obf.sales_person_id',

                                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type' ,'obf.customer_type_new' ,'obf.convinience_program','mcp.name AS carName','mcp.amount AS mcpAmount','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name','obf.fasttag_brand_name AS fasttag_brand_name' ,'obf.einvoicing_applicable', 'obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id' ,'products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.id AS fasttag_id' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS brand_name','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','obf.municipal_tax_id',
                                    'obf.tcs_tax_id',
                                    'obf.registration_tax_id',
                                    'obf.insurance_id','obf.tentetive_delivery_date',
                'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',



                'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id','inventory.vin_number as vinnumber',



                'obf_finance.finance_name','obf.other_accesssories_prise','obf.other_accesssories_detail','obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.pricelist_id','obf.rsa_master_obf')

                    

                            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                            ->leftjoin('products' ,'obf.product_id' ,'products.id')

                            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                            ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')

                            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                            //->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')

                            ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

                            ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')

                            ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')

                            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

                            ->leftjoin('other_one' ,'obf.other_details_1' ,'other_one.id')

                            ->leftjoin('other_two' ,'obf.other_details_2' ,'other_two.id')

                            ->leftjoin('mcp' ,'mcp.id' ,'obf.convinience_program')

                            ->where(['obf.id' => $id])

                            ->first();

                            

        $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();



                    // dd($carmodel);





        $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.id as varient_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

                            ->leftJoin('car_model','car_model.id','=','obf.product_id')

                            ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

                            ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                            ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                            ->where('obf.id', '=', $id)  

                            ->first();



        $fule = Obf::select('fule_type.title as fule_name')

        ->leftJoin('products','products.id','=','obf.product_id')

        ->leftJoin('car_varient','car_varient.id','=','products.veriant')

        ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')

        ->where('obf.id', '=', $id)  

        ->first();



         $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();



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

            

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



         $Inventory_data = [];

         if($data->inventory_id != NULL){

             $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    

         }



        $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  



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



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



        $accessory_sum = 0;

        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){

            $accessory_id_arr = explode(' ,', $data->accessory_id);

            if(!empty($accessory_id_arr)){

                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           

            }

        }

        return view('MCP.processmcp')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum]);

    }

    public function processmcpdms(Request $request){
        $mcpImage = $request->file('dms_mcp_certificate');

        $mcpImageName = $mcpImage ? time().'.'.$mcpImage->extension() : null;

        $mcpImagePath = $mcpImage ? $mcpImage->storeAs('MCPIMAGE', $mcpImageName, 'public') : null;

            

        $mcp = [

            'obf_id'=> $request->id,

            'mcp_invoice' => $request->mcp_invoice,

            'mcp_invoice_date' => Carbon::parse($request->mcp_invoice_date)->toDateString(),

            'dms_invoice_no' => $request->dms_invoice_no,

            'dms_invoice_date' => Carbon::parse($request->dms_invoice_date)->toDateString(),

            'dms_gatepass_date' => Carbon::parse($request->dms_gatepass_date)->toDateString(),

            'dms_location' => $request->dms_location,

            'dms_mcp_create_date' => Carbon::parse($request->dms_mcp_create_date)->toDateString(),

            'dms_mcp_certificate' => $mcpImagePath,

            'dms_invoice_no' => $request->dms_invoice_no,

            'status' => $request->mcp_status,

        ];

        \DB::table('mcp_process_dms')->updateOrInsert(['obf_id' => $mcp['obf_id']], $mcp);
        
        \DB::table('obf')->where('id',$request->id)->update(['mcp_status' => $request->mcp_status]);
        
        $mcp_log_crud = [
            'module_nm' => 'mcp_process_dms_create',
            'module_id' => $request->id,
            'status' => $request->status,
            'created_at' => now(),
            'created_by' => auth()->user()->id,
        ];
        
        \DB::table('logs')->insert($mcp_log_crud);

        return redirect()->route('obf');

    }    

    public function processrsa(Request $request){

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);

                    $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                    $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                    $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                    $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

    

                    $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

                    $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                    $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

                    $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                    $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();
                            

                $data = OBF::select('obf.id','obf.sales_person_id',

                                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type' ,'obf.customer_type_new' ,'obf.convinience_program' ,'obf.rsa_master_obf','rsa.name as rsaname','rsa.amount AS rsaamount','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name','obf.fasttag_brand_name AS fasttag_brand_name' ,'obf.einvoicing_applicable', 'obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id' ,'products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.id AS fasttag_id' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS brand_name','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','obf.municipal_tax_id',
                                        'obf.tcs_tax_id',
                                        'obf.registration_tax_id',
                                        'obf.insurance_id','obf.tentetive_delivery_date',

                    'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',

    

                    'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id','inventory.vin_number as vinnumber',

    

                    'obf_finance.finance_name','obf.other_accesssories_prise','obf.other_accesssories_detail','obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.pricelist_id')

                        

                                ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                                ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                                ->leftjoin('products' ,'obf.product_id' ,'products.id')

                                ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                                ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                                ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                                ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                                ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')

                                ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                                ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                                ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                                ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                                ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                                ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

                                ->leftjoin('obf_fasttag','obf.id' ,'obf_fasttag.obf_id')

                                ->leftjoin('obf_finance','obf.id' ,'obf_finance.obf_id')

                                ->leftjoin('accessories','obf.accessory_id' ,'accessories.id')

                                ->leftjoin('other_one','obf.other_details_1' ,'other_one.id')

                                ->leftjoin('other_two','obf.other_details_2' ,'other_two.id')

                                ->leftjoin('mcp' ,'mcp.id','obf.convinience_program')

                                ->leftjoin('rsa' ,'rsa.id','obf.rsa_master_obf')

                                ->where(['obf.id' => $id])

                                ->first();

                                

            $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();

    

                        // dd($carmodel);

    

    

            $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.id as varient_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

                                ->leftJoin('car_model','car_model.id','=','obf.product_id')

                                ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

                                ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                                ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                                ->where('obf.id', '=', $id)  

                                ->first();

    

            $fule = Obf::select('fule_type.title as fule_name')

            ->leftJoin('products','products.id','=','obf.product_id')

            ->leftJoin('car_varient','car_varient.id','=','products.veriant')

            ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')

            ->where('obf.id', '=', $id)  

            ->first();

    

             $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();

    

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

                

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

    

             $Inventory_data = [];

             if($data->inventory_id != NULL){

                 $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    

             }

    

            $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  

    

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

    

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

    

            $accessory_sum = 0;

            if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){

                $accessory_id_arr = explode(' ,', $data->accessory_id);

                if(!empty($accessory_id_arr)){

                    $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           

                }

            }

        return view('RSA.processrsa')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum]);

    }

    public function processrsadms(Request $request){

        $rsaImage = $request->file('dms_rsa_certificate');

        if ($rsaImage) {
            $rsaImageName = time() . '.' . $rsaImage->getClientOriginalExtension();
            $rsaImage->move(public_path('RSAIMAGE'), $rsaImageName);
            $rsaImagePath = 'RSAIMAGE/' . $rsaImageName; // Save this to DB
        }   
    

        $rsa = [

            'obf_id'=> $request->id,

            'rsa_invoice' => $request->rsa_invoice,

            'rsa_invoice_date' => Carbon::parse($request->rsa_invoice_date)->toDateString(),

            'dms_invoice_no' => $request->dms_invoice_no,

            'dms_invoice_date' => Carbon::parse($request->dms_invoice_date)->toDateString(),

            'dms_gatepass_date' => Carbon::parse($request->dms_gatepass_date)->toDateString(),

            'dms_location' => $request->dms_location,

            'dms_rsa_create_date' => Carbon::parse($request->dms_rsa_create_date)->toDateString(),

            'dms_rsa_certificate' => $rsaImagePath, 

            'dms_invoice_no' => $request->dms_invoice_no,

            'status' => $request->rsa_status,

        ];
        
        \DB::table('rsa_process_dms')->updateOrInsert(['obf_id' => $rsa['obf_id']], $rsa);
        
        \DB::table('obf')->where('id',$request->id)->update(['rsa_status' => $request->rsa_status]);
        
        $rsa_log_crud = [
            'module_nm' => 'rsa_process_dms_create',
            'module_id' => $request->id,
            'status' => $request->status,
            'created_at' => now(),
            'created_by' => auth()->user()->id,
        ];
        
        \DB::table('logs')->insert($rsa_log_crud);

        return redirect()->route('obf');

    }  
    
    public function processccs(Request $request){

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);

                    $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                    $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                    $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                    $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

    

                    $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

                    $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                    $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

                    $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                    $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();
                            

                $data = OBF::select('obf.id','obf.sales_person_id',

                                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type' ,'obf.customer_type_new' ,'obf.convinience_program' ,'obf.rsa_master_obf','rsa.name as rsaname','rsa.amount AS rsaamount','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name','obf.fasttag_brand_name AS fasttag_brand_name' ,'obf.einvoicing_applicable', 'obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id' ,'products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.id AS fasttag_id' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS brand_name','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','obf.municipal_tax_id',
                                        'obf.tcs_tax_id',
                                        'obf.registration_tax_id',
                                        'obf.insurance_id','obf.tentetive_delivery_date',

                    'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',

    

                    'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id','inventory.vin_number as vinnumber',

    

                    'obf_finance.finance_name','obf.other_accesssories_prise','obf.other_accesssories_detail','obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.pricelist_id')

                        

                                ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                                ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                                ->leftjoin('products' ,'obf.product_id' ,'products.id')

                                ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                                ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                                ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                                ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                                ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')

                                ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                                ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                                ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                                ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                                ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                                ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

                                ->leftjoin('obf_fasttag','obf.id' ,'obf_fasttag.obf_id')

                                ->leftjoin('obf_finance','obf.id' ,'obf_finance.obf_id')

                                ->leftjoin('accessories','obf.accessory_id' ,'accessories.id')

                                ->leftjoin('other_one','obf.other_details_1' ,'other_one.id')

                                ->leftjoin('other_two','obf.other_details_2' ,'other_two.id')

                                ->leftjoin('mcp' ,'mcp.id','obf.convinience_program')

                                ->leftjoin('rsa' ,'rsa.id','obf.rsa_master_obf')

                                ->where(['obf.id' => $id])

                                ->first();

                                

            $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();

    

                        // dd($carmodel);

    

    

            $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.id as varient_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

                                ->leftJoin('car_model','car_model.id','=','obf.product_id')

                                ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

                                ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                                ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                                ->where('obf.id', '=', $id)  

                                ->first();

    

            $fule = Obf::select('fule_type.title as fule_name')

            ->leftJoin('products','products.id','=','obf.product_id')

            ->leftJoin('car_varient','car_varient.id','=','products.veriant')

            ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')

            ->where('obf.id', '=', $id)  

            ->first();

    

             $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();

    

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

                

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

    

             $Inventory_data = [];

             if($data->inventory_id != NULL){

                 $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    

             }

    

            $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  

    

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

    

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

    

            $accessory_sum = 0;

            if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){

                $accessory_id_arr = explode(' ,', $data->accessory_id);

                if(!empty($accessory_id_arr)){

                    $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           

                }

            }

        return view('CCS.processccs')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum]);

    }

    public function processccsdms(Request $request){

        $rsaImage = $request->file('dms_rsa_certificate');

        if ($rsaImage) {
            $rsaImageName = time() . '.' . $rsaImage->getClientOriginalExtension();
            $rsaImage->move(public_path('RSAIMAGE'), $rsaImageName);
            $rsaImagePath = 'RSAIMAGE/' . $rsaImageName;
        }     
    

        $rsa = [

            'obf_id'=> $request->id,

            'rsa_invoice' => $request->rsa_invoice,

            'rsa_invoice_date' => Carbon::parse($request->rsa_invoice_date)->toDateString(),

            'dms_invoice_no' => $request->dms_invoice_no,

            'dms_invoice_date' => Carbon::parse($request->dms_invoice_date)->toDateString(),

            'dms_gatepass_date' => Carbon::parse($request->dms_gatepass_date)->toDateString(),

            'dms_location' => $request->dms_location,

            'dms_rsa_create_date' => Carbon::parse($request->dms_rsa_create_date)->toDateString(),

            'dms_rsa_certificate' => $rsaImagePath,

            'dms_invoice_no' => $request->dms_invoice_no,

            'status' => $request->rsa_status,

        ];
        
        \DB::table('rsa_process_dms')->updateOrInsert(['obf_id' => $rsa['obf_id']], $rsa);
        
        \DB::table('obf')->where('id',$request->id)->update(['rsa_status' => $request->rsa_status]);
        
        $rsa_log_crud = [
            'module_nm' => 'rsa_process_dms_create',
            'module_id' => $request->id,
            'status' => $request->status,
            'created_at' => now(),
            'created_by' => auth()->user()->id,
        ];
        
        \DB::table('logs')->insert($rsa_log_crud);

        return redirect()->route('obf');

    }
    
    public function processfastag(Request $request){

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);
        $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();
        $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();
        $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();
        $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();
        $accessory = Accessory::select('id' , 'name' ,'price')->where(['status' => 'active'])->get();
        $extanded_warranty = ExtandWarranty::select('id' , 'years' ,'amount')->where(['status' => 'active'])->get();
        $fasttag = Fasttag::select('id', 'brand_name' ,'amount')->where(['status' => 'active'])->get();
        $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();
        $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();
        $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();
        $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();
        $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

            $data = OBF::select(
                'obf.id',
                'obf.sales_person_id',
                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                'obf.temporary_id' ,
                'obf.booking_date' ,
                'obf.customer_name' ,
                'obf.customer_type' ,
                'obf.customer_type_new' ,
                'obf.convinience_program' ,
                'branches.name AS branch_name' ,
                'branches.id AS branch_id' ,
                'obf.company_name',
                'obf.fasttag_brand_name AS fasttag_brand_name' ,
                'obf.einvoicing_applicable', 
                'obf.gst' ,
                'obf.address' ,
                'obf.registration' ,
                'obf.email' ,
                'obf.pan_number',
                'obf.adhar_number' ,
                'obf.licance_number',
                'obf.contact_number' ,
                'obf.dob' ,
                'obf.nominee_name',
                'obf.nominee_reletion' ,
                'obf.nominee_age' ,
                'obf.occupation',
                'products.name AS product_name',
                'obf.product_id' ,
                'products.veriant',
                'products.is_applicable_for_mcp' ,
                'obf.ex_showroom_price' ,
                'registration_tax.percentage AS registration_tax' ,
                'insurance.name AS insurance' ,
                'obf.insurance_id' ,
                'municipal_tax.percentage AS municipal_tax' ,
                'tcs_tax.percentage AS tcs_tax' ,
                'accessories.name AS accessory_name' ,
                'obf.accessory_id',
                'obf.extanded_warranty_id' ,
                'extand_warranties.years AS extand_warranties_years' ,
                'extand_warranties.amount AS extand_warranties_amount' ,
                'fasttags.id AS fasttag_id' ,
                'fasttags.amount AS fasttag_amount' ,
                'fasttags.brand_name AS brand_name',
                'obf.trade_car_name', 
                'obf.trade_car_value', 
                'obf.on_road_price' ,
                'obf.on_road_price_word' ,
                'obf.on_road_price_word',
                'obf.finance_id' ,
                'finance.name AS finance_name' ,
                'finance_branch.name AS finance_branch_name' ,
                'lead.name AS lead_name',
                'obf.lead_id' ,
                'obf.booking_amount' ,
                'obf.mode_of_payment' ,
                'obf.status' ,
                'obf.created_by' ,
                'obf.updated_by',
                'obf.created_at' ,
                'obf.updated_at',
                'obf_rto.rto_type',
                'obf_rto.registration_date',
                'obf_rto.application_number',
                'obf_rto.temporary_number',
                'obf_rto.final_amount',
                'obf_rto.vehicle_number',
                'obf_rto.status as rto_status',
                'obf_rto.number_plate',
                'obf_rto.remarks',
                'obf_fasttag.fasttag_number',
                'obf_fasttag.fasttag_brand',
                'obf_fasttag.date_of_issue',
                'obf_fasttag.fasttag_amount',
                'obf_fasttag.opening_stock',
                'obf_fasttag.status as fasttag_status',
                'obf_fasttag.remarks',
                'obf_fasttag.dms_location',
                'obf_fasttag.dms_ew_create_date',
                'obf_fasttag.ew_invoice',
                'obf_fasttag.ew_invoice_date',
                'obf_fasttag.fasttag_image',
                'obf_fasttag.dms_certificate',
                'obf_fasttag.dms_invoice_no',
                'obf_fasttag.dms_invoice_date',
                'obf_fasttag.dms_gatepass_date',
                'obf.other_documents',
                'obf.pan_image',
                'obf.adhar_image',
                'obf.licance_image',
                'obf.other_details_1',
                'obf.other_details_2',
                'obf.priclist_detail',
                'obf.inventory_id',
                'obf.municipal_tax_id',
                'obf.tcs_tax_id',
                'obf.registration_tax_id',
                'obf.insurance_id',
                // 'inventory.vin_number as vinnumber',
                DB::raw('(SELECT vin_number FROM inventory WHERE inventory.status = "allocated" AND inventory.id = obf.inventory_id) as vinnumber'),
                'obf_finance.finance_name',
                'obf.other_accesssories_prise',
                'obf.other_accesssories_detail',
                'obf_finance.repo_rate',
                'obf_finance.net_disbusment',
                'obf_finance.loan_amount',
                'obf_finance.processing_fee',
                'obf_finance.finance_discount',
                'obf_finance.payout',
                'obf_finance.pay_booster',
                'obf_finance.finance_required',
                'obf.sub_lead_id',
                'obf.pricelist_id',
                'obf.tentetive_delivery_date',
                'obf.rsa_master_obf'
            )
            
            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
            ->leftjoin('products' ,'obf.product_id' ,'products.id')
            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
            ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')
            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
            ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
            ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')
            ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
            ->leftjoin('ew_process_dms','obf.id','ew_process_dms.obf_id')
            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')
            ->leftjoin('other_one' ,'obf.other_details_1' ,'other_one.id')
            ->leftjoin('other_two' ,'obf.other_details_2' ,'other_two.id')
            ->leftjoin('mcp' ,'mcp.id' ,'obf.convinience_program')
            ->where(['obf.id' => $id])
            ->first();

            $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();

             $Cardata = Obf::select(
                'obf.id as o_id',
                'obf.product_id as o_product',
                'car_model.name as car_name',
                'car_model.id as car_id',
                'car_varient.id as varient_id',
                'car_varient.name as varient_name',
                'exteriorcolor.name as exterior_color', 
                'interiorcolor.name as interior_color'
            )
            ->leftjoin('products', 'obf.product_id', 'products.id')
            ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
            ->leftjoin('car_model', 'car_model.id', 'products.car_model')
            ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
            ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
            ->where('obf.id', '=', $id)  
            ->first();

    

            $fule = Obf::select('fule_type.title as fule_name')
            ->leftJoin('products','products.id','=','obf.product_id')
            ->leftJoin('car_varient','car_varient.id','=','products.veriant')
            ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')
            ->where('obf.id', '=', $id)  
            ->first();

            $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();
            $OtherOne = OtherOne::where(['status' => 'active'])->get();  
            $OtherTwo = OtherTwo::where(['status' => 'active'])->get(); 
            
            $Inventory_data = [];

            if($data->inventory_id != NULL){
                 $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    
            }

            $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  
            $CustomerTypeMaster = CustomerTypeMaster::where(['status' => 'active'])->get();  
            $rsa = RSA::where(['status' => 'active','deleted_at' => 0])->get();

            $accessory_sum = 0;
            if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){
                $accessory_id_arr = explode(' ,', $data->accessory_id);
                if(!empty($accessory_id_arr)){
                    $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           
                }
            }
            
            $make_deal_data = OBF::select('obf.id','obf.sales_person_id',

            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type','obf.customer_type_new' ,'obf.booking_date','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' , 'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id','products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'obf.fasttag_brand_name AS fasttag_brand_name','registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount_new' ,'fasttags.id AS fasttag_id','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','Team_master.team_name','obf.other_accesssories_prise','obf.municipal_custom_handling_charges','obf.rto_custom_handling_charges',
    
            'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',
    
            'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.pricelist_id','obf.registration_tax_id','obf.municipal_tax_id','obf.municipal_tax_applicable','obf.tcs_tax_id','obf.nominee_dob','obf.convinience_program',
    
            'obf.step1_remarks','obf.step3_remarks','obf.step4_remarks','obf.step5_remarks','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id','obf.finance_image','obf.rto_image','obf.insurance_image', 'obf.fasttag_image','obf.passport_document','obf.gst_certificate',
    
            'obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.rsa_master_obf',
    
            'car_model.name AS car_model_name','car_varient.name AS car_varient_name','interiorcolor.name AS interiorcolor_name','exteriorcolor.name AS exteriorcolor_name','inventory.key_number','inventory.engine_number','inventory.chassis_number','inventory.vin_number', 'obf_insurance.company_name AS insurance_company_name','obf_insurance.ncb_amount','obf.offer_ib_amount','obf.offer_kin_amount','obf.offer_amount','inventory.purchase_price','inventory.aging_days','inventory.remark',
            
            'make_deal.obf_id','make_deal.purchase_gst_tax_deal','make_deal.final_deal_amt','make_deal.deal_amt','make_deal.gst_tax_deal','make_deal.cess_tax_deal','make_deal.tcs_tax_deal','make_deal.municipal_tax_deal','make_deal.rto_deal','make_deal.insurance_deal','make_deal.created_by','obf.number_plate','mcp.id as mcp_id', 'mcp.name as mcp_name', 'mcp.amount as mcp_amount')
    
            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
            ->leftjoin('products', 'obf.product_id', 'products.id')
            ->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')
            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
            ->leftjoin('allocation' ,'obf.id' ,'allocation.obf_id')
            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')
            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')
            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
            ->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')
            ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
            ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')
            ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
            ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
            ->leftjoin('Team_master','Team_master.id','users.team_name')
            ->leftjoin('make_deal','obf.id','make_deal.obf_id')
            ->leftjoin('mcp','obf.convinience_program','mcp.id')
            ->where(['obf.id' => $id])->first(); 
    
            $make_deal_branch = Branch::select('start_value1', 'end_value1', 'tax_percentage1', 'start_value2', 'end_value2', 'tax_percentage2')->where(['status' => 'active','id' => $make_deal_data->branch_id])->first();
           
            $make_deal_price_list_name = DB::table('pricelist_master')->select('basic','price_list_name','gst_percentage','gst_amount','cess_percentage','cess_amount')->where('id',  $make_deal_data->pricelist_id)->first();
    
            $make_deal_rto_data = DB::table('rto_master')->select('rto_type', 'rto_tax_individual', 'rto_tax_company', 'totali_individual_charges','totalcharges')->Where('rto_type', 'like', $make_deal_data->customer_type . '%')->orderBy('id', 'DESC')->first();
    
            $make_deal_accessory_sum = 0;
    
            if(!empty($make_deal_data->accessory_id) && $make_deal_data->accessory_id != NULL && $make_deal_data->accessory_id != ''){
                $accessory_id_arr = explode(' ,', $make_deal_data->accessory_id);
                if(!empty($accessory_id_arr)){
                    $make_deal_accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');           
                }
            }
            
            $my_con_program = Mcp::where(['status' => 'active','car_model' => $Cardata->car_id])->get();
            
        return view('FASTTAG.processfasttag')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum,'make_deal_data' => $make_deal_data,'make_deal_branch' => $make_deal_branch,'make_deal_price_list_name' => $make_deal_price_list_name,'make_deal_rto_data' => $make_deal_rto_data]);
    }

    public function processfastagdms(Request $request){
           $fasttag = [
            'obf_id' => $request->id,
            'ew_invoice' => $request->ew_invoice ?? null,
            'ew_invoice_date' => $request->ew_invoice_date ?? null,
            'fasttag_number' => $request->fasttag_number ?? null,
            'fasttag_brand' => $request->fasttag_brand ?? null,
            'date_of_issue' => $request->date_of_issue ?? null,
            'fasttag_amount' => $request->fasttag_amount ?? null,
            'opening_stock' => $request->opening_stock ?? null,
            'remarks' => $request->remarks ?? null,
            'status' => $request->status ?? null,
            'dms_location' => $request->dms_location ?? null,
            'dms_ew_create_date' => $request->dms_ew_create_date ?? null,
            'dms_invoice_no' => $request->dms_invoice_no ?? null,
            'dms_invoice_date' => $request->dms_invoice_date ?? null,
            'dms_gatepass_date' => $request->dms_gatepass_date ?? null,
            'created_at' => date('Y-m-d H:i:s'),
            
        ];
        

        if(!empty($request->file('fasttag_image'))){
                $fasttag_image = '';
                $fasttag_image_name_arr = [];
                $fasttag_image_arr = $request->file('fasttag_image');
                foreach($fasttag_image_arr as $key => $file_value){
                    $filenameWithExtension_three = $file_value->getClientOriginalName();
                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                    $extension_three = $file_value->getClientOriginalExtension();
                    $filenameToStore_three_new = "fasttag_image".time()."_".$filename_three.'.'.$extension_three;
                    array_push($fasttag_image_name_arr, $filenameToStore_three_new);                        
                    $folder_to_upload_sn = public_path().'/uploads/kyc/';
                    if(!\File::exists($folder_to_upload_sn))
                        \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                        $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                }
                if(!empty($fasttag_image_name_arr)){
                    $fasttag_image = implode(",",$fasttag_image_name_arr);
                }
                $fasttag['fasttag_image'] = $fasttag_image;
            }

            if(!empty($request->file('dms_certificate'))){
                $dms_certificate = '';
                $dms_certificate_name_arr = [];
                $dms_certificate_arr = $request->file('dms_certificate');
                foreach($dms_certificate_arr as $key => $file_value){
                    $filenameWithExtension_three = $file_value->getClientOriginalName();
                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                    $extension_three = $file_value->getClientOriginalExtension();
                    $filenameToStore_three_new = "dms_certificate".time()."_".$filename_three.'.'.$extension_three;
                    array_push($dms_certificate_name_arr, $filenameToStore_three_new);                        
                    $folder_to_upload_sn = public_path().'/uploads/kyc/';
                    if(!\File::exists($folder_to_upload_sn))
                        \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                        $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                }
                if(!empty($dms_certificate_name_arr)){
                    $dms_certificate = implode(",",$dms_certificate_name_arr);
                }
                $fasttag['dms_certificate'] = $dms_certificate;
            }

        \DB::table('obf_fasttag')->updateOrInsert(['obf_id' => $fasttag['obf_id']], $fasttag);
        
        \DB::table('obf')->where('id',$request->id)->update(['fasttag_status' => $request->status]);
        
        $fasttag_log_crud = [
            'module_nm' => 'obf_fasstag_create',
            'module_id' => $request->id,
            'status' => $request->status,
            'remark' => $request->status,
            'created_at' => now(),
            'created_by' => auth()->user()->id,
        ];
        \DB::table('logs')->insert($fasttag_log_crud);

        // Redirect with success message
        return redirect()->route('obf')->with('success', 'OBF Fasttag Details Updated...');

    } 

    public function processyodepartment(Request $request){

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);

        $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                    $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                    $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                    $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

    

                    $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

                    $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                    $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

                    $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                    $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

                    

                    

                            

                      $data = OBF::select('obf.id','obf.sales_person_id',

                                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type' ,'obf.customer_type_new' ,'obf.convinience_program' ,'branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name','obf.fasttag_brand_name AS fasttag_brand_name' ,'obf.einvoicing_applicable', 'obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id' ,'products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.id AS fasttag_id' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS brand_name','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','obf.municipal_tax_id',
                                        'obf.tcs_tax_id',
                                        'obf.registration_tax_id',
                                        'obf.insurance_id','obf.tentetive_delivery_date',

                    'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',

    

                    'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id','inventory.vin_number as vinnumber',

    

                    'obf_finance.finance_name','obf.other_accesssories_prise','obf.other_accesssories_detail','obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.pricelist_id','obf.rsa_master_obf')

                        

                                ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                                ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                                ->leftjoin('products' ,'obf.product_id' ,'products.id')

                                ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                                ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                                ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                                ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                                ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')

                                ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                                ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                                ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                                ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                                ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                                //->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')

                                ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

                                ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')

                                ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')

                                ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

                                ->leftjoin('other_one' ,'obf.other_details_1' ,'other_one.id')

                                ->leftjoin('other_two' ,'obf.other_details_2' ,'other_two.id')

                                ->leftjoin('mcp' ,'mcp.id' ,'obf.convinience_program')

                                ->where(['obf.id' => $id])

                                ->first();

                                

            $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();

    

                        // dd($carmodel);

    

    

            $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.id as varient_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

                                ->leftJoin('car_model','car_model.id','=','obf.product_id')

                                ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

                                ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                                ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                                ->where('obf.id', '=', $id)  

                                ->first();

    

            $fule = Obf::select('fule_type.title as fule_name')

            ->leftJoin('products','products.id','=','obf.product_id')

            ->leftJoin('car_varient','car_varient.id','=','products.veriant')

            ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')

            ->where('obf.id', '=', $id)  

            ->first();

    

             $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();

    

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

                

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

    

             $Inventory_data = [];

             if($data->inventory_id != NULL){

                 $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    

             }

    

            $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  

    

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

    

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

    

            $accessory_sum = 0;

            if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){

                $accessory_id_arr = explode(' ,', $data->accessory_id);

                if(!empty($accessory_id_arr)){

                    $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           

                }

            }

        return view('YODEPARTMENT.processyoepartment')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum]);

    }

    public function processyodepartmentdms(Request $request){

        $yo = [

            'obf_id'=> $request->id,

            'yodeparment_invoice' => $request->yodeparment_invoice,

            'yodeparment_invoice_date' => Carbon::parse($request->yodeparment_invoice_date)->toDateString(),

            'dms_location' => $request->dms_location,

            'dms_yodeparment_create_date' => Carbon::parse($request->dms_yodeparment_create_date)->toDateString(),

            'dms_yodeparment_certificate' => $request->dms_yodeparment_certificate,
            
            'status' => $request->yodepartment_status,


        ];

        \DB::table('yodepartment_process_dms')->updateOrInsert(['obf_id' => $yo['obf_id']], $yo);
        
        \DB::table('obf')->where('id',$request->id)->update(['yodepartment_status' => $request->yodepartment_status]);
        
        $yo_log_crud = [
            'module_nm' => 'yodepartment_process_dms_create',
            'module_id' => $request->id,
            'status' => $request->status,
            'created_at' => now(),
            'created_by' => auth()->user()->id,
        ];
        \DB::table('logs')->insert($yo_log_crud);
        

        return redirect()->route('obf');

    } 

    public function processaccesories(Request $request){

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);

        $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

        $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

        $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

        $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

        $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

        $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

        $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

        $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

        $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

        $data = OBF::select(
            'obf.id',
            'obf.sales_person_id',
            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
            'obf.temporary_id',
            'obf.booking_date',
            'obf.customer_name',
            'obf.customer_type',
            'obf.customer_type_new',
            'obf.convinience_program',
            'branches.name AS branch_name',
            'branches.id AS branch_id',
            'obf.company_name',
            'obf.fasttag_brand_name AS fasttag_brand_name',
            'obf.einvoicing_applicable', 
            'obf.gst',
            'obf.address',
            'obf.registration',
            'obf.email',
            'obf.pan_number',
            'obf.adhar_number',
            'obf.licance_number',
            'obf.contact_number',
            'obf.dob',
            'obf.nominee_name',
            'obf.nominee_reletion' ,
            'obf.nominee_age' ,
            'obf.occupation',
            'obf.tentetive_delivery_date',
            'products.name AS product_name',
            'obf.product_id' ,
            'products.veriant',
            'products.is_applicable_for_mcp' ,
            'obf.ex_showroom_price' ,
            'registration_tax.percentage AS registration_tax' ,
            'insurance.name AS insurance' ,
            'obf.insurance_id' ,
            'municipal_tax.percentage AS municipal_tax' ,
            'tcs_tax.percentage AS tcs_tax' ,
            'accessories.name AS accessory_name',
            'accessories.type AS accesories_type',
            'accessories.price AS accesories_price',
            'accessories.model_number AS accesories_model',
            'obf.accessory_id',
            'obf.extanded_warranty_id' ,
            'extand_warranties.years AS extand_warranties_years' ,
            'extand_warranties.amount AS extand_warranties_amount' ,
            'fasttags.id AS fasttag_id' ,
            'fasttags.amount AS fasttag_amount' ,
            'fasttags.brand_name AS brand_name',
            'obf.trade_car_name',
            'obf.trade_car_value',
            'obf.on_road_price' ,
            'obf.on_road_price_word' ,
            'obf.on_road_price_word',
            'obf.finance_id' ,
            'finance.name AS finance_name' ,
            'finance_branch.name AS finance_branch_name' ,
            'lead.name AS lead_name',
            'obf.lead_id' ,
            'obf.booking_amount' ,
            'obf.mode_of_payment' ,
            'obf.status' ,
            'obf.created_by' ,
            'obf.updated_by',
            'obf.created_at' ,
            'obf.updated_at',
            'obf_rto.rto_type',
            'obf_rto.registration_date',
            'obf_rto.application_number',
            'obf_rto.temporary_number',
            'obf_rto.final_amount',
            'obf_rto.vehicle_number',
            'obf_rto.status as rto_status',
            'obf_fasttag.fasttag_number',
            'obf_fasttag.fasttag_brand',
            'obf_fasttag.date_of_issue',
            'obf_fasttag.fasttag_amount',
            'obf_fasttag.opening_stock',
            'obf_fasttag.status as fasttag_status',
            'obf.other_documents',
            'obf.pan_image',
            'obf.adhar_image',
            'obf.licance_image',
            'obf.other_details_1',
            'obf.other_details_2',
            'obf.priclist_detail',
            'obf.inventory_id',
            'inventory.vin_number as vinnumber',
            'obf_finance.finance_name',
            'obf.other_accesssories_prise',
            'obf.other_accesssories_detail',
            'obf_finance.repo_rate',
            'obf_finance.net_disbusment',
            'obf_finance.loan_amount',
            'obf_finance.processing_fee',
            'obf_finance.finance_discount',
            'obf_finance.payout',
            'obf_finance.pay_booster',
            'obf_finance.finance_required',
            'obf.sub_lead_id',
            'obf.pricelist_id',
            'obf.rsa_master_obf',
            'obf.municipal_tax_id',
            'obf.tcs_tax_id',
            'obf.registration_tax_id',
            'obf.insurance_id',
        )

        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

        ->leftjoin('products' ,'obf.product_id' ,'products.id')

        ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

        ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

        ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

        ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

        ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')

        ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

        ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

        ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

        ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

        ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

        //->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')

        ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

        ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')

        ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')

        ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')

        ->leftjoin('other_one' ,'obf.other_details_1' ,'other_one.id')

        ->leftjoin('other_two' ,'obf.other_details_2' ,'other_two.id')

        ->leftjoin('mcp' ,'mcp.id' ,'obf.convinience_program')

        ->where(['obf.id' => $id])

        ->first();

                                

        $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();

        
        $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.id as varient_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

            ->leftJoin('car_model','car_model.id','=','obf.product_id')

            ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

            ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

            ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

            ->where('obf.id', '=', $id)  

            ->first();

    

        $fule = Obf::select('fule_type.title as fule_name')

            ->leftJoin('products','products.id','=','obf.product_id')

            ->leftJoin('car_varient','car_varient.id','=','products.veriant')

            ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')

            ->where('obf.id', '=', $id)  

            ->first();

    

         $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();



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

            

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



         $Inventory_data = [];

         if($data->inventory_id != NULL){

             $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    

         }



        $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  



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



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



        $accessory_sum = 0;

        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){

            $accessory_id_arr = explode(' ,', $data->accessory_id);

            if(!empty($accessory_id_arr)){

                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           

            }

        }

        return view('ACCESORIES.processaccesories')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum]);

    }

    public function processaccesoriesdms(Request $request){

        /*$accesoryImage = $request->file('dms_accesories_certificate');

        $accesoryImageName = $accesoryImage ? time().'.'.$accesoryImage->getClientOriginalExtension() : null;

        $accesoryImagePath = $request->file('accesoryImage')?->storeAs('ACCESORYIMAGE',time().'.'.$request->file('accesoryImage')?->getClientOriginalExtension(),'public');*/
        
        $accesoryImage = $request->file('dms_accesories_certificate');

        $accesoryImageName = null;
        $accesoryImagePath = null;
        
        if ($accesoryImage) {
            $accesoryImageName = time() . '.' . $accesoryImage->getClientOriginalExtension();
            $accesoryImagePath = $accesoryImage->storeAs(
                'EWIMAGE',
                $accesoryImageName,
                'public'
            );
        }


        $accessories = [

            'obf_id'=> $request->id,

            'accesories_invoice' => $request->accesories_invoice,

            'accesories_invoice_date' => Carbon::parse($request->accesories_invoice_date)->toDateString(),

            'dms_invoice_no' => $request->dms_invoice_no,

            'dms_invoice_date' => Carbon::parse($request->dms_invoice_date)->toDateString(),

            'dms_gatepass_date' => Carbon::parse($request->dms_gatepass_date)->toDateString(),

            'dms_location' => $request->dms_location,

            'dms_accesories_create_date' => Carbon::parse($request->dms_accesories_create_date)->toDateString(),

            'dms_accesories_certificate' => $accesoryImagePath,

            'status' => $request->accesories_status,

        ];

        \DB::table('accesories_process_dms')->updateOrInsert(['obf_id' => $accessories['obf_id']], $accessories);
        
        \DB::table('obf')->where('id',$request->id)->update(['accesories_status' => $request->accesories_status]);
        
        $accessories_log_crud = [
            'module_nm' => 'accesories_process_dms_create',
            'module_id' => $request->id,
            'status' => $request->status,
            'created_at' => now(),
            'created_by' => auth()->user()->id,
        ];
        \DB::table('logs')->insert($accessories_log_crud);

        return redirect()->route('obf');

    }

    public function processrto(Request $request){

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);

        $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();
        $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();
        $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();
        $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();
        $accessory = Accessory::select('id' , 'name' ,'price')->where(['status' => 'active'])->get();
        $extanded_warranty = ExtandWarranty::select('id' , 'years' ,'amount')->where(['status' => 'active'])->get();
        $fasttag = Fasttag::select('id', 'brand_name' ,'amount')->where(['status' => 'active'])->get();
        $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();
        $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();
        $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();
        $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();
        $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

        $data = OBF::select('obf.id',
            'obf.sales_person_id',
            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
            'obf.temporary_id' ,
            'obf.booking_date' ,
            'obf.customer_name' ,
            'obf.customer_type' ,
            'obf.customer_type_new' ,
            'obf.convinience_program' ,
            'obf.rsa_master_obf',
            'rsa.name as rsaname',
            'rsa.amount AS rsaamount',
            'branches.name AS branch_name' ,
            'branches.id AS branch_id' ,
            'obf.company_name',
            'obf.fasttag_brand_name AS fasttag_brand_name' ,
            'obf.einvoicing_applicable', 
            'obf.gst' ,
            'obf.address' ,
            'obf.registration' ,
            'obf.email' ,
            'obf.pan_number',
            'obf.adhar_number' ,
            'obf.licance_number',
            'obf.contact_number' ,
            'obf.dob' ,
            'obf.nominee_name',
            'obf.nominee_reletion' ,
            'obf.nominee_age' ,
            'obf.occupation',
            'obf.tentetive_delivery_date',
            'products.name AS product_name',
            'obf.product_id' ,
            'products.veriant',
            'products.is_applicable_for_mcp' ,
            'obf.ex_showroom_price' ,
            'registration_tax.percentage AS registration_tax' ,
            'insurance.name AS insurance' ,
            'obf.insurance_id' ,
            'municipal_tax.percentage AS municipal_tax' ,
            'tcs_tax.percentage AS tcs_tax' ,
            'accessories.name AS accessory_name' ,
            'obf.accessory_id',
            'obf.extanded_warranty_id' ,
            'extand_warranties.years AS extand_warranties_years' ,
            'extand_warranties.amount AS extand_warranties_amount' ,
            'fasttags.id AS fasttag_id' ,
            'fasttags.amount AS fasttag_amount' ,
            'fasttags.brand_name AS brand_name',
            'obf.trade_car_name', 
            'obf.trade_car_value', 
            'obf.on_road_price' ,
            'obf.on_road_price_word' ,
            'obf.on_road_price_word',
            'obf.finance_id' ,
            'finance.name AS finance_name' ,
            'finance_branch.name AS finance_branch_name' ,
            'lead.name AS lead_name',
            'obf.lead_id' ,
            'obf.booking_amount' ,
            'obf.mode_of_payment' ,
            'obf.status' ,
            'obf.created_by' ,
            'obf.updated_by',
            'obf.created_at' ,
            'obf.updated_at',
            'obf_rto.rto_invoice',
            'obf_rto.rto_invoice_date',
            'obf_rto.rto_type',
            'obf_rto.number_plate',
            'obf_rto.registration_date',
            'obf_rto.application_number',
            'obf_rto.temporary_number',
            'obf_rto.final_amount',
            'obf_rto.vehicle_number',
            'obf_rto.rto_status',
            'obf_rto.remarks',
            'obf_rto.status',
            'obf_rto.dms_invoice_no',
            'obf_rto.dms_invoice_date',
            'obf_rto.dms_gatepass_date',
            'obf_rto.dms_location',
            'obf_rto.dms_rto_create_date',
            'obf_rto.rto_image',
            'obf_rto.dms_rto_certificate',
            'obf_rto.created_at',
            'obf_rto.updated_at',
            'obf_fasttag.fasttag_number',
            'obf_fasttag.fasttag_brand',
            'obf_fasttag.date_of_issue',
            'obf_fasttag.fasttag_amount',
            'obf_fasttag.opening_stock',
            'obf_fasttag.status as fasttag_status',
            'obf.other_documents',
            'obf.pan_image',
            'obf.adhar_image',
            'obf.licance_image',
            'obf.other_details_1',
            'obf.other_details_2',
            'obf.priclist_detail',
            'obf.inventory_id',
            'inventory.vin_number as vinnumber',
            'obf_finance.finance_name',
            'obf.other_accesssories_prise',
            'obf.other_accesssories_detail',
            'obf_finance.repo_rate',
            'obf_finance.net_disbusment',
            'obf_finance.loan_amount',
            'obf_finance.processing_fee',
            'obf_finance.finance_discount',
            'obf_finance.payout',
            'obf_finance.pay_booster',
            'obf_finance.finance_required',
            'obf.sub_lead_id',
            'obf.pricelist_id',
            'obf.municipal_tax_id',
            'obf.tcs_tax_id',
            'obf.registration_tax_id',
            'obf.insurance_id',
            'orders.invoice_no as order_invoice_no',
            'orders.invoice_date as order_invoice_date',
        )

        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
        ->leftjoin('products' ,'obf.product_id' ,'products.id')
        ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
        ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
        ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
        ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
        ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
        ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
        ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
        ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
        ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')
        ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
        ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
        ->leftjoin('obf_fasttag','obf.id' ,'obf_fasttag.obf_id')
        ->leftjoin('obf_finance','obf.id' ,'obf_finance.obf_id')
        ->leftjoin('rto_process_dms','obf.id','rto_process_dms.obf_id')
        ->leftjoin('accessories','obf.accessory_id' ,'accessories.id')
        ->leftjoin('other_one','obf.other_details_1' ,'other_one.id')
        ->leftjoin('other_two','obf.other_details_2' ,'other_two.id')
        ->leftjoin('mcp' ,'mcp.id','obf.convinience_program')
        ->leftjoin('rsa' ,'rsa.id','obf.rsa_master_obf')
        ->leftjoin('orders' ,'orders.obf_id','obf.id')
        ->where(['obf.id' => $id])
        ->first();

        $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();

        $Cardata = Obf::select(
            'obf.id as o_id',
            'obf.product_id as o_product',
            'car_model.name as car_name',
            'car_model.id as car_id',
            'car_varient.id as varient_id',
            'car_varient.name as varient_name',
            'exteriorcolor.name as exterior_color', 
            'interiorcolor.name as interior_color'
        )
        
        ->leftJoin('car_model','car_model.id','=','obf.product_id')
        ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
        ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')
        ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')
        ->where('obf.id', '=', $id)  
        ->first();

        $fule = Obf::select(
            'fule_type.title as fule_name'
        )

        ->leftJoin('products','products.id','=','obf.product_id')
        ->leftJoin('car_varient','car_varient.id','=','products.veriant')
        ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')
        ->where('obf.id', '=', $id)  
        ->first();

        $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();
        $OtherOne = OtherOne::where(['status' => 'active'])->get();  
        $OtherTwo = OtherTwo::where(['status' => 'active'])->get(); 
        
        $Inventory_data = [];

        if($data->inventory_id != NULL){
            $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();   
        }

        $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  
        $CustomerTypeMaster = CustomerTypeMaster::where(['status' => 'active'])->get();  
        $rsa = RSA::where(['status' => 'active','deleted_at' => 0])->get();
        
        $accessory_sum = 0;
        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){
            $accessory_id_arr = explode(' ,', $data->accessory_id);
            if(!empty($accessory_id_arr)){
                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           
            }
        }
        $dms_data = [];
        if(isset($Inventory_data) && !empty($Inventory_data)){
            $dms_data = DMS::where('vin_number',$Inventory_data->vin_number)->first();    
        }
        
        $make_deal_data = OBF::select('obf.id','obf.sales_person_id',

            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.final_on_road_price_after_way_off' ,'obf.customer_type','obf.customer_type_new' ,'obf.booking_date','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' , 'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id','products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'obf.fasttag_brand_name AS fasttag_brand_name','registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount_new' ,'fasttags.id AS fasttag_id','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','allocation.tentetive_delivery_date','Team_master.team_name','obf.other_accesssories_prise','obf.municipal_custom_handling_charges','obf.rto_custom_handling_charges',
    
            'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',
    
            'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.pricelist_id','obf.registration_tax_id','obf.municipal_tax_id','obf.municipal_tax_applicable','obf.tcs_tax_id','obf.nominee_dob', 'obf.convinience_program',
    
            'obf.step1_remarks','obf.step3_remarks','obf.step4_remarks','obf.step5_remarks','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id',
    
            'obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.rsa_master_obf',
    
            'car_model.name AS car_model_name','car_varient.name AS car_varient_name','interiorcolor.name AS interiorcolor_name','exteriorcolor.name AS exteriorcolor_name','inventory.key_number','inventory.engine_number','inventory.chassis_number','inventory.vin_number', 'obf_insurance.company_name AS insurance_company_name','obf_insurance.ncb_amount','obf.offer_ib_amount','obf.offer_kin_amount','obf.offer_amount','inventory.purchase_price','inventory.aging_days','inventory.remark',
            
            'make_deal.obf_id','make_deal.purchase_gst_tax_deal','make_deal.final_deal_amt','make_deal.deal_amt','make_deal.gst_tax_deal','make_deal.cess_tax_deal','make_deal.tcs_tax_deal','make_deal.municipal_tax_deal','make_deal.municipal_custom_handling_charges_deal','make_deal.rto_deal','make_deal.insurance_deal','make_deal.rto_cutom_handling_charges_deal','make_deal.created_by','make_deal.remark as make_deal_remark','pricelist_master.rto_custome_handling_charges','mcp.id as mcp_id','mcp.name as mcp_name','mcp.amount as mcp_amount','rsa.id as rsa_id','rsa.name as rsa_name','rsa.amount as rsa_amount','rsa.rsa_ccs as rsa_type')
    
            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
            ->leftjoin('products', 'obf.product_id', 'products.id')
            ->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')
            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
            ->leftjoin('allocation' ,'obf.id' ,'allocation.obf_id')
            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')
            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')
            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
            ->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')
            ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
            ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')
            ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
            ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
            ->leftjoin('Team_master','Team_master.id','users.team_name')
            ->leftjoin('make_deal','obf.id','make_deal.obf_id')
            ->leftjoin('pricelist_master', 'obf.pricelist_id', 'pricelist_master.id')
            ->leftjoin('mcp','obf.convinience_program','mcp.id')
            ->leftjoin('rsa','obf.rsa_master_obf','rsa.id')
            ->where(['obf.id' => $id])->first();
    
            $make_deal_branch = Branch::select('start_value1', 'end_value1', 'tax_percentage1', 'start_value2', 'end_value2', 'tax_percentage2')->where(['status' => 'active','id' => $make_deal_data->branch_id])->first();
           
            $price_list_name_data = DB::table('pricelist_master')->select('basic','price_list_name','gst_percentage','gst_amount','cess_percentage','cess_amount')->where('id',  $make_deal_data->pricelist_id)->first();
    
            $make_deal_rto_data = DB::table('rto_master')->select('rto_type', 'rto_tax_individual', 'rto_tax_company', 'totali_individual_charges','totalcharges')->Where('rto_type', 'like', $make_deal_data->customer_type . '%')->orderBy('id', 'DESC')->first();
    
            $make_deal_accessory_sum = 0;
    
            if(!empty($make_deal_data->accessory_id) && $make_deal_data->accessory_id != NULL && $make_deal_data->accessory_id != ''){
                $accessory_id_arr = explode(' ,', $make_deal_data->accessory_id);
                if(!empty($accessory_id_arr)){
                    $make_deal_accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');           
                }
            }
            
            $my_con_program = Mcp::where(['status' => 'active','car_model' => $Cardata->car_id])->get();
        
        return view('RTO.processrto')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum,'dms_data'=>$dms_data,'make_deal_data' => $make_deal_data,'make_deal_branch' => $make_deal_branch,'price_list_name_data' => $price_list_name_data,'make_deal_rto_data' => $make_deal_rto_data]);

    }

    public function processrtodms(Request $request){
        try{
            $rto = [
                'obf_id' => $request->id,
                'rto_invoice' => $request->rto_invoice ?? null,
                'rto_invoice_date' => $request->rto_invoice_date ?? null,
                'rto_type' => $request->rto_type ?? null,
                'number_plate' => $request->number_plate ?? null, 
                'registration_date' => $request->registration_date ?? null,
                'application_number' => $request->application_number ?? null,
                'temporary_number' => $request->temporary_number ?? null,
                'final_amount' => $request->final_amount ?? null,
                'vehicle_number' => $request->vehicle_number ?? null,
                'rto_status' => $request->rto_status ?? null,
                'remarks' => $request->remarks ?? null,
                'status' => $request->status ?? null,
                'dms_invoice_no' => $request->dms_invoice_no ?? null,
                'dms_invoice_date' => $request->dms_invoice_date ?? null,
                'dms_gatepass_date' => $request->dms_gatepass_date ?? null,
                'dms_location' => $request->dms_location ?? null,
                'dms_rto_create_date' => $request->dms_rto_create_date ?? null,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
                
            ];
            
            if(!empty($request->file('rto_image'))){
                $rto_image = '';
                $rto_image_name_arr = [];
                $rto_image_arr = $request->file('rto_image');
                foreach($rto_image_arr as $key => $file_value){
                    $filenameWithExtension_three = $file_value->getClientOriginalName();
                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                    $extension_three = $file_value->getClientOriginalExtension();
                    $filenameToStore_three_new = "rto_image".time()."_".$filename_three.'.'.$extension_three;
                    array_push($rto_image_name_arr, $filenameToStore_three_new);                        
                    $folder_to_upload_sn = public_path().'/uploads/kyc/';
                    if(!\File::exists($folder_to_upload_sn))
                        \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                        $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                }
                if(!empty($rto_image_name_arr)){
                    $rto_image = implode(",",$rto_image_name_arr);
                }
                $rto['rto_image'] = $rto_image;
            }

            if(!empty($request->file('dms_rto_certificate'))){
                $dms_rto_certificate = '';
                $dms_rto_certificate_name_arr = [];
                $dms_rto_certificate_arr = $request->file('dms_rto_certificate');
                foreach($dms_rto_certificate_arr as $key => $file_value){
                    $filenameWithExtension_three = $file_value->getClientOriginalName();
                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                    $extension_three = $file_value->getClientOriginalExtension();
                    $filenameToStore_three_new = "dms_rto_certificate".time()."_".$filename_three.'.'.$extension_three;
                    array_push($dms_rto_certificate_name_arr, $filenameToStore_three_new);                        
                    $folder_to_upload_sn = public_path().'/uploads/kyc/';
                    if(!\File::exists($folder_to_upload_sn))
                        \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                        $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                }
                if(!empty($dms_rto_certificate_name_arr)){
                    $dms_rto_certificate = implode(",",$dms_rto_certificate_name_arr);
                }
                $rto['dms_rto_certificate'] = $dms_rto_certificate;
            }
            
            \DB::table('obf_rto')->updateOrInsert(['obf_id' => $rto['obf_id']], $rto);
            
            \DB::table('obf')->where('id',$request->id)->update(['rto_status' => $request->status]);
    
            $rto_log_crud = [
                'module_nm' => 'obf_rto_create',
                'module_id' => $request->id,
                'status' => $request->status,
                'remark' => $request->status,
                'created_at' => now(),
                'created_by' => auth()->user()->id,
            ];
            
            \DB::table('logs')->insert($rto_log_crud);
    
            return redirect()->route('obf')->with('success', 'OBF RTO Details Updated...');
        } catch (\Exception $e) {
            $data = $this->processrto($id);
            $encodedId = $request->id;
            $url = route('obf.processrto') . '?id=' . $encodedId;
            return redirect($url)->withInput()->withErrors(['error' => 'Something went wrong. Please try again.'])->with($data);
        }    

    }
    
    public function processmuniciple(Request $request){

        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);
        
        $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();
        $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();
        $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();
        $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();
        $accessory = Accessory::select('id' , 'name' ,'price')->where(['status' => 'active'])->get();
        $extanded_warranty = ExtandWarranty::select('id' , 'years' ,'amount')->where(['status' => 'active'])->get();
        $fasttag = Fasttag::select('id', 'brand_name' ,'amount')->where(['status' => 'active'])->get();
        $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();
        $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();
        $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();
        $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();
        $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();

            $data = OBF::select(
                'obf.id',
                'obf.sales_person_id',
                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                'obf.temporary_id' ,
                'obf.booking_date' ,
                'obf.customer_name' ,
                'obf.customer_type' ,
                'obf.customer_type_new' ,
                'obf.convinience_program' ,
                'branches.name AS branch_name' ,
                'branches.id AS branch_id' ,
                'obf.company_name',
                'obf.fasttag_brand_name AS fasttag_brand_name' ,
                'obf.einvoicing_applicable', 
                'obf.gst' ,
                'obf.address' ,
                'obf.registration' ,
                'obf.email' ,
                'obf.pan_number',
                'obf.adhar_number' ,
                'obf.licance_number',
                'obf.contact_number' ,
                'obf.dob' ,
                'obf.nominee_name',
                'obf.nominee_reletion' ,
                'obf.nominee_age' ,
                'obf.occupation',
                'obf.tentetive_delivery_date',
                'products.name AS product_name',
                'obf.product_id' ,
                'products.veriant',
                'products.is_applicable_for_mcp' ,
                'obf.ex_showroom_price' ,
                'registration_tax.percentage AS registration_tax' ,
                'insurance.name AS insurance' ,
                'obf.insurance_id' ,
                'municipal_tax.percentage AS municipal_tax' ,
                'tcs_tax.percentage AS tcs_tax' ,
                'accessories.name AS accessory_name' ,
                'obf.accessory_id',
                'obf.extanded_warranty_id' ,
                'extand_warranties.years AS extand_warranties_years' ,
                'extand_warranties.amount AS extand_warranties_amount' ,
                'fasttags.id AS fasttag_id' ,
                'fasttags.amount AS fasttag_amount' ,
                'fasttags.brand_name AS brand_name',
                'obf.trade_car_name', 
                'obf.trade_car_value', 
                'obf.on_road_price' ,
                'obf.on_road_price_word' ,
                'obf.on_road_price_word',
                'obf.finance_id' ,
                'finance.name AS finance_name' ,
                'finance_branch.name AS finance_branch_name' ,
                'lead.name AS lead_name',
                'obf.lead_id' ,
                'obf.booking_amount' ,
                'obf.mode_of_payment' ,
                'obf.status' ,
                'obf.created_by' ,
                'obf.updated_by',
                'obf.created_at' ,
                'obf.updated_at',
                'obf_rto.rto_type',
                'obf_rto.registration_date',
                'obf_rto.application_number',
                'obf_rto.temporary_number',
                'obf_rto.final_amount',
                'obf_rto.vehicle_number',
                'obf_rto.status as rto_status',
                'obf_rto.number_plate',
                'obf_rto.remarks',
                'obf_fasttag.fasttag_number',
                'obf_fasttag.fasttag_brand',
                'obf_fasttag.date_of_issue',
                'obf_fasttag.fasttag_amount',
                'obf_fasttag.opening_stock',
                'obf_fasttag.status as fasttag_status',
                'obf_fasttag.remarks',
                'obf_fasttag.dms_location',
                'obf_fasttag.dms_ew_create_date',
                'obf_fasttag.ew_invoice',
                'obf_fasttag.ew_invoice_date',
                'obf_fasttag.fasttag_image',
                'obf_fasttag.dms_certificate',
                'obf_fasttag.dms_invoice_no',
                'obf_fasttag.dms_invoice_date',
                'obf_fasttag.dms_gatepass_date',
                'obf_municiple_tax.rmc_receipt_no',
                'obf_municiple_tax.municiple_date',
                'obf_municiple_tax.municiple_image',
                'obf_municiple_tax.tax_type',
                'obf_municiple_tax.remarks',
                'obf_municiple_tax.dms_location',
                'obf_municiple_tax.dms_mt_create_date',
                'obf_municiple_tax.mt_invoice',
                'obf_municiple_tax.mt_invoice_date',
                'obf_municiple_tax.dms_certificate',
                'obf_municiple_tax.dms_invoice_no',
                'obf_municiple_tax.dms_invoice_date',
                'obf_municiple_tax.dms_gatepass_date',
                'obf_municiple_tax.status as municiple_status',
                'obf.other_documents',
                'obf.pan_image',
                'obf.adhar_image',
                'obf.licance_image',
                'obf.other_details_1',
                'obf.other_details_2',
                'obf.priclist_detail',
                'obf.inventory_id',
                'obf.municipal_tax_id',
                'obf.tcs_tax_id',
                'obf.registration_tax_id',
                'obf.insurance_id',
                DB::raw('(SELECT vin_number FROM inventory WHERE inventory.status = "allocated" AND inventory.id = obf.inventory_id) as vinnumber'),
                'obf_finance.finance_name',
                'obf.other_accesssories_prise',
                'obf.other_accesssories_detail',
                'obf_finance.repo_rate',
                'obf_finance.net_disbusment',
                'obf_finance.loan_amount',
                'obf_finance.processing_fee',
                'obf_finance.finance_discount',
                'obf_finance.payout',
                'obf_finance.pay_booster',
                'obf_finance.finance_required',
                'obf.sub_lead_id',
                'obf.pricelist_id',
                'obf.rsa_master_obf',
                'orders.invoice_no as order_invoice_no',
                'orders.invoice_date as order_invoice_date',
                'obf.municipal_tax_type',
                'municipal_custom_handling_charges', 
            )
            
            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
            ->leftjoin('products' ,'obf.product_id' ,'products.id')
            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
            ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')
            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
            ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
            ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')
            ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
            ->leftjoin('obf_municiple_tax','obf.id','obf_municiple_tax.obf_id')
            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')
            ->leftjoin('other_one' ,'obf.other_details_1' ,'other_one.id')
            ->leftjoin('other_two' ,'obf.other_details_2' ,'other_two.id')
            ->leftjoin('mcp' ,'mcp.id' ,'obf.convinience_program')
            ->leftjoin('orders' ,'orders.obf_id','obf.id') 
            ->where(['obf.id' => $id])
            ->first();

            $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();

             $Cardata = Obf::select(
                'obf.id as o_id',
                'obf.product_id as o_product',
                'car_model.name as car_name',
                'car_model.id as car_id',
                'car_varient.id as varient_id',
                'car_varient.name as varient_name',
                'exteriorcolor.name as exterior_color', 
                'interiorcolor.name as interior_color'
            )
            ->leftjoin('products', 'obf.product_id', 'products.id')
            ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
            ->leftjoin('car_model', 'car_model.id', 'products.car_model')
            ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
            ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
            ->where('obf.id', '=', $id)  
            ->first();

    

            $fule = Obf::select('fule_type.title as fule_name')
            ->leftJoin('products','products.id','=','obf.product_id')
            ->leftJoin('car_varient','car_varient.id','=','products.veriant')
            ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')
            ->where('obf.id', '=', $id)  
            ->first();

            $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();
            $OtherOne = OtherOne::where(['status' => 'active'])->get();  
            $OtherTwo = OtherTwo::where(['status' => 'active'])->get(); 
            
            $Inventory_data = [];

            if($data->inventory_id != NULL){
                 $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    
            }

            $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  
            $CustomerTypeMaster = CustomerTypeMaster::where(['status' => 'active'])->get();  
            $rsa = RSA::where(['status' => 'active','deleted_at' => 0])->get();

            $accessory_sum = 0;
            if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){
                $accessory_id_arr = explode(' ,', $data->accessory_id);
                if(!empty($accessory_id_arr)){
                    $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           
                }
            }
            
            $make_deal_data = OBF::select('obf.id','obf.sales_person_id',

            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.final_on_road_price_after_way_off' ,'obf.customer_type','obf.customer_type_new' ,'obf.booking_date','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' , 'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id','products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'obf.fasttag_brand_name AS fasttag_brand_name','registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount_new' ,'fasttags.id AS fasttag_id','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','allocation.tentetive_delivery_date','Team_master.team_name','obf.other_accesssories_prise','obf.municipal_custom_handling_charges','obf.rto_custom_handling_charges',
    
            'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',
    
            'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.pricelist_id','obf.registration_tax_id','obf.municipal_tax_id','obf.municipal_tax_applicable','obf.tcs_tax_id','obf.nominee_dob', 'obf.convinience_program',
    
            'obf.step1_remarks','obf.step3_remarks','obf.step4_remarks','obf.step5_remarks','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id',
    
            'obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.rsa_master_obf',
    
            'car_model.name AS car_model_name','car_varient.name AS car_varient_name','interiorcolor.name AS interiorcolor_name','exteriorcolor.name AS exteriorcolor_name','inventory.key_number','inventory.engine_number','inventory.chassis_number','inventory.vin_number', 'obf_insurance.company_name AS insurance_company_name','obf_insurance.ncb_amount','obf.offer_ib_amount','obf.offer_kin_amount','obf.offer_amount','inventory.purchase_price','inventory.aging_days','inventory.remark',
            
            'make_deal.obf_id','make_deal.purchase_gst_tax_deal','make_deal.final_deal_amt','make_deal.deal_amt','make_deal.gst_tax_deal','make_deal.cess_tax_deal','make_deal.tcs_tax_deal','make_deal.municipal_tax_deal','make_deal.municipal_custom_handling_charges_deal','make_deal.rto_deal','make_deal.insurance_deal','make_deal.rto_cutom_handling_charges_deal','make_deal.created_by','make_deal.remark','pricelist_master.rto_custome_handling_charges','mcp.id as mcp_id','mcp.name as mcp_name','mcp.amount as mcp_amount','rsa.id as rsa_id','rsa.name as rsa_name','rsa.amount as rsa_amount','rsa.rsa_ccs as rsa_type')
    
            ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
            ->leftjoin('products', 'obf.product_id', 'products.id')
            ->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')
            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
            ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
            ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
            ->leftjoin('allocation' ,'obf.id' ,'allocation.obf_id')
            ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')
            ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
            ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
            ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
            ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')
            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
            ->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')
            ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
            ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')
            ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
            ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
            ->leftjoin('Team_master','Team_master.id','users.team_name')
            ->leftjoin('make_deal','obf.id','make_deal.obf_id')
            ->leftjoin('pricelist_master', 'obf.pricelist_id', 'pricelist_master.id')
            ->leftjoin('mcp','obf.convinience_program','mcp.id')
            ->leftjoin('rsa','obf.rsa_master_obf','rsa.id')
            ->where(['obf.id' => $id])->first(); 
    
            $make_deal_branch = Branch::select('start_value1', 'end_value1', 'tax_percentage1', 'start_value2', 'end_value2', 'tax_percentage2')->where(['status' => 'active','id' => $make_deal_data->branch_id])->first();
           
            $price_list_name_data = DB::table('pricelist_master')->select('basic','price_list_name','gst_percentage','gst_amount','cess_percentage','cess_amount')->where('id',  $make_deal_data->pricelist_id)->first();
    
            $make_deal_rto_data = DB::table('rto_master')->select('rto_type', 'rto_tax_individual', 'rto_tax_company', 'totali_individual_charges','totalcharges')->Where('rto_type', 'like', $make_deal_data->customer_type . '%')->orderBy('id', 'DESC')->first();
    
            $make_deal_accessory_sum = 0;
    
            if(!empty($make_deal_data->accessory_id) && $make_deal_data->accessory_id != NULL && $make_deal_data->accessory_id != ''){
                $accessory_id_arr = explode(' ,', $make_deal_data->accessory_id);
                if(!empty($accessory_id_arr)){
                    $make_deal_accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');           
                }
            }
            
            $my_con_program = Mcp::where(['status' => 'active','car_model' => $Cardata->car_id])->get();

        return view('municipletax.processmunicipletax')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum,'make_deal_data' => $make_deal_data,'make_deal_branch' => $make_deal_branch,'price_list_name_data' => $price_list_name_data,'make_deal_rto_data' => $make_deal_rto_data]);
    }

    public function processmunicipledms(Request $request){
        // dd($request->all());
        $id = base64_decode($request->id);
        
        try{
           $municiple = [
            'obf_id' => $request->id,
            'mt_invoice' => $request->mt_invoice ?? null,
            'mt_invoice_date' => $request->mt_invoice_date ?? null,
            'rmc_receipt_no' => $request->rmc_receipt_no ?? null,
            'municiple_date' => $request->municiple_date ?? null,
            'tax_type' => $request->tax_type ?? null,
            'amount' => $request->amount ?? null,
            'remarks' => $request->remarks ?? null,
            'status' => $request->status ?? null,
            'dms_location' => $request->dms_location ?? null,
            'dms_mt_create_date' => $request->dms_mt_create_date ?? null,
            'dms_invoice_no' => $request->dms_invoice_no ?? null,
            'dms_invoice_date' => $request->dms_invoice_date ?? null,
            'dms_gatepass_date' => $request->dms_gatepass_date ?? null,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            
        ];
        

        if(!empty($request->file('municiple_image'))){
            $municiple_image = '';
            $municiple_image_name_arr = [];
            $municiple_image_arr = $request->file('municiple_image');
            foreach($municiple_image_arr as $key => $file_value){
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "municiple_image".time()."_".$filename_three.'.'.$extension_three;
                array_push($municiple_image_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/kyc/';
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                    $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
            if(!empty($municiple_image_name_arr)){
                $municiple_image = implode(",",$municiple_image_name_arr);
            }
            $municiple['municiple_image'] = $municiple_image;
        }
        \DB::table('obf_municiple_tax')->updateOrInsert(['obf_id' => $municiple['obf_id']], $municiple);
        
        \DB::table('obf')->where('id',$request->id)->update(['municipal_tax_status' => $request->status]);
        
        $municiple_log_crud = [
            'module_nm' => 'obf_fasstag_create',
            'module_id' => $request->id,
            'status' => $request->status,
            'remark' => $request->status,
            'created_at' => now(),
            'created_by' => auth()->user()->id,
        ];
        
        \DB::table('logs')->insert($municiple_log_crud);

        // Redirect with success message
        return redirect()->route('obf')->with('success', 'OBF Municiple Details Updated...');

        } catch (\Exception $e) {
            dd($e);
            $encodedId = $request->id;
            $url = route('obf.processmunicipletax') . '?id=' . $encodedId;
            return redirect($url)->withInput()->withErrors(['error' => 'Something went wrong. Please try again.']);
        }    
    }
    
    public function processinsurance(Request $request){
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);
        view()->share('id',$id);
        $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();
        $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();
        $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();
        $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();
        $accessory = Accessory::select('id' , 'name' ,'price')->where(['status' => 'active'])->get();
        $extanded_warranty = ExtandWarranty::select('id' , 'years' ,'amount')->where(['status' => 'active'])->get();
        $fasttag = Fasttag::select('id', 'brand_name' ,'amount')->where(['status' => 'active'])->get();
        $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();
        $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();
        $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();
        $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();
        $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();
        $data = OBF::select(
            'obf.id',
            'obf.sales_person_id',
            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
            'obf.temporary_id',
            'obf.booking_date',
            'obf.customer_name',
            'obf.customer_type',
            'obf.customer_type_new',
            'obf.convinience_program',
            'branches.name AS branch_name',
            'branches.id AS branch_id',
            'obf.company_name',
            'obf.fasttag_brand_name AS fasttag_brand_name',
            'obf.einvoicing_applicable',
            'obf.gst',
            'obf.address',
            'obf.registration',
            'obf.email',
            'obf.pan_number',
            'obf.adhar_number',
            'obf.licance_number',
            'obf.contact_number',
            'obf.dob',
            'obf.nominee_name',
            'obf.nominee_reletion',
            'obf.nominee_age',
            'obf.occupation',
            'products.name AS product_name',
            'obf.product_id',
            'products.veriant',
            'products.is_applicable_for_mcp',
            'obf.ex_showroom_price',
            'obf.tentetive_delivery_date',
            'registration_tax.percentage AS registration_tax',
            'insurance.name AS insurance' ,'obf.insurance_id',
            'municipal_tax.percentage AS municipal_tax',
            'tcs_tax.percentage AS tcs_tax',
            'accessories.name AS accessory_name',
            'accessories.type AS accesories_type',
            'accessories.price AS accesories_price',
            'accessories.model_number AS accesories_model',
            'obf.accessory_id',
            'obf.extanded_warranty_id',
            'extand_warranties.years AS extand_warranties_years',
            'extand_warranties.amount AS extand_warranties_amount',
            'fasttags.id AS fasttag_id',
            'fasttags.amount AS fasttag_amount',
            'fasttags.brand_name AS brand_name',
            'obf.trade_car_name', 
            'obf.trade_car_value', 
            'obf.on_road_price',
            'obf.on_road_price_word',
            'obf.finance_id',
            'obf.municipal_tax_id',
            'obf.tcs_tax_id',
            'obf.registration_tax_id',
            'obf.insurance_id',
            'finance.name AS finance_name',
            'lead.name AS lead_name',
            'obf.lead_id',
            'obf.booking_amount',
            'obf.mode_of_payment',
            'obf.status',
            'obf.created_by',
            'obf.updated_by',
            'obf.created_at',
            'obf.updated_at',
            'obf_rto.rto_type',
            'obf_rto.registration_date',
            'obf_rto.application_number',
            'obf_rto.temporary_number',
            'obf_rto.final_amount',
            'obf_rto.vehicle_number',
            'obf_rto.status as rto_status',
            'obf_fasttag.fasttag_number',
            'obf_fasttag.fasttag_brand',
            'obf_fasttag.date_of_issue',
            'obf_fasttag.fasttag_amount',
            'obf_fasttag.opening_stock',
            'obf_fasttag.status as fasttag_status',
            'obf.other_documents','obf.pan_image',
            'obf.adhar_image','obf.licance_image',
            'obf.other_details_1',
            'obf.other_details_2',
            'obf.priclist_detail',
            'obf.inventory_id',
            'inventory.vin_number as vinnumber',
            'obf_finance.finance_name',
            'obf.other_accesssories_prise',
            'obf.other_accesssories_detail',
            'obf_finance.repo_rate',
            'obf_finance.net_disbusment',
            'obf_finance.loan_amount',
            'obf_finance.processing_fee',
            'obf_finance.finance_discount',
            'obf_finance.payout',
            'obf_finance.pay_booster',
            'obf_finance.finance_required',
            'obf.sub_lead_id',
            'obf.pricelist_id',
            'obf.rsa_master_obf',
            'obf_insurance.insurance_exist',
            'obf_insurance.ncb',
            'obf_insurance.date_of_insurance',
            'obf_insurance.time_of_insurance',
            'obf_insurance.last_time_of_insurance',
            'obf_insurance.company_name as insurance_company_name',
            'obf_insurance.ncb_amount',
            'obf_insurance.policy_number',
            'obf_insurance.insurance_status',
            'obf_insurance.remarks',
            'obf_insurance.issue_date',
            'obf_insurance.risk_start_date',
            'obf_insurance.risk_end_date',
            'obf_insurance.tyre_no1',
            'obf_insurance.tyre_company_1',
            'obf_insurance.tyre_year_1',
            'obf_insurance.tyre_no2',
            'obf_insurance.tyre_company_2',
            'obf_insurance.tyre_year_2',
            'obf_insurance.tyre_no3',
            'obf_insurance.tyre_company_3',
            'obf_insurance.tyre_year_3',
            'obf_insurance.tyre_no4',
            'obf_insurance.tyre_company_4',
            'obf_insurance.tyre_year_4',
            'obf_insurance.tyre_no5',
            'obf_insurance.tyre_company_5',
            'obf_insurance.tyre_year_5',
            'obf_insurance.status',
            'obf_insurance.handicap',
            'obf_insurance.handicap_image',
            'obf_insurance.insurance_image',
            'obf_insurance.old_rc_book_image',
            'obf_insurance.policy_image',
            'obf_insurance.ncb_certificate_image',
            'obf.insurance_company_name',
            'obf_insurance.own_damage_premium',
            'obf_insurance.gross_premium_paid' 
        )
        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
        ->leftjoin('products' ,'obf.product_id' ,'products.id')
        ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
        ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
        ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
        ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
        ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
        ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
        ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')
        ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
        ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
        ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
        ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')
        ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
        ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')
        ->leftjoin('other_one' ,'obf.other_details_1' ,'other_one.id')
        ->leftjoin('other_two' ,'obf.other_details_2' ,'other_two.id')
        ->leftjoin('mcp' ,'mcp.id' ,'obf.convinience_program')
        ->leftjoin('obf_insurance' ,'obf_insurance.obf_id' ,'obf.id')
        ->where(['obf.id' => $id])
        ->first();
        
        $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();

        $Cardata = Obf::select(
            'obf.id as o_id',
            'obf.product_id as o_product',
            'car_model.name as car_name',
            'car_model.id as car_id',
            'car_varient.id as varient_id',
            'car_varient.name as varient_name',
            'exteriorcolor.name as exterior_color', 
            'interiorcolor.name as interior_color'
        )
        ->leftJoin('car_model','car_model.id','=','obf.product_id')
        ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
        ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')
        ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')
        ->where('obf.id', '=', $id)  
        ->first();

        $fule = Obf::select('fule_type.title as fule_name')
        ->leftJoin('products','products.id','=','obf.product_id')
        ->leftJoin('car_varient','car_varient.id','=','products.veriant')
        ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')
        ->where('obf.id', '=', $id)  
        ->first();

        $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();
        $OtherOne = OtherOne::where(['status' => 'active'])->get();  
        $OtherTwo = OtherTwo::where(['status' => 'active'])->get(); 
        
        $Inventory_data = [];
        // if($data->inventory_id != NULL){
        //     $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    
        // }

        $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  
        $CustomerTypeMaster = CustomerTypeMaster::where(['status' => 'active'])->get();  
        $rsa = RSA::where(['status' => 'active','deleted_at' => 0])->get();

        $accessory_sum = 0;
        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){
            $accessory_id_arr = explode(' ,', $data->accessory_id);
            if(!empty($accessory_id_arr)){
                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           
            }
        }

        return view('obf_insurance.process_insurance')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum]);
    }

    public function processinsurancedms(Request $request){
        try {
            $insurance = [
                'obf_id' => $request->id,
                'insurance_exist' => $request->insurance_exist ?? 1,
                'ncb' => $request->ncb ?? null,
                'date_of_insurance' => $request->date_of_insurance ?? null ,
                'time_of_insurance' => $request->time_of_insurance ?? null,
                'last_time_of_insurance' => $request->last_time_of_insurance3 ?? null, 
                'company_name' => $request->insurance_company_name ?? null,
                'own_damage_premium' => $request->own_damage_premium ?? null,
                'gross_premium_paid' => $request->gross_premium_paid ?? null,
                'ncb_amount' => $request->ncb_amount ?? null,
                'policy_number' => $request->policy_number ?? null,
                'insurance_status' => $request->insurance_status ?? null,
                'remarks' => $request->insurance_remarks ?? null,
                'issue_date' => $request->issue_date ?? null,
                'risk_start_date' => $request->risk_start_date ?? null,
                'risk_end_date' => $request->risk_end_date ?? null,
                'handicap' => $request->handicap ?? null,
                'tyre_no1' => $request->tyre_no1 ?? null, 
                'tyre_company_1' => $request->tyre_company_1 ?? null,
                'tyre_year_1' => $request->tyre_year_1 ?? null,
                'tyre_no2' => $request->tyre_no2 ?? null, 
                'tyre_company_2' => $request->tyre_company_2 ?? null,
                'tyre_year_2' => $request->tyre_year_2 ?? null,
                'tyre_no3' => $request->tyre_no3 ?? null, 
                'tyre_company_3' => $request->tyre_company_3 ?? null,
                'tyre_year_3' => $request->tyre_year_3 ?? null,
                'tyre_no4' => $request->tyre_no4 ?? null, 
                'tyre_company_4' => $request->tyre_company_4 ?? null,
                'tyre_year_4' => $request->tyre_year_4 ?? null,
                'tyre_no5' => $request->tyre_no5 ?? null, 
                'tyre_company_5' => $request->tyre_company_5 ?? null,
                'tyre_year_5' => $request->tyre_year_5 ?? null,
                'status' => $request->status ?? null,
                'is_delete' => 0,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            
            if(!empty($request->file('insurance_image'))){
                $insurance_image = '';
                $insurance_image_name_arr = [];
                $insurance_image_arr = $request->file('insurance_image');
                foreach($insurance_image_arr as $key => $file_value){
                    $filenameWithExtension_three = $file_value->getClientOriginalName();
                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                    $extension_three = $file_value->getClientOriginalExtension();
                    $filenameToStore_three_new = "insurance_image_".time()."_".$filename_three.'.'.$extension_three;
                    array_push($insurance_image_name_arr, $filenameToStore_three_new);                        
                    $folder_to_upload_sn = public_path().'/uploads/kyc/';
                    if(!\File::exists($folder_to_upload_sn))
                        \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                     $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                }
                if(!empty($insurance_image_name_arr)){
                    $insurance_image = implode(",",$insurance_image_name_arr);
                }
                $insurance['insurance_image'] = $insurance_image;
            }
            
            if(!empty($request->file('handicap_image'))){
                $handicap_image = '';
                $handicap_image_name_arr = [];
                $handicap_image_arr = $request->file('handicap_image');
                foreach($handicap_image_arr as $key => $file_value){
                    $filenameWithExtension_three = $file_value->getClientOriginalName();
                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                    $extension_three = $file_value->getClientOriginalExtension();
                    $filenameToStore_three_new = "handicap_image_".time()."_".$filename_three.'.'.$extension_three;
                    array_push($handicap_image_name_arr, $filenameToStore_three_new);                        
                    $folder_to_upload_sn = public_path().'/uploads/kyc/';
                    if(!\File::exists($folder_to_upload_sn))
                        \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                     $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                }
                if(!empty($handicap_image_name_arr)){
                    $handicap_image = implode(",",$handicap_image_name_arr);
                }
                $insurance['handicap_image'] = $handicap_image;
            }
            
            if(!empty($request->file('old_rc_book_image'))){
                $old_rc_book_image = '';
                $old_rc_book_image_name_arr = [];
                $old_rc_book_image_arr = $request->file('old_rc_book_image');
                foreach($old_rc_book_image_arr as $key => $file_value){
                    $filenameWithExtension_three = $file_value->getClientOriginalName();
                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                    $extension_three = $file_value->getClientOriginalExtension();
                    $filenameToStore_three_new = "old_rc_book_image".time()."_".$filename_three.'.'.$extension_three;
                    array_push($old_rc_book_image_name_arr, $filenameToStore_three_new);                        
                    $folder_to_upload_sn = public_path().'/uploads/kyc/';
                    if(!\File::exists($folder_to_upload_sn))
                        \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                     $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                }
                if(!empty($old_rc_book_image_name_arr)){
                    $old_rc_book_image = implode(",",$old_rc_book_image_name_arr);
                }
                $insurance['old_rc_book_image'] = $old_rc_book_image;
            }
            
            if(!empty($request->file('policy_image'))){
                $policy_image = '';
                $policy_image_name_arr = [];
                $policy_image_arr = $request->file('policy_image');
                foreach($policy_image_arr as $key => $file_value){
                    $filenameWithExtension_three = $file_value->getClientOriginalName();
                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                    $extension_three = $file_value->getClientOriginalExtension();
                    $filenameToStore_three_new = "policy_image".time()."_".$filename_three.'.'.$extension_three;
                    array_push($policy_image_name_arr, $filenameToStore_three_new);                        
                    $folder_to_upload_sn = public_path().'/uploads/kyc/';
                    if(!\File::exists($folder_to_upload_sn))
                        \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                        $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                }
                if(!empty($policy_image_name_arr)){
                    $policy_image = implode(",",$policy_image_name_arr);
                }
                $insurance['policy_image'] = $policy_image;
            }
            
            if(!empty($request->file('ncb_certificate_image'))){
                $ncb_certificate_image = '';
                $ncb_certificate_image_name_arr = [];
                $ncb_certificate_image_arr = $request->file('ncb_certificate_image');
                foreach($ncb_certificate_image_arr as $key => $file_value){
                    $filenameWithExtension_three = $file_value->getClientOriginalName();
                    $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                    $extension_three = $file_value->getClientOriginalExtension();
                    $filenameToStore_three_new = "ncb_certificate_image".time()."_".$filename_three.'.'.$extension_three;
                    array_push($ncb_certificate_image_name_arr, $filenameToStore_three_new);                        
                    $folder_to_upload_sn = public_path().'/uploads/kyc/';
                    if(!\File::exists($folder_to_upload_sn))
                        \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                        $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
                }
                if(!empty($ncb_certificate_image_name_arr)){
                    $ncb_certificate_image = implode(",",$ncb_certificate_image_name_arr);
                }
                $insurance['ncb_certificate_image'] = $ncb_certificate_image;
            }
            
            \DB::table('obf_insurance')->updateOrInsert(['obf_id' => $insurance['obf_id']],$insurance);
            
            \DB::table('obf')->where('id',$request->id)->update(['insurance_status' => $request->status]);
    
            $insurance_log_crud = [
                'module_nm' => 'obf_insurance_create',
                'module_id' => $request->id,
                'status' => $request->status,
                'remark' => $request->status,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
            ];
            \DB::table('logs')->insert($insurance_log_crud);
            
            return redirect()->route('obf')->with('success', 'OBF Insurance Details Updated...');
        } catch (\Exception $e) {
            $data = $this->getProcessInsuranceData($id);
            $encodedId = $request->id;
            $url = route('obf.processinsurance') . '?id=' . $encodedId;
            return redirect($url)->withInput()->withErrors(['error' => 'Something went wrong. Please try again.'])->with($data);
        }
    }
    
    public function processfinance(Request $request){
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', '300');

        $id = base64_decode($request->id);

                    $product = Product::select('id' , 'name' ,'veriant')->where(['status' => 'active'])->get();

                    $tax_1 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'registration_tax'])->first();

                    $tax_2 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'municipal_tax'])->first();

                    $tax_3 = Tax::select('id' , 'name' ,'percentage')->where(['status' => 'active' ,'name' => 'tcs_tax'])->first();

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

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

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

    

                    $branch = Branch::select('id' , 'name' ,'city')->where(['status' => 'active'])->get();

                    $insurance = Insurance::select('id' , 'name')->where(['status' => 'active'])->get();

                    $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

                    $lead = Lead::select('id' ,'name')->where(['status' => 'active'])->get();

                    $car_exchange = CarExchange::select('car_exchange.id' ,'car_exchange.price','cep.name AS product_name')->leftjoin('car_exchange_product AS cep' ,'car_exchange.product_id' ,'cep.id')->get();
                            

                $data = OBF::select('obf.id','obf.sales_person_id',

                                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type' ,'obf.customer_type_new' ,'obf.convinience_program' ,'obf.rsa_master_obf','rsa.name as rsaname','rsa.amount AS rsaamount','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name','obf.fasttag_brand_name AS fasttag_brand_name' ,'obf.einvoicing_applicable', 'obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id' ,'products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.id AS fasttag_id' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS brand_name','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','obf.municipal_tax_id',
                                        'obf.tcs_tax_id',
                                        'obf.registration_tax_id',
                                        'obf.insurance_id','obf.tentetive_delivery_date',

                    'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',

    

                    'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id','inventory.vin_number as vinnumber',

    

                    'obf_finance.finance_name','obf.other_accesssories_prise','obf.other_accesssories_detail','obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.pricelist_id')

                        

                                ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')

                                ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')

                                ->leftjoin('products' ,'obf.product_id' ,'products.id')

                                ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')

                                ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')

                                ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')

                                ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')

                                ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')

                                ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')

                                ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')

                                ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')

                                ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')

                                ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')

                                ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

                                ->leftjoin('obf_fasttag','obf.id' ,'obf_fasttag.obf_id')

                                ->leftjoin('obf_finance','obf.id' ,'obf_finance.obf_id')

                                ->leftjoin('accessories','obf.accessory_id' ,'accessories.id')

                                ->leftjoin('other_one','obf.other_details_1' ,'other_one.id')

                                ->leftjoin('other_two','obf.other_details_2' ,'other_two.id')

                                ->leftjoin('mcp' ,'mcp.id','obf.convinience_program')

                                ->leftjoin('rsa' ,'rsa.id','obf.rsa_master_obf')

                                ->where(['obf.id' => $id])

                                ->first();

                                

            $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();

    

                        // dd($carmodel);

    

    

            $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.id as varient_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

                                ->leftJoin('car_model','car_model.id','=','obf.product_id')

                                ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')

                                ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')

                                ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')

                                ->where('obf.id', '=', $id)  

                                ->first();

    

            $fule = Obf::select('fule_type.title as fule_name')

            ->leftJoin('products','products.id','=','obf.product_id')

            ->leftJoin('car_varient','car_varient.id','=','products.veriant')

            ->leftJoin('fule_type','fule_type.id','=','car_varient.fule_type')

            ->where('obf.id', '=', $id)  

            ->first();

    

             $mcp = Mcp::select('id' ,'name')->where(['status' => 'active'])->get();

    

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

                

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

    

             $Inventory_data = [];

             if($data->inventory_id != NULL){

                 $Inventory_data = Inventory::where('id', '=', $data->inventory_id)->first();    

             }

    

            $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->first();  

    

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

    

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

    

            $accessory_sum = 0;

            if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){

                $accessory_id_arr = explode(' ,', $data->accessory_id);

                if(!empty($accessory_id_arr)){

                    $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');;           

                }

            }
            
            $ObfFinance = DB::table('obf_finance')->where(['obf_id'=> $id])->orderBy('id', 'desc')->first();  
            
            $finance = Finance::select('finance.id' ,'finance.name' ,'branches.name AS branch_name' ,'branches.id AS branch_id')->leftjoin('branches' ,'finance.branch_id' ,'branches.id')->where(['finance.status' => 'active'])->get();

        return view('obf_finance.processfinance')->with(['data' =>$data,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead, 'OtherOne' => $OtherOne, 'mcp' => $mcp, 'OtherTwo' => $OtherTwo,'Inventory_data' => $Inventory_data,'ObfInsurance' => $ObfInsurance,'fule' => $fule, 'CustomerTypeMaster' => $CustomerTypeMaster,'rsa' => $rsa,'accessory_sum' => $accessory_sum,'finance' => $finance,'ObfFinance'=>$ObfFinance]);
    }
    
    public function processfinancedms(Request $request){

        $obf_finance = [
            'obf_id'=>$request->id,
            'finance_required' => $request->finance_required ?? null,
            'finance_name' => $request->finance_name ?? null,
            'repo_rate' => $request->repo_rate ?? null,
            'net_disbusment' => $request->net_disbusment ?? null,
            'loan_amount' => $request->loan_amount ?? null,
            'processing_fee' => $request->processing_fee ?? null,
            'finance_discount' => $request->finance_discount ?? null,
            'payout' => $request->payout ?? null,
            'pay_booster' => $request->pay_booster ?? null,
            'booster_percentage' => $request->booster_percentage ?? null,
            'finance_type' => $request->finance_type ?? null,
            'delivery_on_d_o' => $request->delivery_on_d_o ?? null,
            'disbursement' => $request->disbursement ?? null,
            'payout_amount'=>$request->payout_amount ?? null,
            'lumsum_amount'=>$request->lumsum_amount ?? null,
            'total_payout_amount'=>$request->total_payout_amount ?? null,
            'boostamt'=>$request->boostamt ?? null,
            'finance_step_remarks' => $request->finance_step_remarks ?? null,
        ];
    
        if(!empty($request->file('finance_image'))){
    
            $finance_image_name_arr = [];
            $finance_image_arr = $request->file('finance_image');
    
            foreach($finance_image_arr as $file_value){
    
                $filenameWithExtension = $file_value->getClientOriginalName();
                $filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
                $extension = $file_value->getClientOriginalExtension();
    
                $filenameToStore = "finance_image_".time()."_".$filename.'.'.$extension;
    
                $finance_image_name_arr[] = $filenameToStore;
    
                $folder_to_upload = public_path().'/uploads/kyc/';
                if(!\File::exists($folder_to_upload)){
                    \File::makeDirectory($folder_to_upload, 0777, true, true);
                }
    
                $file_value->move($folder_to_upload, $filenameToStore);
            }
    
            $obf_finance['finance_image'] = implode(",", $finance_image_name_arr);
        }
    
        \DB::table('obf_finance')->updateOrInsert(
            ['obf_id' => $obf_finance['obf_id']],
            $obf_finance
        );
    
        $finance_log_crud = [
            'module_nm' => 'obf_finance_create',
            'module_id' => $request->id,
            'status' => 'finance_process',
            'remark' => 'Finance Process',
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
        ];
    
        \DB::table('logs')->insert($finance_log_crud);
    
        return redirect()->route('obf')->with('success', 'OBF Finance Details Updated...');
    }
    
    public function getObfCounts()
        {
            $modelCounts = DB::table('car_model')
                ->select('name', DB::raw('COUNT(*) as count'))
                ->groupBy('name')
                ->get();
        
            $variantCounts = DB::table('car_varient')
                ->select('name', DB::raw('COUNT(*) as count'))
                ->groupBy('name')
                ->get();
        
            $statusCounts = DB::table('obf')
                ->select('status', DB::raw('COUNT(*) as count'))
                ->groupBy('status')
                ->get();
        
            return response()->json([
                'modelCounts' => $modelCounts,
                'variantCounts' => $variantCounts,
                'statusCounts' => $statusCounts,
            ]);
        }
        
    public function makedeal(Request $request){
        $id = base64_decode($request->id);               

        $data = OBF::select('obf.id','obf.sales_person_id',

        DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.final_on_road_price_after_way_off' ,'obf.customer_type','obf.customer_type_new' ,'obf.booking_date','branches.name AS branch_name' ,'branches.id AS branch_id' ,'obf.company_name' , 'obf.einvoicing_applicable','obf.gst' ,'obf.address' ,'obf.registration' ,'obf.email' ,'obf.pan_number','obf.adhar_number' ,'obf.licance_number','obf.contact_number' ,'obf.dob' ,'obf.nominee_name','obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation','products.name AS product_name','obf.product_id','products.veriant','products.is_applicable_for_mcp' ,'obf.ex_showroom_price' ,'obf.fasttag_brand_name AS fasttag_brand_name','registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance' ,'obf.insurance_id' ,'municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax' ,'accessories.name AS accessory_name' ,'obf.accessory_id','obf.extanded_warranty_id' ,'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount' ,'fasttags.brand_name AS brand_name' ,'fasttags.amount AS fasttag_amount_new' ,'fasttags.id AS fasttag_id','obf.trade_car_name', 'obf.trade_car_value', 'obf.on_road_price' ,'obf.on_road_price_word' ,'obf.on_road_price_word','obf.finance_id' ,'finance.name AS finance_name' ,'finance_branch.name AS finance_branch_name' ,'lead.name AS lead_name','obf.lead_id' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.status' ,'obf.created_by' ,'obf.updated_by','obf.created_at' ,'obf.updated_at','allocation.tentetive_delivery_date','Team_master.team_name','obf.other_accesssories_prise',

        'obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.temporary_number','obf_rto.final_amount','obf_rto.vehicle_number','obf_rto.status as rto_status',

        'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.pricelist_id','obf.registration_tax_id','obf.rto_custom_handling_charges','obf.municipal_tax_id','obf.municipal_tax_applicable','obf.tcs_tax_id','obf.nominee_dob', 'obf.convinience_program',

        'obf.step1_remarks','obf.step3_remarks','obf.step4_remarks','obf.step5_remarks','obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image','obf.other_details_1','obf.other_details_2','obf.priclist_detail','obf.inventory_id',

        'obf_finance.repo_rate','obf_finance.net_disbusment','obf_finance.loan_amount','obf_finance.processing_fee','obf_finance.finance_discount','obf_finance.payout','obf_finance.pay_booster','obf_finance.finance_required','obf.sub_lead_id','obf.rsa_master_obf',

        'car_model.name AS car_model_name','car_varient.name AS car_varient_name','interiorcolor.name AS interiorcolor_name','exteriorcolor.name AS exteriorcolor_name','inventory.key_number','inventory.engine_number','inventory.chassis_number','inventory.vin_number', 'obf_insurance.company_name AS insurance_company_name','obf_insurance.ncb_amount','obf.offer_ib_amount','obf.offer_kin_amount','obf.offer_amount','inventory.purchase_price','inventory.aging_days','inventory.remark',
        
        'make_deal.obf_id','make_deal.remark','make_deal.purchase_gst_tax_deal','make_deal.final_deal_amt','make_deal.deal_amt','make_deal.gst_tax_deal','make_deal.cess_tax_deal','make_deal.tcs_tax_deal','make_deal.municipal_tax_deal','make_deal.rto_deal','make_deal.insurance_deal','make_deal.created_by','pricelist_master.rto_custome_handling_charges','mcp.id as mcp_id','mcp.name as mcp_name','mcp.amount as mcp_amount','rsa.id as rsa_id','rsa.name as rsa_name','rsa.amount as rsa_amount','rsa.rsa_ccs as rsa_type','ccs.id as ccs_id','ccs.name as ccs_name','ccs.amount as ccs_amount','ccs.rsa_ccs as ccs_type','obf.rto_custom_handling_charges','make_deal.rto_cutom_handling_charges_deal','obf.municipal_tax_type','obf.municipal_custom_handling_charges','make_deal.municipal_custom_handling_charges_deal')

        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
        ->leftjoin('products', 'obf.product_id', 'products.id')
        ->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')
        ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
        ->leftjoin('taxes AS municipal_tax' ,'obf.municipal_tax_id' ,'municipal_tax.id')
        ->leftjoin('taxes AS tcs_tax' ,'obf.tcs_tax_id' ,'tcs_tax.id')
        ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.id')
        ->leftjoin('allocation' ,'obf.id' ,'allocation.obf_id')
        ->leftjoin('accessories' ,'obf.accessory_id' ,'accessories.id')
        ->leftjoin('extand_warranties' ,'obf.extanded_warranty_id' ,'extand_warranties.id')
        ->leftjoin('finance' ,'obf.finance_id' ,'finance.id')
        ->leftjoin('branches AS finance_branch' ,'obf.finance_branch_id' ,'finance_branch.id')
        ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
        ->leftjoin('obf_insurance' ,'obf.id' ,'obf_insurance.obf_id')
        ->leftjoin('obf_rto' ,'obf.id' ,'obf_rto.obf_id')
        ->leftjoin('obf_fasttag' ,'obf.id' ,'obf_fasttag.obf_id')
        ->leftjoin('obf_finance' ,'obf.id' ,'obf_finance.obf_id')
        ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
        ->leftjoin('Team_master','Team_master.id','users.team_name')
        ->leftjoin('make_deal','obf.id','make_deal.obf_id')
        ->leftjoin('pricelist_master', 'obf.pricelist_id', 'pricelist_master.id')
        ->leftjoin('mcp','obf.convinience_program','mcp.id')
        ->leftjoin('rsa','obf.rsa_master_obf','rsa.id')
        ->leftjoin('rsa as ccs','obf.ccs_master_obf','ccs.id')
        ->leftjoin('fasttags' ,'obf.fasttag_brand_name' ,'fasttags.id')   
        ->where(['obf.id' => $id])->first(); 
        
        $branch = Branch::select('start_value1', 'end_value1', 'tax_percentage1', 'start_value2', 'end_value2', 'tax_percentage2')->where(['status' => 'active','id' => $data->branch_id])->first();
       
        $price_list_name = DB::table('pricelist_master')->select('basic','price_list_name','gst_percentage','gst_amount','cess_percentage','cess_amount')->where('id',  $data->pricelist_id)->first();

        $rto_data = DB::table('rto_master')->select('rto_type', 'rto_tax_individual', 'rto_tax_company', 'totali_individual_charges','totalcharges')->Where('rto_type', 'like', $data->customer_type . '%')->orderBy('id', 'DESC')->first();

        $accessory_sum = 0;

        if(!empty($data->accessory_id) && $data->accessory_id != NULL && $data->accessory_id != ''){
            $accessory_id_arr = explode(' ,', $data->accessory_id);
            if(!empty($accessory_id_arr)){
                $accessory_sum = Accessory::whereIn('id', $accessory_id_arr)->sum('price');           
            }
        }

        $user = auth()->user();

        $user_role = $user->getRoleNames(); 

        return view('obf.make-deal')->with(['data' =>$data, 'branch' => $branch, 'price_list_name'=>$price_list_name, 'rto_data'=>$rto_data, 'accessory_sum' => $accessory_sum, 'user_role'=> $user_role[0], 'user'=>$user]);
    }

    public function makedealinsert(Request $request){
        $data = [
            'obf_id' => $request->id,
            'purchase_gst_tax_deal' => $request->purchase_gst_tax_deal,
            'final_deal_amt' => $request->final_deal_amt,
            'deal_amt' => $request->ex_showroom_price_deal,
            'gst_tax_deal' => $request->gst_tax_deal,
            'cess_tax_deal' => $request->cess_tax_deal,
            'tcs_tax_deal' => $request->tcs_tax_deal,
            'municipal_tax_deal' => $request->municipal_tax_deal,
            'municipal_custom_handling_charges_deal' => $request->municipal_custom_handling_charges_deal, 
            'rto_deal' => $request->rto_deal,
            'rto_cutom_handling_charges_deal' => $request->rto_custom_handling_charges_deal,
            'insurance_deal' => $request->insurance_deal,
            'remark' => $request->remark,
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
            'updated_at' => date('Y-m-d H:i:s'),
        ];
            
        MakeDeal::where('obf_id', $data['obf_id'])->delete();
        $newEntry = MakeDeal::create($data);
        
        $make_deal_crud = [
            'module_nm' => 'make_deal_create',
            'module_id' => $request->id,
            'status' => 'make_deal_create',
            'remark' => 'Make Deal Create',
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => auth()->user()->id,
        ];
        \DB::table('logs')->insert($make_deal_crud);
        
        $obf = DB::table('obf')->where('id',$data['obf_id'])->update(['status'=>'deal_generated']);
        $order = DB::table('orders')->where('obf_id',$data['obf_id'])->update(['status'=>'deal_generated']);
        
        // Fetch order to get VIN number
        $order = DB::table('orders')->where('obf_id', $data['obf_id'])->first();

        if ($newEntry) {
            return response()->json(['code' => 200]);
        } else {
            return response()->json(['code' => 201]);
        }
    }
    
    public function cancel_obf(Request $request){
        $obf_id = base64_decode($request->record_id);
        $status = $request->status;
        if($status === 'delete'){
            $crud = [
                'cancel_remark' => $request->cancel_remark,
                'status' => 'delete', 
                'approval_status' => 'delete'
            ];
            
            $crud_logs = [
                'module_nm' => 'obf',
                'module_id' => $obf_id,
                'status' => 'delete',
                'remark' => '',
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
            ];
            
        } else {
            $crud = [
                'cancel_reason' => $request->cancel_reason,
                'cancel_remark' => $request->cancel_remark,
                'status' => 'cancel',
            ];
            
            $crud_logs = [
                'module_nm' => 'obf',
                'module_id' => $obf_id,
                'status' => 'cancel',
                'remark' => $request->cancel_remark,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
            ];
        }
        
        $updated = DB::table('obf')->where('id', $obf_id)->update($crud);
        \DB::table('logs')->insert($crud_logs);
        
        if ($updated) {
            return response()->json(['success' => true, 'message' => 'Record updated successfully.']);
        } else {
            return response()->json(['success' => false, 'message' => 'Failed to update record.'], 500);
        }
    }
    
    public function undertaking(Request $request) 
    {
        $obf_id = base64_decode($request->id);



        $data = OBF::select(
            'obf.*',
            'branches.name AS branch_name',
            'branches.id AS branch_id',
            'products.name AS product_name',
            'products.veriant',
            'car_model.name AS car_model_name',
            'car_varient.name AS car_varient_name',
            'interiorcolor.name AS interiorcolor_name',
            'exteriorcolor.name AS exteriorcolor_name',
            'inventory.key_number',
            'inventory.engine_number',
            'inventory.chassis_number',
            'inventory.vin_number', 
            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
            'Team_master.team_name',
        )   

        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
        ->leftjoin('products', 'obf.product_id', 'products.id')
        ->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')
        ->leftjoin('fule_type', 'fule_type.id', 'obf.fuel_type')
        ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
        ->leftjoin('Team_master','Team_master.id','users.team_name')
        ->where(['obf.id' => $obf_id])
        ->first();
        
        return view('undertaking.undertakingpage',compact('data'));
    }
    
    public function liquidationprocess(Request $request)
    {
        try {
            $obf_id = base64_decode($request->encoded_id);
    
            $exists = DB::table('obf')->where('id', $obf_id)->exists();
            if (!$exists) {
                return response()->json(['success' => false, 'message' => 'Record not found.']);
            }
    
            $crud = [
                'refund_remark' => $request->refund_remark,
                'refund_amount' => $request->refund_amount,
                'status'        => 'refund_process',
                'updated_at'    => now(), 
            ];
    
            $updated = DB::table('obf')->where('id', $obf_id)->update($crud);
            
            $refund_creator = User::select('id' , DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active','id'=>auth()->user()->id])->first();

            $liquidation_curd = [
                'obf_id' => $obf_id,
                'liquidation_amount' => $request->refund_amount,
                'approval_status' => 'pending',
                'approval_remark' => "Refund Process By {$refund_creator->sales_person_name}",
                'liquidation_type' => $request->liquidation_type,
                'refund_by' => auth()->user()->id,
                'created_by' => auth()->user()->id,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s'),    
            ];
            
            DB::table('liquidation')->insert($liquidation_curd);
            
            // DB::table('cash_receipt')->where('obf_id',$obf_id)->update(['refund_status' => 'cancel']);
            
            // $allocation_exists = DB::table('obf')->where('id', $obf_id)->whereNotNull('inventory_id')->exists();

            // if ($allocation_exists) {
            //     $obf_table_id = DB::table('obf')->where('id', $obf_id)->first();
            //     $inventory_allocation = DB::table('inventory')->where('id', $obf_table_id->inventory_id)->where('status','allocated')->exists();
            //     if ($inventory_allocation) {
            //         DB::table('inventory')->where('id', $obf_table_id->inventory_id)->update(['status'=>'active','allocation_count'=> 0]);
            //     }
            // }
            
            // $invoice_exists = DB::table('orders')->where('obf_id',$obf_id)->exists();
            // if($invoice_exists){
            //     $invoice_cancallation = DB::table('orders')->where('obf_id',$obf_id)->update(['status' => 'refund_process']);
            // }
            
            $crud_logs = [
                'module_nm'  => 'obf',
                'module_id'  => $obf_id,
                'status'     => 'refund_process',
                'remark'     => $request->remark,
                'created_at' => now(),
                'created_by' => auth()->user()->id,
            ];
    
            DB::table('logs')->insert($crud_logs);
    
            return response()->json(['success' => true, 'message' => 'Liquidation processed successfully.']);
    
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ], 500);
        }
    }
    
    public function obf_deletation(Request $request){
        return view('obf.deletation_process');
    }
    
    public function obf_deletation_process(Request $request)
    {
        $id = $request->id;
        $obf_data = OBF::find($id);
        
        if (!$obf_data) {
            return response()->json(['code' => 201]);
        }
    
        // Tables to delete by obf_id
        $tablesToDelete = [
            'cash_receipt',
            'orders',
            'exchange_purchase',
            'obf_finance',
            'ew_process_dms',
            'mcp_process_dms',
            'rsa_process_dms',
            'obf_fasttag',
            'obf_municiple_tax',
            'yodepartment_process_dms',
            'accesories_process_dms',
            'obf_rto',
            'obf_insurance',
            'make_deal',
        ];
    
        foreach ($tablesToDelete as $table) {
            DB::table($table)->where('obf_id', $id)->delete();
        }
    
        // Update inventory status if applicable
        if (!empty($obf_data->inventory_id)) {
            DB::table('inventory')
                ->where('id', $obf_data->inventory_id)
                ->update(['allocation_count' => '0', 'status' => 'active']);
        }
    
        // Delete KYC files if exist
        $kycFiles = [
            $obf_data->pan_image,
            $obf_data->adhar_image,
            $obf_data->aadhar_pan_image,
            $obf_data->licance_image,
            $obf_data->other_documents,
            $obf_data->passport_document,
            $obf_data->gst_certificate,
        ];
    
        foreach ($kycFiles as $file) {
            if (!empty($file)) {
                $filePath = public_path('uploads/kyc/' . $file);
                if (file_exists($filePath)) {
                    @unlink($filePath);
                }
            }
        }
    
        // Finally delete the OBF record
        $obf_data->delete();
    
        return response()->json(['code' => 200]);
    }
    
    public function obf_accessory_form(Request $request){
        $obf_id = base64_decode($request->id);

        $data = OBF::select(
            'obf.*',
            'branches.name AS branch_name',
            'branches.id AS branch_id',
            'products.name AS product_name',
            'products.veriant',
            'car_model.name AS car_model_name',
            'car_varient.name AS car_varient_name',
            'interiorcolor.name AS interiorcolor_name',
            'exteriorcolor.name AS exteriorcolor_name',
            'inventory.key_number',
            'inventory.engine_number',
            'inventory.chassis_number',
            'inventory.vin_number', 
            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
            'Team_master.team_name',
            'district.name as district_name',
            'orders.invoice_no',
        )   

        ->leftjoin('users' ,'obf.sales_person_id' ,'users.id')
        ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
        ->leftjoin('products', 'obf.product_id', 'products.id')
        ->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')
        ->leftjoin('fule_type', 'fule_type.id', 'obf.fuel_type')
        ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
        ->leftjoin('Team_master','Team_master.id','users.team_name')
        ->leftjoin('district','district.id','obf.district_id')
        ->leftjoin('orders','orders.obf_id','obf.id')
        ->where(['obf.id' => $obf_id])
        ->first();
        
        $images = DB::table('global_configuration')->select('gatepass_logo1','gatepass_logo2')->first();
        
        return view('obf.accessory_form',compact('data','images'));
        
    }
    
    public function discount_process_fetch(Request $request)
    {
        try {
    
            $obf_id = base64_decode($request->id);
    
            $obf_data = OBF::select(
                'obf.*',
                'car_model.id as model_id',
                'car_model.name as model',
                'fule_type.id as fuel_id',
                'fule_type.title as fuel_type_name',
                'car_varient.id as varient_id',
                'car_varient.name as varient',
                'exteriorcolor.name AS exteriorcolor_name',
                DB::raw("(SELECT GROUP_CONCAT(title SEPARATOR ', ')
                          FROM offer 
                          WHERE FIND_IN_SET(offer.id, obf.offer_kin)
                         ) as kin_offer_titles"),
        
                DB::raw("(SELECT GROUP_CONCAT(amount SEPARATOR ', ')
                          FROM offer 
                          WHERE FIND_IN_SET(offer.id, obf.offer_kin)
                         ) as kin_offer_amounts"),
        
                DB::raw("(SELECT GROUP_CONCAT(title SEPARATOR ', ')
                          FROM offer 
                          WHERE FIND_IN_SET(offer.id, obf.offer_ib)
                         ) as ib_offer_titles"),
        
                DB::raw("(SELECT GROUP_CONCAT(amount SEPARATOR ', ')
                          FROM offer 
                          WHERE FIND_IN_SET(offer.id, obf.offer_ib)
                         ) as ib_offer_amounts"),
                         
                DB::raw("(SELECT GROUP_CONCAT(offer_type SEPARATOR ', ')
                          FROM offer 
                          WHERE FIND_IN_SET(offer.id, obf.offer_kin)
                         ) as kin_offer_types"),
                
                DB::raw("(SELECT GROUP_CONCAT(offer_type SEPARATOR ', ')
                          FROM offer 
                          WHERE FIND_IN_SET(offer.id, obf.offer_ib)
                         ) as ib_offer_types") 
            )
            ->leftJoin('products', 'obf.product_id', 'products.id')
            ->leftJoin('car_model', 'car_model.id', 'products.car_model')
            ->leftJoin('car_varient', 'car_varient.id', 'products.veriant')
            ->leftJoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
            ->leftJoin('fule_type', 'fule_type.id', 'car_varient.fule_type')
            ->where('obf.id', $obf_id)
            ->first();
             
            $today = Carbon::today()->toDateString();
    
            $discount = Discount::where('car_model_id', $obf_data->model_id)
                ->where('fuel_id', $obf_data->fuel_id)
                ->whereRaw('FIND_IN_SET(?, car_varient_id)', [$obf_data->varient_id])
                ->where('discount.discount_year',$obf_data->discount_year)
                ->where('status', 'active')
                ->whereDate('start_date', '<=', $today)
                ->whereDate('end_date', '>=', $today)
                ->latest()
                ->first();

            $roleDiscountMap = [
                'KEC'                     => 'kec_discount',
                'Team leader'             => 'tl_discount',
                'Sales Manager'           => 'sm_discount',
                'General Manager - Sales' => 'gm_discount',
                'Business Head'           => 'bh_discount',
                'CEO'                     => 'ceo_discount',
                'Managing director'       => 'md_discount',
            ];
    
            $userRole = trim(auth()->user()->roles()->pluck('name')->first());
    
            $discountColumn = $roleDiscountMap[$userRole] ?? null;
    
            $discountValue = ($discount && $discountColumn)
                ? (int) $discount->{$discountColumn}
                : 0;
    
            return response()->json([
                'status'        => true,
                'data'          => $obf_data,
                'discount'      => $discountValue,
                'max_discount'  => $discountValue, // ðŸ‘ˆ for JS limit
                'discount_type' => $discountColumn,
                'user_role'     => $userRole,
            ]);
    
        } catch (\Exception $e) {
            return response()->json([
                'status'  => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    
    public function discount_process(Request $request)
    {
        try {
            $obfId = base64_decode($request->encoded_id);
            $userRole = auth()->user()->roles()->pluck('name')->first();
    
            $roleConfig = [
                'KEC'                     => ['flag' => 1, 'column' => 'way_off'],
                'Team leader'             => ['flag' => 2, 'column' => 'tl_discount'],
                'Sales Manager'           => ['flag' => 3, 'column' => 'sm_discount'],
                'General Manager - Sales' => ['flag' => 4, 'column' => 'gm_discount'],
                'Business Head'           => ['flag' => 5, 'column' => 'bh_discount'],
                'CEO'                     => ['flag' => 6, 'column' => 'ceo_discount'],
                'Managing director'       => ['flag' => 7, 'column' => 'md_discount'],
            ];
    
            if (!isset($roleConfig[$userRole])) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid role'
                ]);
            }
    
            $config = $roleConfig[$userRole];
    
            $obf = OBF::findOrFail($obfId);
    
            // store discount in correct column
            $obf->{$config['column']} = $request->discount_value;
    
            // update final price
            $obf->final_on_road_price_after_way_off = $request->final_price;
    
            // Need More Discount button
            if ($request->action === 'need_more') {
                $obf->discount_flag = $config['flag'] + 1;
            }
            
            $approvalStatus = [
                2 => 'KEC Discount Approved',
                3 => 'TL Discount Approved',
                4 => 'SM Discount Approved',
                5 => 'GM Discount Approved',
                6 => 'BH Discount Approved',
                7 => 'CEO Discount Approved',
                8 => 'MD Discount Approved',
            ];
    
            if (!empty($obf->discount_flag) && isset($approvalStatus[$obf->discount_flag])) {
                $obf->discount_approval_status = $approvalStatus[$obf->discount_flag];
            }
    
            // Submit button â†’ DO NOT change discount_flag
            $obf->save();
            
            $crud_logs = [
                'module_nm'  => 'obf_discount',
                'module_id'  => $obfId,
                'status'     => '',
                'remark'     => 'Given Discount â‚¹ ' . number_format($request->discount_value, 0, '.', ','),
                'created_at' => now(),
                'created_by' => auth()->user()->id,
            ];
    
            DB::table('logs')->insert($crud_logs);
    
            return response()->json([
                'success' => true,
                'message' => 'Discount processed successfully'
            ]);
    
        } catch (\Exception $e) {
            dd($e);
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
    
    
    public function obf_discount_index(Request $request){
            
        $permission_get = '';
        
        $data_v = auth()->user()->roles->pluck('data_permission');
        if (!empty($data_v)) {
            $permission_get = $data_v[0];
        }
        
        // Pre-fetch dropdown data (these do not need optimization):
        $customer_name = OBF::select('id', 'customer_name')->get();
        $kec_name = User::select(DB::raw("CONCAT(first_name,' ',last_name) AS kec_name"), '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();
        $date = OBF::select('booking_date', 'id')->get();
        $cash_status = CashReceipt::select('cash_receipt.status')->join('obf', 'obf.id', '=', 'cash_receipt.obf_id')->get();
        $cash_total = CashReceipt::select('amount', 'receipt_type', 'obf.id as obf_id')
            ->join('obf', 'obf.id', '=', 'cash_receipt.obf_id')
            ->whereIn('receipt_type', ['booking_receipt', 'downpayment_receipt'])
            ->get();
        $cancel_reason = CancellationReason::select('name', 'id')->where('status', 'active')->get();
        
        // Filters
        $cust_name = $request->client;
        $kec = $request->kec;
        $products = $request->product;
        $road_price = $request->road_price;
        $variants = $request->varient;
        $locations = $request->location;
        $startdates = $request->start_date;
        $enddates = $request->end_date;
        
        if ($request->ajax()) {
            $cashSummary = DB::table('cash_receipt')
                ->select(
                    'obf_id',
                    DB::raw('SUM(CASE WHEN receipt_type="booking_receipt" AND status!="rejected" THEN amount ELSE 0 END) AS booking_amount'),
                    DB::raw('SUM(CASE WHEN receipt_type="downpayment_receipt" AND status!="rejected" THEN amount ELSE 0 END) AS dp_amount'),
                    DB::raw('SUM(CASE WHEN receipt_type="disbusment_receipt" AND status!="rejected" THEN amount ELSE 0 END) AS net_disbusment'),
                    DB::raw('SUM(CASE WHEN receipt_type="access_sort_receipt" AND status!="rejected" THEN amount ELSE 0 END) AS access_sort_amount'),
                    DB::raw('SUM(CASE WHEN status!="rejected" THEN amount ELSE 0 END) AS received_amount')
                )
                ->groupBy('obf_id');
            
            // Aggregate exchange purchase
            $exchangeSummary = DB::table('exchange_purchase')
                ->select('obf_id', DB::raw('total_exchange_amount'))
                ->whereIn('status', ['active','sell']);
            
            $data = OBF::select(
                'obf.id', 
                'obf.customer_name', 
                'obf.ship_to_customer_name',
                'obf.booking_date',
                'car_model.name AS product',
                'obf.status',
                'obf.ew_status',
                'obf.mcp_status',
                'obf.rsa_status',
                'obf.yodepartment_status',
                'obf.rto_status',
                'obf.insurance_status',
                'obf.accesories_status',
                'obf.fasttag_status',  
                'obf.municipal_tax_status', 
                'obf.on_road_price',
                DB::raw("CONCAT(car_varient.name, ' - ', tex_master.gst, ' - ',tex_master.compensation_cess,  ' %') AS car_varient_name"),
                'branches.name as branch_name',
                'cash_receipt.status as receipt_status',
                'orders.status as order_status',
                'orders.invoice_no as order_invoice_no',
                DB::raw("CASE WHEN orders.invoice_no IS NOT NULL AND orders.invoice_date IS NOT NULL THEN orders.invoice_no ELSE '---' END as invoice_no"),
                DB::raw("COALESCE(MAX(orders.invoice_date), '--') as invoice_date"),
                DB::raw('(SELECT vin_number FROM inventory WHERE inventory.status != "inactive" AND inventory.status != "deleted" AND inventory.status != "sold" AND inventory.id = obf.inventory_id) as vin_number'),
                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                DB::raw('cash_summary.received_amount'),
                'obf.gst',
                'exteriorcolor.name as exterior_color',
                'obf.address',
                'obf.registration',
                'obf_finance.loan_amount',
                'obf_finance.finance_discount',
                DB::raw('cash_summary.net_disbusment'),
                'obf.way_off',
                'obf.foc_accessories',
                'obf.offer_ib_amount',
                'obf.offer_kin_amount',
                'obf.approval_status',
                DB::raw('cash_summary.booking_amount'),
                DB::raw('cash_summary.dp_amount'),
                DB::raw('cash_summary.access_sort_amount'),
                'Team_master.team_name',
                DB::raw('(exchange.total_exchange_amount) as total_exchange_amount'),
                DB::raw("(
                    COALESCE(cash_summary.booking_amount, 0) +
                    COALESCE(cash_summary.dp_amount, 0) +
                    COALESCE(cash_summary.net_disbusment, 0) +
                    COALESCE(exchange.total_exchange_amount, 0)
                ) as final_total"),
                DB::raw("( obf.on_road_price - (COALESCE(obf_finance.finance_discount, 0) + COALESCE(obf.way_off, 0) + COALESCE(obf.foc_accessories, 0) + COALESCE(obf.offer_ib_amount, 0) + COALESCE(obf.offer_kin_amount, 0))) as net_total"),
                DB::raw("(
                    obf.on_road_price - 
                    (
                        COALESCE(cash_summary.booking_amount, 0) + 
                        COALESCE(cash_summary.dp_amount, 0) + 
                        COALESCE(cash_summary.net_disbusment, 0) + 
                        COALESCE(exchange.total_exchange_amount, 0) + 
                        COALESCE(obf_finance.finance_discount, 0) + 
                        COALESCE(obf.way_off, 0) + 
                        COALESCE(obf.tl_discount, 0) + 
                        COALESCE(obf.sm_discount, 0) + 
                        COALESCE(obf.gm_discount, 0) + 
                        COALESCE(obf.bh_discount, 0) + 
                        COALESCE(obf.ceo_discount, 0) + 
                        COALESCE(obf.md_discount, 0) + 
                        COALESCE(obf.foc_accessories, 0) + 
                        COALESCE(obf.offer_ib_amount, 0) + 
                        COALESCE(obf.offer_kin_amount, 0)
                    ) + 
                    CASE 
                        WHEN (
                            (
                                COALESCE(cash_summary.booking_amount, 0) + 
                                COALESCE(cash_summary.dp_amount, 0) + 
                                COALESCE(cash_summary.net_disbusment, 0) + 
                                COALESCE(exchange.total_exchange_amount, 0) + 
                                COALESCE(obf_finance.finance_discount, 0) + 
                                COALESCE(obf.way_off, 0) + 
                                COALESCE(obf.tl_discount, 0) + 
                                COALESCE(obf.sm_discount, 0) + 
                                COALESCE(obf.gm_discount, 0) + 
                                COALESCE(obf.bh_discount, 0) + 
                                COALESCE(obf.ceo_discount, 0) + 
                                COALESCE(obf.md_discount, 0) + 
                                COALESCE(obf.foc_accessories, 0) + 
                                COALESCE(obf.offer_ib_amount, 0) + 
                                COALESCE(obf.offer_kin_amount, 0)
                            ) < obf.on_road_price
                        ) 
                        THEN -COALESCE(cash_summary.access_sort_amount, 0) 
                        ELSE COALESCE(cash_summary.access_sort_amount, 0) 
                    END
                ) as due_amount
            "),
                DB::raw('(COALESCE(obf_finance.finance_discount, 0) + COALESCE(obf.way_off, 0) + COALESCE(obf.foc_accessories, 0) + COALESCE(obf.offer_ib_amount, 0) + COALESCE(obf.offer_kin_amount, 0)) AS total_finance_discount'),
                'obf.tl_discount',
                'obf.sm_discount',
                'obf.gm_discount',
                'obf.bh_discount',
                'obf.ceo_discount',
                'obf.md_discount',
            )
            ->leftjoin('products', 'obf.product_id', 'products.id')
            ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
            ->leftjoin('users','users.id','=','obf.sales_person_id')
            ->leftjoin('car_model', 'car_model.id', 'products.car_model')
            ->leftjoin('branches','branches.id','=','obf.branch_id')
            ->leftjoin('cash_receipt','cash_receipt.obf_id','=','obf.id') // required for cash_receipt.status only
            ->leftjoin('orders','orders.obf_id','=','obf.id')
            ->leftJoin('inventory','inventory.name','=','products.id')
            ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
            ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
            ->leftJoin('obf_finance','obf_finance.obf_id','=','obf.id')
            ->leftjoin('Team_master','Team_master.id','users.team_name')
            ->leftjoin('tex_master', 'car_varient.tex_master_id', '=', 'tex_master.id')
            ->leftJoinSub($cashSummary, 'cash_summary', 'cash_summary.obf_id', '=', 'obf.id')
            ->leftJoinSub($exchangeSummary, 'exchange', 'exchange.obf_id', '=', 'obf.id')
            ->where('obf.status','!=','delete');
        
            // Role-specific filters
            if (auth()->user()->roles && isset(auth()->user()->roles[0]['id'])) {
                $roleId = auth()->user()->roles[0]['id'];
        
                if (in_array($roleId, [33, 36, 37, 32])) {
                    $columns = [
                        33 => 'obf.extanded_warranty_id',
                        36 => 'obf.convinience_program',
                        37 => 'obf.rsa_master_obf',
                        32 => 'obf.accessory_id'
                    ];
                    $data = $data->groupBy('orders.obf_id')->whereIn('orders.status', ['all_payment_done', 'invoice_create'])->whereNotNull($columns[$roleId]);
                } elseif ($roleId == 22) {
                    $data = $data->groupBy('obf.id');
                } elseif ($roleId == 34) {
                    $data = $data->groupBy('obf.id')->where('obf.trade_car_value', '=', 'yes');
                } else {
                    $data = $data->groupBy('obf.id');
                }
            }
        
            // Permissions and branch restrictions
            if ($permission_get === 'ONLY_MY_DATA') {
                $data = $data->whereRaw('FIND_IN_SET(obf.created_by, "' . auth()->id() . '")');
            }
            if (!empty(auth()->user()->branch)) {
                $data = $data->whereRaw('FIND_IN_SET(obf.branch_id, "' . auth()->user()->branch . '")');
            }
            if ($permission_get === 'MY_TEAM_DATA' && auth()->user()->team_name !== null) {
                $teamIds = User::where('team_name', auth()->user()->team_name)->pluck('id');
                $data = $data->whereIn('obf.created_by', $teamIds);
            }
            
            $userRole = trim(auth()->user()->roles()->pluck('name')->first());
            
            $roleConfig = [
                'KEC'                     => ['flag' => 1, 'column' => 'way_off'],
                'Team leader'             => ['flag' => 2, 'column' => 'tl_discount'],
                'Sales Manager'           => ['flag' => 3, 'column' => 'sm_discount'],
                'General Manager - Sales' => ['flag' => 4, 'column' => 'gm_discount'],
                'Business Head'           => ['flag' => 5, 'column' => 'bh_discount'],
                'CEO'                     => ['flag' => 6, 'column' => 'ceo_discount'],
                'Managing director'       => ['flag' => 7, 'column' => 'md_discount'],
            ];
            
            if (isset($roleConfig[$userRole])) {

                $data->whereNotNull('obf.discount_flag')     // not NULL
                     ->where('obf.discount_flag', '!=', '')  // not blank
                     ->where('obf.discount_flag', $roleConfig[$userRole]['flag']);
            }
            $data->where('obf.status', '!=', 'deal_generated');
            $data->where(function($q){
                $q->where('orders.status','!=','invoice_create')
                  ->orWhereNull('orders.status');
            });
            $data->orderByDesc('obf.id');

            return Datatables::of($data)
                ->addIndexColumn()

                ->addColumn('action', function ($data) {

                    $return = '<div class="btn-group">';
                    
                    $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="' . route('obf.obf_summary', ['id' => base64_encode($data->id)]) . '" target="_blank">OBF Summary</a></li>';
                                    
                                    if (auth()->user()->can('Discount Process')){
                                        $return .= '<li><a class="dropdown-item" href="javascript:void(0);" onclick="discount_process(this);" data-id="' . base64_encode($data->id) . '" data-fetch-url="' . route("obf.discount_process_fetch", ":id") . '">Process Discount</a></li>';
                                    }

                    $return .= '</ul></div>';

                    return $return;
                })

                ->editColumn('booking_date', function($data) {
                    return (!empty($data->booking_date))
                        ? \Carbon\Carbon::parse($data->booking_date)->format('d-m-Y H:i:s')
                        : '--';
                })

                ->editColumn('final_total',function($data){

                    $book_amt = $data->booking_amount + $data->dp_amount + $data->net_disbusment + $data->total_exchange_amount;

                    return $book_amt;

                })

                ->editColumn('net_total',function($data){
                    $finance_dis = floatval($data->finance_discount) 
                                 + floatval($data->way_off) 
                                 + floatval($data->tl_discount)
                                 + floatval($data->gm_discount)
                                 + floatval($data->sm_discount)
                                 + floatval($data->bh_discount)
                                 + floatval($data->ceo_discount)
                                 + floatval($data->md_discount)
                                 + floatval($data->foc_accessories) 
                                 + floatval($data->offer_ib_amount) 
                                 + floatval($data->offer_kin_amount);
                    
                    $net_amt = floatval($data->on_road_price) - $finance_dis;
                
                    return $net_amt;
                })

                
                ->editColumn('finance_discount',function($data){

                    $finance_dis = ($data->finance_discount ?? 0) + ($data->way_off ?? 0) + ($data->tl_discount) + ($data->gm_discount) + ($data->sm_discount) + ($data->bh_discount) + ($data->ceo_discount) + ($data->md_discount) + ($data->foc_accessories ?? 0) + ($data->offer_ib_amount ?? 0) + ($data->offer_kin_amount ?? 0);
                    
                    return $finance_dis;
                })
                
                ->editColumn('access_sort_amount',function($data){
                    return (isset($data->access_sort_amount) && !empty($data->access_sort_amount)) ? $data->access_sort_amount : '0';
                })
                
                ->editColumn('due_amount', function($data) {

                    // Safely cast all values to float
                    $finance_dis = floatval($data->finance_discount) 
                                 + floatval($data->way_off)
                                 + floatval($data->tl_discount)
                                 + floatval($data->gm_discount)
                                 + floatval($data->sm_discount)
                                 + floatval($data->bh_discount)
                                 + floatval($data->ceo_discount)
                                 + floatval($data->md_discount)
                                 + floatval($data->foc_accessories) 
                                 + floatval($data->offer_ib_amount) 
                                 + floatval($data->offer_kin_amount);
                
                    $book_amt = floatval($data->booking_amount) 
                              + floatval($data->dp_amount) 
                              + floatval($data->net_disbusment) 
                              + floatval($data->total_exchange_amount);
                
                    $total_amt = $book_amt + $finance_dis;
                    $on_road_amount = floatval($data->on_road_price);
                
                    $due_amount = $on_road_amount - $total_amt;
                
                    if ($total_amt < $on_road_amount) {
                        $due_amount -= floatval($data->access_sort_amount);
                    } else {
                        $due_amount += floatval($data->access_sort_amount);
                    }
                
                    return $due_amount;
                
                })

                
                ->editColumn('status', function ($data) {

                    if($data->receipt_status == 'accepted' && $data->status == 'account_accepted' && $data->order_status == 'waiting'){
                
                        return '<span class="badge badge-pill badge-success">Order'. '-'.$data->order_status .'</span>';
                
                    }elseif($data->status == 'account_accepted' && $data->order_status == 'finance_apporve'){
                
                        return '<span class="badge badge-pill badge-success">Finance Apporved</span>';
                
                    }elseif($data->status == 'account_accepted' && $data->order_status == 'disbursement'){
                
                        return '<span class="badge badge-pill badge-success">Disbursement</span>';
                
                    }elseif($data->status == 'account_accepted' && $data->order_status == 'all_payment_done'){
                
                        return '<span class="badge badge-pill badge-success">All Payment Done</span>';
                
                    }elseif($data->order_status == 'pdi_approve'){
                
                        return '<span class="badge badge-pill badge-success">PDI Approve</span>';
                
                    }elseif($data->order_status == 'pdi_reject'){
                
                        return '<span class="badge badge-pill badge-danger">PDI Reject</span>';
                
                    }elseif($data->order_status == 'ready_to_deliver'){
                
                        return '<span class="badge badge-pill badge-success">Ready to Deliver</span>';
                
                    }elseif($data->order_status == 'delivered'){
                
                        return '<span class="badge badge-pill badge-success">Delivered</span>';
                
                    }elseif($data->order_status == 'invoice_create'){
                
                        return '<span class="badge badge-pill badge-success">Invoice Created</span>';
                
                    }elseif($data->order_status == 'invoice_cancel'){
                
                        return '<span class="badge badge-pill badge-danger">Invoice Cancelled</span>';
                
                    }elseif($data->receipt_status == 'accepted' && $data->status == 'account_accepted'){
                
                        return '<span class="badge badge-pill badge-success">Receipt Created</span>';
                
                    }elseif ($data->status == 'accepted') {
                
                        return '<span class="badge badge-pill badge-success">Active</span>';
                
                    }elseif ($data->status == 'pending') {
                
                        return '-';
                
                    }elseif ($data->status == 'deleted') {
                
                        return '<span class="badge badge-pill badge-danger">Deleted</span>';
                
                    }elseif ($data->status == 'account_rejected') {
                
                        return '<span class="badge badge-pill badge-danger">Account Rejected</span>';
                
                    }elseif ($data->status == 'rejected') {
                
                        return '<span class="badge badge-pill badge-danger">Rejected</span>';
                
                    }elseif ($data->status == 'account_accepted') {
                
                        return '<span class="badge badge-pill badge-success">Account Accepted</span>';
                
                    }elseif($data->status == 'completed'){
                
                        return '<span class="badge badge-pill badge-success">Completed</span>'; 
                
                    }elseif ($data->status == 'cancel') {
                
                        return '<span class="badge badge-pill badge-danger">Cancel</span>';
                
                    }elseif ($data->status == 'deal_generated') {
                
                        return '<span class="badge badge-pill badge-success">Deal Generated</span>';
                
                    }elseif ($data->status == 'delete') {
                
                        return '<span class="badge badge-pill badge-danger">Deleted</span>';
                
                    }elseif ($data->status == 'refund_process') {
                
                        return '<span class="badge badge-pill badge-danger">Refund Process</span>';
                
                    }else{
                
                        return '-';
                
                    }                            
                
                })
                
                ->editColumn('approval_status', function ($data) {

                    if ($data->approval_status == 'pending') {

                        return '<span class="badge badge-pill badge-warning">Pending From TL</span>';

                    }elseif ($data->approval_status == 'obf_tl_rejected') {

                        return '<span class="badge badge-pill badge-danger">OBF Rejected By TL</span>';

                    }elseif ($data->approval_status == 'obf_sm_rejected') {

                        return '<span class="badge badge-pill badge-danger">OBF Rejected By SM</span>';

                    }elseif ($data->approval_status == 'obf_gm_rejected') {

                        return '<span class="badge badge-pill badge-danger">OBF Rejected By GM</span>';

                    }elseif ($data->approval_status == 'obf_accountant_rejected') {

                        return '<span class="badge badge-pill badge-danger">OBF Rejected By Accountant</span>';

                    }elseif ($data->approval_status == 'obf_tl_accepted') {

                        return '<span class="badge badge-pill badge-success">Obf Accepted By TL</span>';

                    }elseif ($data->approval_status == 'obf_sm_accepted') {

                        return '<span class="badge badge-pill badge-success">Obf Accepted By SM</span>';

                    }elseif ($data->approval_status == 'obf_gm_accepted') {

                        return '<span class="badge badge-pill badge-success">Obf Accepted By GM</span>';

                    }elseif ($data->approval_status == 'obf_accountant_accepted') {

                        return '<span class="badge badge-pill badge-success">Obf Accepted By Accountant</span>';

                    }elseif ($data->approval_status == 'delete') {

                        return '<span class="badge badge-pill badge-danger">Deleted</span>';

                    }else{

                        return '-';

                    }                            

                })
                
                ->rawColumns(['action' ,'status','approval_status'])

                ->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('branch_name',false)) {
                        $query->where('branches.name', "like", "%".request()->get("branch_name")."%");
                    }
                    if (request()->get('customer_name',false)) {
                        $query->where('obf.customer_name', "like", "%".request()->get("customer_name")."%");
                    }
                    if (request()->get('gst',false)) {
                        $query->where('obf.gst', "like", "%".request()->get("gst")."%");
                    }
                    if (request()->get('ship_to_customer_name',false)) {
                        $query->where('obf.ship_to_customer_name', "like", "%".request()->get("ship_to_customer_name")."%");
                    }
                    if (request()->get('team_name',false)) {
                        $query->where('Team_master.team_name', "like", "%".request()->get("team_name")."%");
                    }
                    if (request()->get('sales_person_name',false)) {
                        $salesPersonName = request()->get('sales_person_name');
                        $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%{$salesPersonName}%"]);
                    }
                    if (request()->get('product',false)) {
                        $query->where('car_model.name', "like", "%".request()->get("product")."%");
                    }
                    if (request()->get('car_varient_name',false)) {
                        $query->where('car_varient.name', "like", "%".request()->get("car_varient_name")."%");
                    }
                    if (request()->get('exterior_color',false)) {
                        $query->where('exteriorcolor.name', "like", "%".request()->get("exterior_color")."%");
                    }
                    if (request()->get('vin_number',false)) {
                        $query->where('inventory.vin_number', "like", "%".request()->get("vin_number")."%");
                    }
                    if (request()->get('on_road_price',false)) {
                        $query->where('obf.on_road_price', "like", "%".request()->get("on_road_price")."%");
                    }
                    if (request()->get('booking_amount', false)) {
                        $bookingAmount = request()->get('booking_amount');
                        $query->having('booking_amount', 'LIKE', "%{$bookingAmount}%");
                    }
                    if (request()->get('dp_amount', false)) {
                        $dpAmount = request()->get("dp_amount");
                        $query->having('dp_amount', 'LIKE', "%{$dpAmount}%");
                    }
                    if (request()->get('loan_amount',false)) {
                        $query->where('obf_finance.loan_amount', "like", "%".request()->get("loan_amount")."%");
                    }
                    if (request()->get('net_disbusment',false)) {
                        $query->where('obf_finance.net_disbusment', "like", "%".request()->get("net_disbusment")."%");
                    }
                    if (request()->get('total_exchange_amount',false)) {
                        $query->where('exchange_purchase.total_exchange_amount', "like", "%".request()->get("total_exchange_amount")."%");
                    }
                    if ($finalTotal = request()->get('final_total')) {
                        $query->havingRaw("final_total LIKE ?", ["%{$finalTotal}%"]);
                    }
                    if ($discount = request()->get('finance_discount')) {
                        $query->havingRaw('CAST(total_finance_discount AS CHAR) LIKE ?', ["%{$discount}%"]);
                    }

                    if ($netTotal = request()->get('net_total')) {
                        $query->havingRaw("net_total LIKE ?", ["%{$netTotal}%"]);
                    }
                    if ($accessSort = request()->get('access_sort_amount')) {
                        $query->havingRaw("access_sort_amount LIKE ?", ["%{$accessSort}%"]);
                    }
                    if ($dueAmount = request()->get('due_amount')) {
                        $query->havingRaw("due_amount LIKE ?", ["%{$dueAmount}%"]);
                    }
                    if (request()->get('status',false)) {
                        $query->where('obf.status', "like", "%".request()->get("status")."%");
                    }
                    if (request()->get('approval_status',false)) {
                        $query->where('obf.approval_status', "like", "%".request()->get("approval_status")."%");
                    }
                    if (request()->get('invoice_no',false)) {
                        $query->where('orders.invoice_no', "like", "%".request()->get("invoice_no")."%");
                    }
                    if (request()->get('invoice_date',false)) {
                        $query->where('orders.invoice_date', "like", "%".request()->get("invoice_date")."%");
                    }
                })   

                ->make(true);
            }

        

            $role = auth()->user()->roles;

            $roleName = "";

            if ($role) {

                $roleName = $role[0]->name;

            }

        return view('obf_discount.index')->with(['customer_name'=>$customer_name,'kec_name'=>$kec_name,'product'=>$product,'price'=>$price,'varient'=>$varient,'branch'=>$branch,'date'=>$date,'roleName'=>$roleName,'cancel_reason'=>$cancel_reason,'cash_total'=>$cash_total]);

    }

}