<?php



namespace App\Http\Controllers;



use App\Models\Carmodel;

use App\Models\Carvarient;

use App\Models\Finance;

use App\Models\Inventory;

use App\Models\TransitInventory;

use App\Models\pricelist;

use App\Models\OBF;

use App\Models\Product;

use App\Models\Transfer;

use App\Models\ExtandWarranty;

use App\Models\Mcp;

use App\Models\RSA;

use App\Models\Branch;

use App\Models\Accessory;

use App\Models\rto_master;

use App\Models\Teammaster;

use App\Models\CashReceipt;

use App\Models\MakeDeal;

use App\Models\ObfInsurance;

use App\Models\User;

use App\Models\Order;

use App\Models\Texmaster;

use App\Models\CancellationReason;

use Maatwebsite\Excel\Facades\Excel;

use App\Exports\ExportModelReport;

use App\Exports\ExportMunicipleTaxReport;

use App\Exports\ExportSalesReport;

use App\Exports\ExportPurchaseReport;

use App\Exports\ExportRSAReport;

use App\Exports\ExportCCSReport;

use App\Exports\ExportMCPReport;

use App\Exports\ExportEWReport;

use App\Exports\ExportInventoryReport;

use App\Exports\ExportDemoInventoryReport;

use App\Exports\ExportTeamReport;

use App\Exports\ExportUserReport;

use App\Exports\ExportRTOReport;

use App\Exports\ExportTransferReport;

use App\Exports\ExportInsuranceReport;

use App\Exports\ExportFinanceReport;

use App\Exports\ExportStatusWiseReport;

use App\Exports\ExportDayBookReport;

use App\Exports\ExportCashReceiptReport;

use App\Exports\ExportObfReport;

use App\Exports\ExportCancelReasonReport;

use App\Exports\ExportCarDetails;

use App\Exports\ExportBookingDetails;

use App\Exports\ExportYetToDeliverReport;

use App\Exports\ExportBookingReport;

use App\Exports\ExportUsedCarReport;

use App\Exports\ExportCustomerOutstandingReport;

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

use Illuminate\Http\Request;

use App\Jobs\ExportDayBookReportJob;

use Spatie\Permission\Models\Role;

use Carbon\Carbon;

use Illuminate\Support\Str;

use App\Exports\ExportRefundReport;

use App\Exports\ExportDeliverReport;



class DashboardController extends Controller{

    /** index */

        public function index(Request $request){

        	$a_id = auth()->id();

        	$permission_get = '';

            $data_v = auth()->user()->roles->pluck( 'data_permission' );



            if(!empty($data_v) && count($data_v) > 0){

                $permission_get = $data_v[0];

            }

            

        	$row_data = OBF::select('obf.id' ,'obf.customer_name' ,'obf.booking_date' ,'obf.status','car_model.name AS product','obf.created_by as created_by');

            if (!empty($permission_get)) {

                if ($permission_get == 'ONLY_MY_DATA') {

                    $row_data = $row_data->whereRaw('FIND_IN_SET(obf.created_by, "'. auth()->id() .'")');

                } 

                

                if ($permission_get == 'MY_TEAM_DATA' && auth()->user()->team_name != NULL) {

                    $team_name_ids = User::where('team_name', auth()->user()->team_name)->pluck('id')->toArray();   

                    $row_data = $row_data->whereIn('obf.created_by', $team_name_ids);

                } 

                

                if ($permission_get == 'ALL_DATA') {

                    $row_data = $row_data;

                }

            }

            

            if(!empty(auth()->user()->branch)){

                    $row_data = $row_data->whereRaw('FIND_IN_SET(obf.branch_id ,"'.auth()->user()->branch.'")');

            }

            

			$row_data = $row_data->count();

			

			$ewdata = OBF::select('obf.id','orders.status as order_status')->leftjoin('orders','orders.obf_id','=','obf.id')->where('orders.status', 'all_payment_done')->whereNotNull('extanded_warranty_id')->count();

			$mcpdata = OBF::select('obf.id','orders.status as order_status')->leftjoin('orders','orders.obf_id','=','obf.id')->where('orders.status', 'all_payment_done')->whereNotNull('convinience_program')->count();

			$rsadata = OBF::select('obf.id','orders.status as order_status')->leftjoin('orders','orders.obf_id','=','obf.id')->where('orders.status', 'all_payment_done')->whereNotNull('rsa_master_obf')->count();

			$accdata = OBF::select('obf.id','orders.status as order_status')->leftjoin('orders','orders.obf_id','=','obf.id')->where('orders.status', 'all_payment_done')->whereNotNull('accessory_id')->count();

			

            // OBF APPROVALS

			$approved = OBF::select('obf.id' ,'obf.customer_name' ,'obf.booking_date' ,'obf.status','car_model.name AS product','obf.created_by as created_by')

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

                ->leftjoin('car_model', 'car_model.id', 'products.car_model');

               

            if (!empty($permission_get)) {

                if ($permission_get == 'ONLY_MY_DATA') {

                    $approved = $approved->whereRaw('FIND_IN_SET(obf.created_by, "'. auth()->id() .'")');

                } 

                

                if ($permission_get == 'MY_TEAM_DATA' && auth()->user()->team_name != NULL) {

                    $team_name_ids = User::where('team_name', auth()->user()->team_name)->pluck('id')->toArray();   

                    $approved = $approved->whereIn('obf.created_by', $team_name_ids);

                } 

                

                if ($permission_get == 'ALL_DATA') {

                    $approved = $approved;

                }

            }    

            // if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){

            //     $approved = $approved->whereRaw('FIND_IN_SET(obf.created_by ,"'.auth()->id().'")');

            // }

            if(!empty(auth()->user()->branch)){

                $approved =$approved->whereRaw('FIND_IN_SET(obf.branch_id ,"'.auth()->user()->branch.'")');

            }

            $row_approved = $approved ->where('obf.status' ,'pending')->get()->count();

           	

           	// CASH RECEIPT GENERATED

			$cash_receipt = OBF::select('obf.id', 'obf.booking_date', 'obf.customer_name', 'car_model.name AS product_name', 'obf.status')

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

                ->leftjoin('car_model', 'car_model.id', 'products.car_model');

                

			if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){

                $cash_receipt = $cash_receipt->whereRaw('FIND_IN_SET(obf.created_by ,"'.auth()->id().'")');

            }

            if(!empty(auth()->user()->branch)){

                $cash_receipt = $cash_receipt->whereRaw('FIND_IN_SET(obf.branch_id ,"'.auth()->user()->branch.'")');

            }    

               $cash_receipt = $cash_receipt->where(['obf.status' => 'obf_accepted'])

                ->orWhere(['obf.status' => 'account_accepted'])

                ->orderBy('obf.id' ,'desc')

                ->get()->count();

                

            // INVENTORY

            $inventory_data = Inventory::select('inventory.*','fule_type.title','inventory.created_by as created_by')->leftjoin('fule_type','fule_type.id','=','inventory.fuel_type');

           	if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){

                $inventory_data = $inventory_data->whereRaw('FIND_IN_SET(inventory.created_by ,"'.auth()->id().'")');

            }

            if(!empty(auth()->user()->branch)){

                $inventory_data = $inventory_data->whereRaw('FIND_IN_SET(inventory.branch_id ,"'.auth()->user()->branch.'")');

            }

            

			$inventory_data = $inventory_data->count();

            // dd($inventory_data);

            

            // PRICELIST

            $pricelist_data = pricelist::select('pricelist_master.id', 'pricelist_master.price_list_name','car_model.name as product', 'car_varient.name as car_variant_name','colortone.name as color_type','transmission.name as t_name', 'pricelist_master.ex_showroom_price', 'pricelist_master.statutory_charges', 'pricelist_master.registration_corporate_charges', 'pricelist_master.registration_individual_charges', 'pricelist_master.status', 'pricelist_master.created_at')

                        ->leftjoin('car_model', 'car_model.id', 'pricelist_master.car_model')

                        ->leftjoin('transmission', 'transmission.id', 'pricelist_master.transmission')

                        ->leftjoin('car_varient', 'car_varient.id', 'pricelist_master.car_variant')

                        ->leftjoin('colortone', 'colortone.id', 'pricelist_master.colour_type')

                        ->where('pricelist_master.status','!=','deleted')

                        ->orderBy('pricelist_master.id', 'desc');

           	if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){

                $pricelist_data = $pricelist_data->whereRaw('FIND_IN_SET(pricelist_master.created_at ,"'.auth()->id().'")');

            }

            if(!empty(auth()->user()->branch)){

                $pricelist_data = $pricelist_data->whereRaw('FIND_IN_SET(pricelist_master.branch_id ,"'.auth()->user()->branch.'")');

            }

            

			$pricelist_data = $pricelist_data->count();

            // dd($pricelist_data);

			

            // ALL PAYMENT DONE 			

           	$payment = DB::table('orders as o')

                            ->select('o.id', 'o.order_id', 'b.name as branch_name','o.created_by')

                            ->leftjoin('branches as b', 'b.id', 'o.branch_id')

                            ->orderBy('o.id' ,'desc');

                            

            if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){

                $payment = $payment->whereRaw('FIND_IN_SET(o.created_by ,"'.auth()->id().'")');

            }

            

            if(!empty(auth()->user()->branch)){

                $payment = $payment->whereRaw('FIND_IN_SET(o.branch_id ,"'.auth()->user()->branch.'")');

            }

            

            $payment = $payment->where('o.status', 'all_payment_done')->get()->count();



            // ALLOCATED

            $allocated = DB::table('orders as o')

                            ->select('o.id', 'o.order_id', 'b.name as branch_name','o.created_by')

                            ->leftjoin('branches as b', 'b.id', 'o.branch_id')

                            ->orderBy('o.id' ,'desc');

                            

            if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){

                $allocated = $allocated->whereRaw('FIND_IN_SET(o.created_by ,"'.auth()->id().'")');

            }

                            

            if(!empty(auth()->user()->branch)){

                $allocated = $allocated->whereRaw('FIND_IN_SET(o.branch_id ,"'.auth()->user()->branch.'")');

            }

            

            $allocated = $allocated->where('o.inventory_id', '!=', 'NULL')->get()->count();



            // COMPLETED P.D.I APPROVED

            $pdi = DB::table('orders as o')

                            ->select('o.id', 'o.order_id', 'b.name as branch_name','o.created_by')

                            ->leftjoin('branches as b', 'b.id', 'o.branch_id')

                            ->orderBy('o.id' ,'desc');

                            

            if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){

                $pdi = $pdi->whereRaw('FIND_IN_SET(o.created_by ,"'.auth()->id().'")');

            }

            

            if(!empty(auth()->user()->branch)){

                $pdi = $pdi->whereRaw('FIND_IN_SET(o.branch_id ,"'.auth()->user()->branch.'")');

            }

            

            $pdi = $pdi->where('o.status', '!=', 'pdi_reject')->get()->count();

            

            // DELIVERED

            $delivered = DB::table('orders as o')

                            ->select('o.id', 'o.order_id', 'b.name as branch_name','o.created_by','o.status')

                            ->leftjoin('branches as b', 'b.id', 'o.branch_id')

                            ->orderBy('o.id' ,'desc');

            // dd($delivered);

            if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){

                $delivered = $delivered->whereRaw('FIND_IN_SET(o.created_by ,"'.auth()->id().'")');

            }

            

            if(!empty(auth()->user()->branch)){

                $delivered = $delivered->whereRaw('FIND_IN_SET(o.branch_id ,"'.auth()->user()->branch.'")');

            }

            

            $delivered = $delivered->where('o.status', 'delivered')->get()->count();

            // dd($delivered);

            $delivered = DB::table('orders as o')

                            ->select('o.id', 'o.order_id', 'b.name as branch_name','o.created_by','o.status')

                            ->leftjoin('branches as b', 'b.id', 'o.branch_id')

                            ->orderBy('o.id' ,'desc');

            // dd($delivered);

            if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){

                $delivered = $delivered->whereRaw('FIND_IN_SET(o.created_by ,"'.auth()->id().'")');

            }

            

            if(!empty(auth()->user()->branch)){

                $delivered = $delivered->whereRaw('FIND_IN_SET(o.branch_id ,"'.auth()->user()->branch.'")');

            }

            

            $delivered = $delivered->where('o.status', 'delivered')->get()->count();



            $allreports = DB::table('orders as o')

                            ->select('o.id', 'o.order_id', 'b.name as branch_name','o.created_by','o.status')

                            ->leftjoin('branches as b', 'b.id', 'o.branch_id')

                            ->orderBy('o.id' ,'desc');

                            

            if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){

                $allreports = $allreports->whereRaw('FIND_IN_SET(o.created_by ,"'.auth()->id().'")');

            }

            

            // if(!empty(auth()->user()->branch)){

            //     $allreports = $allreports->whereRaw('FIND_IN_SET(o.branch_id ,"'.auth()->user()->branch.'")');

            // }

            

            $allreports = $allreports->count();

            

            $year = date('Y');

            $onRoadPrices = [];

            $row_data1 = OBF::select(

                DB::raw('MONTH(booking_date) as month'),

                DB::raw('SUM(CAST(on_road_price AS DECIMAL(10,2))) as total_on_road_price')

            )

            ->whereYear('booking_date', '=', $year)

            ->groupBy(DB::raw('MONTH(booking_date)'))

            ->orderBy(DB::raw('MONTH(booking_date)'))

            ->get(); 

             foreach ($row_data1 as $data) {

                $onRoadPrices[] = $data->total_on_road_price;

            }

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

                $roleName = "";

                if ($role) {

                    $roleName = $role[0]->name;

                }

                

                $inventoryCount = DB::table('inventory')

                    ->where('status', 'active')

                    ->where('status', '!=','allocatedDealer')

                    

                    ->count();

               

                $inventorydelCount = DB::table('inventory')

                   ->where('status', '!=', 'deleted')

                    ->where('status', '!=', 'active')

                    ->where('status', '!=','allocatedDealer')

                    

                    ->count();

                    

                $typea = DB::table('inventory')

                   ->where('status', '!=', 'deleted')

                   ->where('status', '!=','allocatedDealer')

                    

                   ->where('inventory_type', 'Type A')

                    ->count();

                    

                $typeb = DB::table('inventory')

                   ->where('status', '!=', 'deleted')

                   ->where('status', '!=','allocatedDealer')

                    ->where('inventory_type', 'Type B')

                    ->count();

                

                $typec = DB::table('inventory')

                   ->where('status', '!=', 'deleted')

                    ->where('status', '!=','allocatedDealer')

                  

                   ->where('inventory_type', 'Type C')

                    ->count();

                

                

                $typed = DB::table('inventory')

                   ->where('status', '!=', 'deleted')

                    ->where('status', '!=','allocatedDealer')

                  

                   ->where('inventory_type', 'Type D')

                    ->count();

                    

                    

                    

                

            $car_detail = DB::table('inventory as i')

                ->select('i.id',  'i.name', 'b.name as branch', 'i.veriant','i.inventory_type','i.ex_showroom_price', 'i.status','i.aging_days', 'cv.name as varient_name', 'cm.name as car_name','i.vin_number',DB::raw('count(obf.id) as obf_id'),DB::raw('(CASE 

                        WHEN i.status = "allocated" THEN obf.customer_name                         

                        END) AS customer_name'),'i.purchase_price','i.kin_margin','i.manufacturing_year', 'fule_type.title as fuel_type')

                ->leftjoin('branches as b', 'b.id', 'i.branch_id')

                ->leftjoin('products', 'i.name', 'products.id')

                ->leftjoin('car_model as cm', 'cm.id', 'products.car_model')

                ->leftjoin('car_varient as cv', 'cv.id', 'products.veriant')

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

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

                ->leftJoin('obf','obf.product_id','=','i.name')

                ->leftjoin('fule_type','fule_type.id','=','i.fuel_type')

                ->groupBy('car_name')

                ->orderBy('i.id', 'desc')

                ->where('i.status','!=',"allocatedDealer")

                ->where('i.status','!=','deleted')->get();    

           

          $i = 0;

            $car_details=[];

            foreach ($car_detail as $value) {

                $total = DB::table('inventory as i')

                ->where('name', $value->name)  // Access property with -> instead of []

                ->where('i.status', '!=', "allocatedDealer")

                ->where('i.status', '!=', 'deleted')

                ->count();

               

                $car_details[$i] = [

                    'car_name' => $value->car_name,

                    'total' => $total

                ];

                $i++;

            }



            /** New Dashboard Code Only For Top 4 Div **/

            /** OBF DATA */

            $user = auth()->user();
            $permission_get = $permission_get ?? null;

            /** Common filter */
            $applyFilters = function ($query) use ($user, $permission_get) {

                // ONLY MY DATA
                if ($permission_get === 'ONLY_MY_DATA') {
                    $query->where('obf.sales_person_id', $user->id);
                }

                $user = auth()->user();
                if ($permission_get === 'MY_TEAM_DATA') {
                    if (!empty($user->team_name)) {
                        $teamId = $user->team_name;
                        $teamUserIds = User::where('team_name', $teamId)
                            ->pluck('id')
                            ->toArray();
                        $query = $query->whereIn('obf.sales_person_id', $teamUserIds);
                    } else {
                        $query = $query->where('obf.sales_person_id', $user->id);
                    }
                }

                // BRANCH FILTER
                if (!empty($user->branch)) {
                    $query->whereRaw('FIND_IN_SET(obf.branch_id, "' . $user->branch . '")');
                }

                // MY TEAM DATA
                if ($permission_get === 'MY_TEAM_DATA' && $user->team_name !== null) {
                    $teamIds = \App\Models\User::where('team_name', $user->team_name)->pluck('id');
                    $query->whereIn('obf.created_by', $teamIds);
                }

                return $query;
            };

            $total_obf = OBF::whereNotIn('obf.status', ['delete','rejected','obf_rejected','deleted','cancel']);
            $total_obf = $applyFilters($total_obf);
            $total_obf = $total_obf->count();

            $tl_pending = OBF::where('obf.approval_status', 'pending')->whereNotIn('obf.status', ['completed','refund_process','account_accepted','delete']);
            $tl_pending = $applyFilters($tl_pending);
            $tl_pending = $tl_pending->count();

            $sm_pending = OBF::where('obf.approval_status', 'obf_tl_accepted')->whereNotIn('obf.status', ['completed','refund_process','account_accepted','delete']);
            $sm_pending = $applyFilters($sm_pending);
            $sm_pending = $sm_pending->count();

            $gm_pending = OBF::where('obf.approval_status', 'obf_sm_accepted')->whereNotIn('obf.status', ['completed','refund_process','account_accepted','delete']);
            $gm_pending = $applyFilters($gm_pending);
            $gm_pending = $gm_pending->count();

            
            /** INVENTORY DATA */
            $live_inventory = Inventory::where('inventory.status','=','active');
            if(!empty(auth()->user()->branch)){
                $live_inventory = $live_inventory->whereRaw('FIND_IN_SET(inventory.branch_id ,"'.auth()->user()->branch.'")');
            }
            $live_inventory = $live_inventory->count();

            $transit_inventory = TransitInventory::where('transit_inventory.status','=','active');
            if(!empty(auth()->user()->branch)){
                $transit_inventory = $transit_inventory->whereRaw('FIND_IN_SET(transit_inventory.branch_id ,"'.auth()->user()->branch.'")');
            }
            $transit_inventory = $transit_inventory->count();

            $customer_alloted = Inventory::where('inventory.status','=','allocated')->count();
            $dealer_alloted = Inventory::where('inventory.status','=','allocatedDealer')->count();
            $total_inventory = $live_inventory + $transit_inventory + $customer_alloted + $dealer_alloted;

            /** OORDER DATA */
            $all_payment_done = Order::where('orders.status','=','all_payment_done')->count();
            $invoice_create = Order::where('orders.status','=','invoice_create')->count();
            $delivered = Order::where('orders.status','=','delivered')->count();

			return view('dashboard',compact('ewdata','mcpdata','rsadata','accdata','roleName'))->with(['car_detail' => $car_details,'typea' => $typea,'typeb' => $typeb,'typec' => $typec,'typed' => $typed,'inventoryCount' => $inventoryCount,'inventorydelCount' => $inventorydelCount,'row_data' => $row_data, 'row_approved' => $row_approved, 'cash_receipt' => $cash_receipt, 'payment' => $payment, 'pdi' => $pdi, 'delivered' => $delivered, 'allocated' => $allocated, 'onRoadPrices'=>$onRoadPrices,'inventory_data'=>$inventory_data,'pricelist_data'=>$pricelist_data,'allreports'=>$allreports,'total_obf'=>$total_obf,'tl_pending'=>$tl_pending,'sm_pending'=>$sm_pending,'gm_pending'=>$gm_pending,'live_inventory'=>$live_inventory,'transit_inventory'=>$transit_inventory,'customer_alloted'=>$customer_alloted,'dealer_alloted'=>$dealer_alloted,'total_inventory'=>$total_inventory,'all_payment_done'=>$all_payment_done,'invoice_create'=>$invoice_create,'delivered'=>$delivered]);

		} 

    /** index */

    

    

    public function allReport(){
        $user_branches = auth()->user()->branch;
        $allowedBranchIds = explode(',', $user_branches);
        $branches = Branch::where('status', 'active')->whereIn('id', $allowedBranchIds)->get();

        $models = Carmodel::select('id', 'name')->where('status', 'active')->get();

        $fuelTypes = DB::table('fule_type')->pluck('title', 'id');

        $from_date = request()->from_date;
        $to_date   = request()->to_date;


        // Fetch inventory counts grouped by car_model, fuel_type, branch_id, and status

        $inventoryData = DB::table('inventory')

            ->join('products', 'inventory.name', '=', 'products.id')

            ->select(

                'products.car_model',

                'inventory.fuel_type',

                'inventory.branch_id',

                'inventory.status',
                
                'inventory.created_at',

                DB::raw('count(*) as total'),

                DB::raw('GROUP_CONCAT(inventory.id) as inventory_ids')

            )

            ->whereNotIn('inventory.status', ['inactive', 'deleted', 'sold','invoice_create'])
            
            ->when($from_date && $to_date, function ($query) use ($from_date, $to_date) {
                $query->whereDate('inventory.created_at', '>=', $from_date)
                      ->whereDate('inventory.created_at', '<=', $to_date);
            })

            ->groupBy(

                'products.car_model',

                'inventory.fuel_type',

                'inventory.branch_id',

                'inventory.status'

            )

            ->get();

            

         $transitInventoryData = DB::table('transit_inventory')

            ->join('products', 'transit_inventory.name', '=', 'products.id')

            ->select(

                'products.car_model',

                'transit_inventory.fuel_type',

                'transit_inventory.branch_id',

                'transit_inventory.status',
                
                'transit_inventory.created_at',

                DB::raw('count(*) as total'),

                DB::raw('GROUP_CONCAT(transit_inventory.id) as inventory_ids')

            )

            ->whereNotIn('transit_inventory.status', ['inactive', 'deleted'])
            
            ->when($from_date && $to_date, function ($query) use ($from_date, $to_date) {
                $query->whereDate('transit_inventory.created_at', '>=', $from_date)
                      ->whereDate('transit_inventory.created_at', '<=', $to_date);
            })
            
            ->groupBy(

                'products.car_model',

                'transit_inventory.fuel_type',

                'transit_inventory.branch_id',

                'transit_inventory.status'

            )

            ->get();    

        

        $data = [];

        $transitData = [];

        

        foreach ($inventoryData as $row) {

            $modelId = $row->car_model;

            $fuelTypeId = $row->fuel_type;

            $branchId = $row->branch_id;

            $status = $row->status;

            $total = $row->total;

            $inventoryIds = explode(',', $row->inventory_ids);

        

            // Initialize nested structure

            if (!isset($data[$modelId][$fuelTypeId][$branchId])) {

                $data[$modelId][$fuelTypeId][$branchId] = [

                    'allocated' => 0,

                    'deal_generated' => 0,

                    'active' => 0,

                    'pdi_hold' => 0,

                    'inventory_ids' => [],

                ];

            }

        

            // Merge allocated and allocatedDealer into 'allocated'

            if (in_array($status, ['allocated', 'allocatedDealer'])) {

                $data[$modelId][$fuelTypeId][$branchId]['allocated'] += $total;

        

                if (!isset($data[$modelId][$fuelTypeId][$branchId]['inventory_ids']['allocated'])) {

                    $data[$modelId][$fuelTypeId][$branchId]['inventory_ids']['allocated'] = [];

                }

                $data[$modelId][$fuelTypeId][$branchId]['inventory_ids']['allocated'] = array_merge(

                    $data[$modelId][$fuelTypeId][$branchId]['inventory_ids']['allocated'],

                    $inventoryIds

                );

            }

            else {

                // Count other statuses normally

                if (isset($data[$modelId][$fuelTypeId][$branchId][$status])) {

                    $data[$modelId][$fuelTypeId][$branchId][$status] += $total;

                } else {

                    $data[$modelId][$fuelTypeId][$branchId][$status] = $total;

                }

        

                // Merge inventory IDs

                if (!isset($data[$modelId][$fuelTypeId][$branchId]['inventory_ids'][$status])) {

                    $data[$modelId][$fuelTypeId][$branchId]['inventory_ids'][$status] = [];

                }

                $data[$modelId][$fuelTypeId][$branchId]['inventory_ids'][$status] = array_merge(

                    $data[$modelId][$fuelTypeId][$branchId]['inventory_ids'][$status],

                    $inventoryIds

                );

            }

        }

        

        // Process transit data (NEW LOGIC)

        foreach ($transitInventoryData as $row) {

            $modelId = $row->car_model;

            $fuelTypeId = $row->fuel_type;

            $branchId = $row->branch_id;

            $total = $row->total;

            $inventoryIds = explode(',', $row->inventory_ids);

        

            if (!isset($transitData[$modelId][$fuelTypeId][$branchId])) {

                $transitData[$modelId][$fuelTypeId][$branchId] = [

                    'total' => 0,

                    'inventory_ids' => []

                ];

            }

        

            $transitData[$modelId][$fuelTypeId][$branchId]['total'] += $total;

            $transitData[$modelId][$fuelTypeId][$branchId]['inventory_ids'] = array_merge(

                $transitData[$modelId][$fuelTypeId][$branchId]['inventory_ids'],

                $inventoryIds

            );

        }  


        $startDate = '2026-01-01';
        $cutoffDate = Carbon::now()->subDays(45)->format('Y-m-d'); // 45 days ago
        
        $booking_fuel_type_data = DB::table('obf')
            ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id') // include OBFs with no orders
            ->leftJoin('inventory', 'orders.inventory_id', '=', 'inventory.id')
            ->join('cash_receipt', function ($join) {
                $join->on('cash_receipt.obf_id', '=', 'obf.id')
                     ->where('cash_receipt.status', '!=', 'rejected');
            })
            ->join('fule_type', 'obf.fuel_type', '=', 'fule_type.id')
            ->select(
                'fule_type.title as fuel_type',
                'obf.branch_id',
                DB::raw('COUNT(DISTINCT obf.id) as total'),
                DB::raw('GROUP_CONCAT(DISTINCT obf.id) as obf_ids')
            )
            ->whereDate('obf.booking_date', '>=', $startDate) // 01-01-2026 onward
            ->whereNotIn('obf.status', [
                'obf_rejected',
                'rejected',
                'deleted',
                'cancel',
                'delete',
                'refund_process'
            ])
            ->whereNotIn('obf.approval_status', [
                'obf_tl_rejected',
                'obf_sm_rejected',
                'obf_gm_rejected',
                'obf_accountant_rejected',
                'delete'
            ])
            ->where(function ($query) use ($cutoffDate) {
                // Include if: no order OR order exists but invoice not created AND booking date within 45 days
                $query->whereNull('orders.id') // no orders
                      ->orWhere(function ($q) use ($cutoffDate) {
                          $q->where(function ($q2) {
                              $q2->whereNull('orders.invoice_no')
                                 ->orWhere('orders.invoice_no', '=', '');
                          })
                          ->whereDate('obf.booking_date', '>', $cutoffDate); // booking within last 45 days
                      });
            })
            ->when($from_date && $to_date, function ($query) use ($from_date, $to_date) {
                $query->whereDate('obf.booking_date', '>=', $from_date)
                      ->whereDate('obf.booking_date', '<=', $to_date);
            })
            ->groupBy('fuel_type', 'obf.branch_id')
            ->get()
            ->groupBy('fuel_type');
    

        // Get total per branch

        $totalsPerBranch = DB::table('obf')

            ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id')

            ->join('cash_receipt', function ($join) {

                $join->on('cash_receipt.obf_id', '=', 'obf.id')

                     ->where('cash_receipt.status', '!=', 'rejected');

            })

            ->where(function ($query) {

                $query->whereNull('orders.id')

                      ->orWhereNull('orders.invoice_no');

            })

            ->select('obf.branch_id', DB::raw('COUNT(DISTINCT obf.id) as total'))

            ->groupBy('obf.branch_id')

            ->whereNotIn('obf.status', [

                'obf_rejected',

                'rejected',

                'deleted',

                'cancel',

                'delete',

                'refund_process'

            ])

            ->whereNotIn('obf.approval_status', [

                'obf_tl_rejected',

                'obf_sm_rejected',

                'obf_gm_rejected',

                'obf_accountant_rejected',

                'delete'

            ])

            ->pluck('total', 'obf.branch_id');

            
            $startDate = '2026-01-01';
            $cutoffDate = Carbon::now()->subDays(45)->format('Y-m-d');
            
            $obfIds = DB::table('obf')
                ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id')
                ->join('cash_receipt', function ($join) {
                    $join->on('cash_receipt.obf_id', '=', 'obf.id')
                         ->where('cash_receipt.status', '!=', 'rejected');
                })
                ->whereDate('obf.booking_date', '>=', $startDate)
                ->whereNotIn('obf.status', [
                    'obf_rejected','rejected','deleted','cancel','delete','refund_process'
                ])
                ->whereNotIn('obf.approval_status', [
                    'obf_tl_rejected','obf_sm_rejected','obf_gm_rejected','obf_accountant_rejected','delete'
                ])
                ->where(function ($query) use ($cutoffDate) {
                    $query->whereNull('orders.id')
                          ->orWhere(function ($q) use ($cutoffDate) {
                              $q->where(function ($q2) {
                                  $q2->whereNull('orders.invoice_no')
                                     ->orWhere('orders.invoice_no', '=', '');
                              })
                              ->whereDate('obf.booking_date', '>', $cutoffDate);
                          });
                })
                ->distinct()
                ->pluck('obf.id');
                
                
                $modelWiseCustomerBookingData = DB::table('obf')
                ->join('products', 'obf.product_id', '=', 'products.id')
                ->join('cash_receipt', function ($join) {
                    $join->on('cash_receipt.obf_id', '=', 'obf.id')
                         ->where('cash_receipt.status', '!=', 'rejected');
                })
                ->whereIn('obf.id', $obfIds) // âœ… SAME DATASET (VERY IMPORTANT)
                ->select(
                    'products.car_model',
                    'obf.fuel_type',
                    'obf.branch_id',
                    DB::raw('COUNT(DISTINCT obf.id) as total'),
                    DB::raw('GROUP_CONCAT(DISTINCT obf.id) as obf_ids')
                )
                ->when($from_date && $to_date, function ($query) use ($from_date, $to_date) {
                    $query->whereDate('obf.booking_date', '>=', $from_date)
                          ->whereDate('obf.booking_date', '<=', $to_date);
                })
                ->groupBy('products.car_model', 'obf.fuel_type', 'obf.branch_id')
                ->get();
                
                
                $modelbookingdata = [];

                foreach ($modelWiseCustomerBookingData as $row) {
                    $modelId = $row->car_model;
                    $fuelTypeId = $row->fuel_type;
                    $branchId = $row->branch_id;
                
                    $modelbookingdata[$modelId][$fuelTypeId][$branchId] = [
                        'total' => $row->total,
                        'obf_ids' => explode(',', $row->obf_ids),
                    ];
                }


        // Get Fuel Type Data

        $startDate = '2026-01-01';
        $cutoffDate = Carbon::now()->subDays(45)->format('Y-m-d');
        
        $obfIds = DB::table('obf')
            ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id')
            ->join('cash_receipt', function ($join) {
                $join->on('cash_receipt.obf_id', '=', 'obf.id')
                     ->where('cash_receipt.status', '!=', 'rejected');
            })
            ->whereDate('obf.booking_date', '>=', $startDate)
            ->whereNotIn('obf.status', [
                'obf_rejected','rejected','deleted','cancel','delete','refund_process'
            ])
            ->whereNotIn('obf.approval_status', [
                'obf_tl_rejected','obf_sm_rejected','obf_gm_rejected','obf_accountant_rejected','delete'
            ])
            ->where(function ($query) use ($cutoffDate) {
                $query->whereNull('orders.id')
                      ->orWhere(function ($q) use ($cutoffDate) {
                          $q->where(function ($q2) {
                              $q2->whereNull('orders.invoice_no')
                                 ->orWhere('orders.invoice_no', '=', '');
                          })
                          ->whereDate('obf.booking_date', '>', $cutoffDate);
                      });
            })
            ->distinct()
            ->pluck('obf.id'); // âœ… EXACT 176 IDs


            $booking_fuel_type_amt_wise_data = DB::table('obf')
            ->join('fule_type', 'obf.fuel_type', '=', 'fule_type.id')
            ->join('cash_receipt', function ($join) {
                $join->on('cash_receipt.obf_id', '=', 'obf.id')
                     ->where('cash_receipt.status', '!=', 'rejected');
            })
            ->whereIn('obf.id', $obfIds) // âœ… ensures exact same records
            ->select(
                'fule_type.title as fuel_type',
                'obf.branch_id',
                DB::raw('SUM(cash_receipt.amount) as total'),
                DB::raw('GROUP_CONCAT(DISTINCT obf.id) as obf_ids')
            )
            ->when($from_date && $to_date, function ($query) use ($from_date, $to_date) {
                $query->whereDate('obf.booking_date', '>=', $from_date)
                      ->whereDate('obf.booking_date', '<=', $to_date);
            })
            ->groupBy('fule_type.title', 'obf.branch_id')
            ->get()
            ->groupBy('fuel_type');



        // Get total per branch

        $totalsPerBranchAmountWise = DB::table('obf')

            ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id')

            ->join('cash_receipt', function ($join) {

                $join->on('cash_receipt.obf_id', '=', 'obf.id')

                ->where('cash_receipt.status', '!=', 'rejected');

            })

            ->where(function ($query) {

                $query->whereNull('orders.id')

                      ->orWhereNull('orders.invoice_no');

            })

            ->select('obf.branch_id', DB::raw('SUM(cash_receipt.amount) as total'))

            ->whereNotIn('obf.status', [

                'obf_rejected',

                'rejected',

                'deleted',

                'cancel',

                'delete',

                'refund_process'

            ])

            ->whereNotIn('obf.approval_status', [

                'obf_tl_rejected',

                'obf_sm_rejected',

                'obf_gm_rejected',

                'obf_accountant_rejected',

                'delete'

            ])
            ->when($from_date && $to_date, function ($query) use ($from_date, $to_date) {
                $query->whereDate('obf.booking_date', '>=', $from_date)
                      ->whereDate('obf.booking_date', '<=', $to_date);
            })
            ->groupBy('obf.branch_id')

            ->pluck('total', 'obf.branch_id');

            
        
        
        // ðŸ”¥ Pre-aggregate cash per OBF
        $cashReceiptSub = DB::table('cash_receipt')
            ->select('obf_id', DB::raw('SUM(amount) as total_amount'))
            ->where('status', '!=', 'rejected')
            ->groupBy('obf_id');
        
        $modelFuelWiseCustomerBookingData = DB::table('obf')
            ->join('products', 'obf.product_id', '=', 'products.id')
            ->leftJoinSub($cashReceiptSub, 'cr', function ($join) {
                $join->on('cr.obf_id', '=', 'obf.id'); // âœ… one row per OBF
            })
            ->whereIn('obf.id', $obfIds) // âœ… SAME DATASET (176)
            ->select(
                'products.car_model',
                'obf.fuel_type',
                'obf.branch_id',
                DB::raw('SUM(cr.total_amount) as total'), // âœ… correct sum
                DB::raw('GROUP_CONCAT(DISTINCT obf.id) as obf_ids') // âœ… unique OBFs
            )
            ->when($from_date && $to_date, function ($query) use ($from_date, $to_date) {
                $query->whereDate('obf.booking_date', '>=', $from_date)
                      ->whereDate('obf.booking_date', '<=', $to_date);
            })
            ->groupBy('products.car_model', 'obf.fuel_type', 'obf.branch_id')
            ->get();
            
            
        
        $modelFuelbookingdata = [];

        foreach ($modelFuelWiseCustomerBookingData as $row) {
            $modelId = $row->car_model;
            $fuelTypeId = $row->fuel_type;
            $branchId = $row->branch_id;
        
            $modelFuelbookingdata[$modelId][$fuelTypeId][$branchId] = [
                'total' => $row->total,
                'obf_ids' => explode(',', $row->obf_ids),
            ];
        }    
        

        

        

        // Get total per branch

        $totalsPerLocation = DB::table('obf')

            ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id')

            ->where(function ($query) {

                $query->WhereNotNull('orders.id')

                      ->orWhereNotNull('orders.invoice_no');

            })

            ->select('obf.branch_id', DB::raw('COUNT(DISTINCT obf.id) as total'))

            ->groupBy('obf.branch_id')

            ->pluck('total', 'obf.branch_id');

            
        /* Retail Target Report */
        $taget_from_date = request()->taget_from_date;
        $taget_to_date   = request()->taget_to_date;
        $modelWiseTargetBookingData = DB::table('target')
            ->select(
                'target.model',
                'target.fuel_type',
                'target.branch',
                DB::raw('SUM(target.target_value) as total'),
                DB::raw('GROUP_CONCAT(target.id) as obf_ids') 
            )
            ->when($taget_from_date && $taget_to_date, function ($query) use ($taget_from_date, $taget_to_date) {
                $query->whereDate('target.date', '>=', $taget_from_date)
                      ->whereDate('target.date', '<=', $taget_to_date);
            })
            ->where('target.target_type', '=', 'retail')
            ->groupBy('target.model', 'target.fuel_type', 'target.branch')
            ->get();
        
        $targetbookingdata = [];
        foreach ($modelWiseTargetBookingData as $row) {
            $modelId = $row->model;
            $fuelTypeId = $row->fuel_type;
            $branchId = $row->branch;
            
            $targetbookingdata[$modelId][$fuelTypeId][$branchId] = [
                'total' => (int) $row->total,
                'obf_ids' => $row->obf_ids ? explode(',', $row->obf_ids) : [],
            ];
        }
        
        
        
        /* Retail Target Archive Report */
        $achievedRaw = DB::table('obf')
            ->join('orders', 'orders.obf_id', '=', 'obf.id')
            ->whereDate('orders.invoice_date', '>=', '2026-04-01')
            ->whereNotNull('orders.invoice_no')
            ->whereNotNull('orders.invoice_date')
        
            ->when($taget_from_date && $taget_to_date, function ($query) use ($taget_from_date, $taget_to_date) {
                $query->whereDate('orders.invoice_date', '>=', $taget_from_date)
                      ->whereDate('orders.invoice_date', '<=', $taget_to_date);
            })
        
            ->select(
                'obf.car_model as model',
                'obf.fuel_type',
                'obf.branch_id as branch',
                DB::raw('COUNT(DISTINCT obf.id) as total'),
                DB::raw('GROUP_CONCAT(DISTINCT obf.id) as obf_ids')
            )
            
            ->groupBy('obf.car_model', 'obf.fuel_type', 'obf.branch_id')
            ->get();
        
        $achievedData = [];
        
        foreach ($achievedRaw as $row) {
            $achievedData[$row->model][$row->fuel_type][$row->branch] = [
                'total' => (int) $row->total,
                'obf_ids' => $row->obf_ids ? explode(',', $row->obf_ids) : [],
            ];
        }
        
        
        
        
        
        /* Wholesale Target Report */
        $modelWiseTargetWholesaleBookingData = DB::table('target')
            ->select(
                'target.model',
                'target.fuel_type',
                'target.branch',
                DB::raw('SUM(target.target_value) as total'),
                DB::raw('GROUP_CONCAT(target.id) as obf_ids') 
            )
            ->when($taget_from_date && $taget_to_date, function ($query) use ($taget_from_date, $taget_to_date) {
                $query->whereDate('target.date', '>=', $taget_from_date)
                      ->whereDate('target.date', '<=', $taget_to_date);
            })
            ->where('target.target_type', '=', 'wholesale')
            ->groupBy('target.model', 'target.fuel_type', 'target.branch')
            ->get();
        
        $targetwholesalebookingdata = [];
        foreach ($modelWiseTargetWholesaleBookingData as $row) {
            $modelId = $row->model;
            $fuelTypeId = $row->fuel_type;
            $branchId = $row->branch;
            
            $targetwholesalebookingdata[$modelId][$fuelTypeId][$branchId] = [
                'total' => (int) $row->total,
                'obf_ids' => $row->obf_ids ? explode(',', $row->obf_ids) : [],
            ];
        }
        
        
        
        /* Wholesale Target Archive Report */
        $achievedWholesaleRaw = DB::table('inventory')
        	->leftJoin('products', 'products.id', '=', 'inventory.name')
            ->whereDate('inventory.kin_invoice_date', '>=', '2026-04-01')
            ->whereNotNull('inventory.kin_invoice_date')
        
            ->when($taget_from_date && $taget_to_date, function ($query) use ($taget_from_date, $taget_to_date) {
                $query->whereDate('orders.kin_invoice_date', '>=', $taget_from_date)
                      ->whereDate('orders.kin_invoice_date', '<=', $taget_to_date);
            })
        
            ->select(
                'products.car_model as model',
                'inventory.fuel_type',
                'inventory.branch_id as branch',
                DB::raw('COUNT(DISTINCT inventory.id) as total'),
                DB::raw('GROUP_CONCAT(DISTINCT inventory.id) as obf_ids')
            )
            
            ->groupBy('products.car_model', 'inventory.fuel_type', 'inventory.branch_id')
            ->get();
        
        $achievedWholesaleData = [];
        
        foreach ($achievedWholesaleRaw as $row) {
            $achievedWholesaleData[$row->model][$row->fuel_type][$row->branch] = [
                'total' => (int) $row->total,
                'obf_ids' => $row->obf_ids ? explode(',', $row->obf_ids) : [],
            ];
        }



        return view('AllReport.report', [

            'branches' => $branches,

            'models' => $models,

            'data' => $data,

            'fuelTypes' => $fuelTypes,

            'booking_fuel_type_data' => $booking_fuel_type_data,

            'totalsPerBranch' => $totalsPerBranch,

            'totalsPerLocation' => $totalsPerLocation,

            'modelWiseCustomerBookingData' =>$modelWiseCustomerBookingData,

            'modelWiseTargetBookingData' =>$modelWiseTargetBookingData,

            'modelbookingdata' => $modelbookingdata,

            'targetbookingdata' => $targetbookingdata,

            'booking_fuel_type_amt_wise_data' => $booking_fuel_type_amt_wise_data,

            'totalsPerBranchAmountWise' => $totalsPerBranchAmountWise,

            'modelFuelWiseCustomerBookingData' => $modelFuelWiseCustomerBookingData,

            'modelFuelbookingdata' => $modelFuelbookingdata,

            'transitData' => $transitData,

            'achievedData' => $achievedData,
            
            'targetwholesalebookingdata' => $targetwholesalebookingdata,
            
            'achievedWholesaleData' => $achievedWholesaleData,

        ]);

    }

    

    // public function getCarDetails(Request $request)

    // {

    //     $ids = $request->input('ids', []);

    //     $cars = DB::table('inventory')

    //     ->join('products', 'inventory.name', '=', 'products.id')

    //     ->join('branches', 'branches.id', '=', 'inventory.branch_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('interiorcolor', 'interiorcolor.id', '=', 'products.interior_color')

    //     ->leftJoin('fule_type', 'fule_type.id', '=', 'inventory.fuel_type')

    //     ->leftJoin('obf', 'obf.inventory_id', '=', 'inventory.id')

    //     ->leftJoin('dealer_management', 'dealer_management.id', '=', 'inventory.delear_id')

    //     ->whereIn('inventory.id', $ids)

    //     ->select(

    //         'inventory.*',

    //         'branches.name as branch_name',

    //         'car_model.name as car_name',

    //         'car_varient.name as varient_name',

    //         'exteriorcolor.name as exterior_color',

    //         'interiorcolor.name as interior_color',

    //         'fule_type.title as fuel_type_name',

    //         DB::raw("COALESCE(obf.customer_name, dealer_management.dealer_name) as customer_name")

    //     )

    //     ->groupBy('inventory.id')

    //     ->get();

        

    //     $transit_ids = $request->input('transit_ids', []);

    //     $transit_cars = DB::table('transit_inventory')

    //     ->join('products', 'transit_inventory.name', '=', 'products.id')

    //     ->join('branches', 'branches.id', '=', 'transit_inventory.branch_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('interiorcolor', 'interiorcolor.id', '=', 'products.interior_color')

    //     ->leftJoin('fule_type', 'fule_type.id', '=', 'transit_inventory.fuel_type')

    //     ->whereIn('transit_inventory.id', $ids)

    //     ->select(

    //         'transit_inventory.*',

    //         'branches.name as branch_name',

    //         'car_model.name as car_name',

    //         'car_varient.name as varient_name',

    //         'exteriorcolor.name as exterior_color',

    //         'interiorcolor.name as interior_color',

    //         'fule_type.title as fuel_type_name',

    //     )

    //     ->groupBy('transit_inventory.id')

    //     ->get();

    

    //     return view('AllReport.ViewReport.car_details_table', compact('cars','transit_cars'));

    // }

    

    public function getCarDetails(Request $request)

    {

        $ids = $request->input('ids', []);

        $transit_ids = $request->input('transit_ids', []);

    

        $cars = collect(); // Empty collection as default

        $transit_cars = collect(); // Same

    

        $data_type = null;

    

        if (!empty($ids)) {

            $data_type = 'inventory';

            $cars = DB::table('inventory')

                ->join('products', 'inventory.name', '=', 'products.id')

                ->join('branches', 'branches.id', '=', 'inventory.branch_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('interiorcolor', 'interiorcolor.id', '=', 'products.interior_color')

                ->leftJoin('fule_type', 'fule_type.id', '=', 'inventory.fuel_type')

                ->leftJoin('obf', 'obf.inventory_id', '=', 'inventory.id')

                ->leftJoin('dealer_management', 'dealer_management.id', '=', 'inventory.delear_id')

                ->whereIn('inventory.id', $ids)

                ->select(

                    'inventory.*',

                    'branches.name as branch_name',

                    'car_model.name as car_name',

                    'car_varient.name as varient_name',

                    'exteriorcolor.name as exterior_color',

                    'interiorcolor.name as interior_color',

                    'fule_type.title as fuel_type_name',

                    DB::raw("COALESCE(obf.customer_name, dealer_management.dealer_name) as customer_name")

                )

                ->groupBy('inventory.id')

                ->get();

        } 

        

        if (!empty($transit_ids)) {

            // $data_type = 'transit';

            $data_type = $data_type === 'inventory' ? 'both' : 'transit';

            $transit_cars = DB::table('transit_inventory')

                ->join('products', 'transit_inventory.name', '=', 'products.id')

                ->join('branches', 'branches.id', '=', 'transit_inventory.branch_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('interiorcolor', 'interiorcolor.id', '=', 'products.interior_color')

                ->leftJoin('fule_type', 'fule_type.id', '=', 'transit_inventory.fuel_type')

                ->whereIn('transit_inventory.id', $transit_ids)

                ->select(

                    'transit_inventory.*',

                    'branches.name as branch_name',

                    'car_model.name as car_name',

                    'car_varient.name as varient_name',

                    'exteriorcolor.name as exterior_color',

                    'interiorcolor.name as interior_color',

                    'fule_type.title as fuel_type_name',

                )

                ->groupBy('transit_inventory.id')

                ->get();

        }



        return view('AllReport.ViewReport.car_details_table', compact('cars', 'transit_cars', 'data_type'));

    }



    

    public function exportCarDetails(Request $request)

    {

        $inventoryIds = json_decode($request->input('ids'), true) ?? [];

        $transitIds = json_decode($request->input('transit_ids'), true) ?? [];

    

        $allIds = [

            'ids' => $inventoryIds,

            'transit_ids' => $transitIds,

        ];

    

        return Excel::download(new ExportCarDetails($allIds), 'car_details.xlsx');

    }   

    

    public function getBookingDetails(Request $request)

    {

        $obfIds = $request->obf_ids;

    

        // Subquery: Total amount from all valid (non-rejected) receipts

       $bookingReceipt = DB::table('cash_receipt')

            ->selectRaw('obf_id, SUM(amount) as booking_amount')

            ->where('receipt_type', 'booking_receipt')

            ->where('status', '!=', 'rejected')

            ->groupBy('obf_id');

        

        $dpReceipt = DB::table('cash_receipt')

            ->selectRaw('obf_id, SUM(amount) as dp_amount')

            ->where('receipt_type', 'downpayment_receipt')

            ->where('status', '!=', 'rejected')

            ->groupBy('obf_id');

        

        $netDisbusment = DB::table('cash_receipt')

            ->selectRaw('obf_id, SUM(amount) as net_disbusment')

            ->where('receipt_type', 'disbusment_receipt')

            ->where('status', '!=', 'rejected')

            ->groupBy('obf_id');

        

        $exchangeAmount = DB::table('exchange_purchase')

            ->selectRaw('obf_id, total_exchange_amount')

            ->where('status', 'active')

            ->groupBy('obf_id');

    

        // Main query with consistent filters and joins

        $data = DB::table('obf')

            ->leftJoin('branches', 'branches.id', '=', 'obf.branch_id')

            ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id')

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

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

            ->leftJoin('inventory', 'products.id', '=', 'inventory.name')

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

            ->leftJoin('users', 'users.id', '=', 'obf.sales_person_id')

            ->leftJoin('Team_master', 'Team_master.id', '=', 'users.team_name')

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

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

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

            ->leftJoin('obf_finance', 'obf_finance.obf_id', '=', 'obf.id')

            // Join subqueries for sums

            ->leftJoinSub($bookingReceipt, 'br', function ($join) {

                $join->on('br.obf_id', '=', 'obf.id');

            })

            ->leftJoinSub($dpReceipt, 'dr', function ($join) {

                $join->on('dr.obf_id', '=', 'obf.id');

            })

            ->leftJoinSub($netDisbusment, 'nr', function ($join) {

                $join->on('nr.obf_id', '=', 'obf.id');

            })

            ->leftJoinSub($exchangeAmount, 'ex', function ($join) {

                $join->on('ex.obf_id', '=', 'obf.id');

            })

            ->select(

                DB::raw("DATE_FORMAT(obf.booking_date, '%d-%m-%Y %H:%i:%s') as booking_date"),

                'branches.name as branch_name',

                'Team_master.team_name',

                DB::raw("CONCAT(users.first_name, ' ', users.last_name) as sales_person_name"),

                'obf.customer_name',

                'car_model.name as product',

                'car_varient.name as car_varient_name',

                'fule_type.title as fuel_type_name',

                'exteriorcolor.name as exterior_color',

                'interiorcolor.name as interior_color',

                'inventory.manufacturing_year',

                'inventory.vin_number',

                'obf.on_road_price',

                'obf_finance.finance_discount',

                'obf.way_off',

                'obf.foc_accessories',

                'obf.offer_ib_amount',

                'obf.offer_kin_amount',

                'br.booking_amount',

                'dr.dp_amount',

                'nr.net_disbusment',

                'ex.total_exchange_amount',

            )

        

            ->whereIn('obf.id', $obfIds)

            ->groupBy('obf.id')

            ->get();

    

        return view('AllReport.ViewReport.booking_fuel_detail', compact('data'));

    }



    

    public function exportBookingDetails(Request $request)

    {

        $ids = json_decode($request->input('ids'), true);

    

        return Excel::download(new ExportBookingDetails($ids), 'booking_details.xlsx');

    }   

    

    public function vinReport(){

        return view('AllReport.vinreport');

    }



    public function ModelReport(){

        return view('AllReport.modelreport');

    }



    public function SalesReport(){

        return view('AllReport.salesreport');

    }

    

    public function yettodeliveryReport(Request $request){

        return view('AllReport.gettodeliveryreport');

    }



    public function BookingReport(){

        return view('AllReport.bookingreport');

    }

    

    public function MunicipleTaxReport(){

        return view('AllReport.municipletaxreport');

    }



    public function PurchaseReport(){

        return view('AllReport.purchasereport');

    }



    public function VarientReport(){

        return view('AllReport.varientreport');

    }



    public function RsaReport(){

        return view('AllReport.rsareport');

    }

    public function CcsReport(){

        return view('AllReport.ccsreport');

    }



    public function McpReport(){

        return view('AllReport.mcpreport');

    }



    public function EwReport(){

        return view('AllReport.ewreport');

    }



    public function TaregetReport(){

        return view('AllReport.targetreport');

    }



    public function AgainDayReport(){

        return view('AllReport.againdayreport');

    }



    public function InventoryReport(){
        $branches = Branch::where('status', 'active')->get();
        $models = Carmodel::select('id', 'name')->where('status', 'active')->get();

        return view('AllReport.inventoryreport', [
            'branches' => $branches,
            'models' => $models
        ]);
    }

    public function BookingAdanceReport(){
        $branches = Branch::where('status', 'active')->get();
        
        $booking_fuel_type_data = DB::table('obf')
            ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id')
            ->leftJoin('inventory', 'orders.inventory_id', '=', 'inventory.id')
            ->join('cash_receipt', function ($join) {
                $join->on('cash_receipt.obf_id', '=', 'obf.id')
                ->where('cash_receipt.status', '!=', 'rejected');
            })
            ->join('fule_type', 'obf.fuel_type', '=', 'fule_type.id') // fuel_type comes from obf

            ->select(
                'fule_type.title as fuel_type',
                'obf.branch_id',
                DB::raw('COUNT(DISTINCT obf.id) as total'),
                DB::raw('GROUP_CONCAT(DISTINCT obf.id) as obf_ids')
            )

            ->where(function ($query) {
                $query->whereNull('orders.id') // obf with no orders
                ->orWhereNull('orders.invoice_no'); // or orders with invoice_no IS NULL
            })
            ->whereNotIn('obf.status', [
                'obf_rejected',
                'rejected',
                'deleted',
                'cancel',
                'delete',
                'refund_process'
            ])
            ->whereNotIn('obf.approval_status', [
                'obf_tl_rejected',
                'obf_sm_rejected',
                'obf_gm_rejected',
                'obf_accountant_rejected',
                'delete'
            ])
            ->groupBy('fuel_type', 'obf.branch_id')
            ->get()
            ->groupBy('fuel_type');
        
        $booking_fuel_type_amt_wise_data = DB::table('obf')

            ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id')

            ->join('cash_receipt', function ($join) {

                $join->on('cash_receipt.obf_id', '=', 'obf.id')

                     ->where('cash_receipt.status', '!=', 'rejected');

            })

            ->join('fule_type', 'obf.fuel_type', '=', 'fule_type.id')

            ->select(

                'fule_type.title as fuel_type',

                'obf.branch_id',

                DB::raw('SUM(cash_receipt.amount) as total'),

                DB::raw('GROUP_CONCAT(DISTINCT obf.id) as obf_ids')

            )

            ->where(function ($query) {

                $query->whereNull('orders.id')

                      ->orWhereNull('orders.invoice_no');

            })

            ->whereNotIn('obf.status', [

                'obf_rejected',

                'rejected',

                'deleted',

                'cancel',

                'delete',

                'refund_process'

            ])
            ->whereNotIn('obf.approval_status', [
                'obf_tl_rejected',
                'obf_sm_rejected',
                'obf_gm_rejected',
                'obf_accountant_rejected',
                'delete'
            ])
            ->groupBy('fule_type.title', 'obf.branch_id')
            ->get()
            ->groupBy('fuel_type');

        $modelWiseCustomerBookingData = DB::table('obf')

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

            ->leftJoin('orders', 'obf.id', '=', 'orders.obf_id')

            ->join('cash_receipt', function ($join) {

                $join->on('cash_receipt.obf_id', '=', 'obf.id')

                     ->where('cash_receipt.status', '!=', 'rejected');

            })

            ->select(

                'products.car_model',

                'obf.fuel_type',

                'obf.branch_id',

                DB::raw('COUNT(DISTINCT obf.id) as total'),

                DB::raw('GROUP_CONCAT(DISTINCT obf.id) as obf_ids')

            )

            ->where(function ($query) {

                $query->whereNull('orders.id')

                      ->orWhereNull('orders.invoice_no');

            })

            ->whereNotIn('obf.status', [

                'obf_rejected',

                'rejected',

                'deleted',

                'cancel',

                'delete',

                'refund_process'

            ])

            ->whereNotIn('obf.approval_status', [

                'obf_tl_rejected',

                'obf_sm_rejected',

                'obf_gm_rejected',

                'obf_accountant_rejected',

                'delete'

            ])

            ->groupBy('products.car_model', 'obf.fuel_type', 'obf.branch_id')

            ->get();



        

        $modelbookingdata = [];

        foreach ($modelWiseCustomerBookingData as $row) {

            $modelId = $row->car_model;

            $fuelTypeId = $row->fuel_type;

            $branchId = $row->branch_id;

            $total = $row->total;

            $obfIds = explode(',', $row->obf_ids);

        

            $modelbookingdata[$modelId][$fuelTypeId][$branchId] = [

                'total' => $total,

                'obf_ids' => $obfIds,

            ];

        }

        $modelFuelWiseCustomerBookingData = DB::table('obf')

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

            ->leftJoin('orders', 'obf.id', '=', 'orders.obf_id')

            ->join('cash_receipt', function ($join) {

                $join->on('cash_receipt.obf_id', '=', 'obf.id')

                     ->where('cash_receipt.status', '!=', 'rejected');

            })

            ->select(

                'products.car_model',

                'obf.fuel_type',

                'obf.branch_id',

                DB::raw('SUM(cash_receipt.amount) as total'),

                DB::raw('GROUP_CONCAT(obf.id) as obf_ids')

            )

            ->where(function ($query) {

                $query->whereNull('orders.id')

                      ->orWhereNull('orders.invoice_no');

            })

            ->whereNotIn('obf.status', [

                'obf_rejected',

                'rejected',

                'deleted',

                'cancel',

                'delete',

                'refund_process'

            ])

            ->whereNotIn('obf.approval_status', [

                'obf_tl_rejected',

                'obf_sm_rejected',

                'obf_gm_rejected',

                'obf_accountant_rejected',

                'delete'

            ])

            ->groupBy('products.car_model', 'obf.fuel_type', 'obf.branch_id')

            ->get();

        

        $modelFuelbookingdata = [];

        

        foreach ($modelFuelWiseCustomerBookingData as $row) {

            $modelId = $row->car_model;

            $fuelTypeId = $row->fuel_type;

            $branchId = $row->branch_id;

            $total = $row->total;

            $obfIds = explode(',', $row->obf_ids);

            $modelFuelbookingdata[$modelId][$fuelTypeId][$branchId] = [
                'total' => $total,
                'obf_ids' => $obfIds,
            ];
        }

        return view('AllReport.bookingadvancereport', [
            'branches' => $branches,
            'booking_fuel_type_data' => $booking_fuel_type_data,
            'modelbookingdata' => $modelbookingdata,
            'modelFuelbookingdata' => $modelFuelbookingdata,
            'booking_fuel_type_amt_wise_data' => $booking_fuel_type_amt_wise_data
        ]);
    }

    public function SalesMisReport()
    {
        $branches = Branch::where('status', 'active')->get();
        $modelWiseTargetBookingData = DB::table('obf')
            ->join('products', 'obf.product_id', '=', 'products.id')
            ->leftJoin('orders', 'obf.id', '=', 'orders.obf_id')
            ->select(
                'products.car_model',
                'obf.fuel_type',
                'obf.branch_id',
                DB::raw('COUNT(DISTINCT obf.id) as total'),
                DB::raw('GROUP_CONCAT(obf.id) as obf_ids')
            )
            ->where(function ($query) {
                $query->WhereNotNull('orders.id')
                ->orWhereNotNull('orders.invoice_no');
            })
            ->groupBy('products.car_model', 'obf.fuel_type', 'obf.branch_id')
            ->get();

        $targetbookingdata = [];

        foreach ($modelWiseTargetBookingData as $row) {
            $modelId = $row->car_model;
            $fuelTypeId = $row->fuel_type;
            $branchId = $row->branch_id;
            $total = $row->total;
            $obfIds = explode(',', $row->obf_ids);
            $targetbookingdata[$modelId][$fuelTypeId][$branchId] = [
                'total' => $total,
                'obf_ids' => $obfIds,
            ];
        }

        return view('AllReport.salesmisreport', [
            'branches' => $branches,
            'targetbookingdata' => $targetbookingdata
        ]);
    }



    public function TeamReport(){

        return view('AllReport.teamreport');

    }



    public function UserReport(){

        return view('AllReport.userreport');

    }



    public function OfferReport(){

        return view('AllReport.offerreport');

    }



    public function BranchReport(){

        return view('AllReport.branchreport');

    }



    public function FualtypeReport(){

        return view('AllReport.fualtypereport');

    }



    public function TranssimissionReport(){

        return view('AllReport.transsimissionreport');

    }



    public function ColourReport(){

        return view('AllReport.colourreport');

    }



    public function RTOReport(){

        return view('AllReport.rtoreport');

    }



    public function CustomerReport(){

        return view('AllReport.customerreport');

    }





    public function TransferReport(){

        return view('AllReport.transferreport');

    }



    public function InsuranceReport(){

        return view('AllReport.insurancereport');

    }



    public function FinanceReport(){

        return view('AllReport.financereport');

    }

    

    public function StatusReport(){

        $status = OBF::pluck('status','id')->unique()->toArray();

        view()->share('status',$status);

        return view('AllReport.statuswisereport');

    }



    public function vinReportfetch(Request $request){

        $obfRecords = Inventory::select(

            'obf.id', 'obf.customer_name', DB::raw("DATE_FORMAT(obf.booking_date, '%d-%m-%Y') as 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.accesories_status', 'obf.on_road_price',

            'car_varient.name AS car_varient_name', 'branches.name as branch_name',

            'cash_receipt.status as receipt_status', 'orders.status as order_status',

            'inventory.vin_number', 'inventory.id',

            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

            DB::raw('ROUND(obf.on_road_price - sum(cash_receipt.amount)) as due_amount'),

            DB::raw('ROUND(sum(cash_receipt.amount)) as received_amount'),

            'obf.gst', 'exteriorcolor.name as exterior_color',

            'obf.address', 'obf.registration', 'obf_finance.loan_amount',

            'obf_finance.finance_discount',

            DB::raw('SUM(IF(cash_receipt.receipt_type = "booking_receipt",cash_receipt.amount,0)) as booking_amount'),

            DB::raw('SUM(IF(cash_receipt.receipt_type = "downpayment_receipt",cash_receipt.amount,null)) as dp_amount'),

            'Team_master.team_name', 'exchange_purchase.total_exchange_amount'

        )

        ->leftJoin('obf', 'obf.inventory_id', 'inventory.id')

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

        ->leftJoin('orders','orders.obf_id','=','obf.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('exchange_purchase','exchange_purchase.obf_id','=','obf.id')

        ->orderBy('inventory.id','desc')

        ->groupBy('inventory.id')

        ->get();



        return DataTables::of($obfRecords)

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

                $query->where('branches.name', 'like', '%' . request()->get('branch_name') . '%');

            }

            if (request()->get('customer_name')) {

                $query->where('obf.customer_name', 'like', '%' . request()->get('customer_name') . '%');

            }

            if (request()->get('gst')) {

                $query->where('obf.gst', 'like', '%' . request()->get('gst') . '%');

            }

            if (request()->get('team_name')) {

                $query->where('Team_master.team_name', 'like', '%' . request()->get('team_name') . '%');

            }

            if (request()->get('sales_person_name')) {

                $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%" . request()->get('sales_person_name') . "%"]);

            }

            if (request()->get('product')) {

                $query->where('car_model.name', 'like', '%' . request()->get('product') . '%');

            }

            if (request()->get('car_varient_name')) {

                $query->where('car_varient.name', 'like', '%' . request()->get('car_varient_name') . '%');

            }

            if (request()->get('exterior_color')) {

                $query->where('exteriorcolor.name', 'like', '%' . request()->get('exterior_color') . '%');

            }

            if (request()->get('vin_number')) {

                $query->where('inventory.vin_number', 'like', '%' . request()->get('vin_number') . '%');

            }

        })->make(true);

    }



    // public function vinReportshow($id)

    // {

    //     $obfShow = Inventory::where('inventory.id', $id)

    //                     ->select('obf.id', 'obf.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.accesories_status','obf.on_road_price','car_varient.name AS car_varient_name','branches.name as branch_name','cash_receipt.status as receipt_status','orders.status as order_status','inventory.vin_number','inventory.id','inventory.purchase_price','inventory.key_number','inventory.kin_invoice_date','inventory.kin_margin','inventory.inventory_type','inventory.ex_showroom_price',DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),DB::raw('ROUND(obf.on_road_price - sum(cash_receipt.amount)) as due_amount'),DB::raw('ROUND(sum(cash_receipt.amount)) as received_amount'),'obf.gst','exteriorcolor.name as exterior_color','obf.address','obf.registration','obf_finance.loan_amount','obf_finance.finance_discount',DB::raw('SUM(IF(cash_receipt.receipt_type = "booking_receipt",cash_receipt.amount,0)) 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'),

    //                     'Team_master.team_name','exchange_purchase.total_exchange_amount','fule_type.title as fuel_type','obf.extanded_warranty_id' ,

    //                     'extand_warranties.years AS extand_warranties_years' ,'extand_warranties.amount AS extand_warranties_amount','obf.convinience_program',

    //                     'mcp.name AS carName','mcp.amount AS mcpAmount','obf.rsa_master_obf','rsa.name as rsaname','rsa.amount AS rsaamount','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_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','fasttags.id AS fasttag_id' ,'fasttags.amount AS fasttag_amount' ,'fasttags.brand_name AS brand_name','insurance.name AS insurance',

    //                     'customer_type_master.name as customer_type_nm','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.rsa_ccs as rsa_type')

    //                     ->leftJoin('obf', 'obf.inventory_id', 'inventory.id')

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

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

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

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

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

    //                     ->leftjoin('Team_master','Team_master.id','users.team_name')

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

    //                     ->leftjoin('fule_type','fule_type.id','=','inventory.fuel_type')

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

    //                     ->leftjoin('pricelist_master', 'obf.pricelist_id', 'pricelist_master.id')

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

    //                     ->leftjoin('rsa' ,'rsa.id','obf.rsa_master_obf')

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

    //                     ->leftjoin('finance' ,'obf_finance.finance_name' ,'finance.id')

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

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

                        

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

    //                     ->leftjoin('customer_type_master','obf.customer_type_new','customer_type_master.id')

    //                     ->orderBy('inventory.id','desc')->groupBy('inventory.id')->first();    

    //   $transferShow = DB::table('transfer as t')

    //                     ->select('t.id','fb.name as from_branch', 'tb.name as to_branch')

    //                     ->leftjoin('branches as fb', 'fb.id', 't.from_branch')

    //                     ->leftjoin('branches as tb', 'tb.id', 't.to_branch')

    //                     ->where(['t.inventory_id' => $id])

    //                     ->first();   

    //                     // dd($obfShow);

    //     $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.aadhar_pan_link','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.municipal_tax_id','obf.municipal_tax_applicable','obf.tcs_tax_id','obf.nominee_dob','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.rto_deal','make_deal.insurance_deal','make_deal.created_by',

        

    //     'inventory.manufacturing_year','obf.rsa_master_obf','rsa.name as rsaname','rsa.amount AS rsaamount','customer_type_master.name as customer_type_nm','obf.way_off','obf_finance.finance_type',

        

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



    //     ->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('obf_finance', 'obf.id', '=', 'obf_finance.obf_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('obf_rto' ,'obf.id' ,'obf_rto.obf_id')

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

    //     ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')

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

    //     ->leftjoin('customer_type_master','obf.customer_type_new','customer_type_master.id')

    //     ->leftjoin('Team_master','Team_master.id','users.team_name')

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

    //     ->leftjoin('rsa' ,'rsa.id','obf.rsa_master_obf')

    //     ->where(['obf.inventory_id' => $id])->first(); 

        

    //     // dd($data->finance_id);

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

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

    //     //  $ObfInsurance = ObfInsurance::where(['obf_id'=> $id,'is_delete' => 0])->orderBy('id', 'desc')->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;

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

    //     $user_role = $user->getRoleNames();



    //     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('AllReport.ViewReport.vinshow',compact('obfShow','transferShow','data','price_list_name','rto_data','accessory_sum','user','user_role','fule'));

    // }

    

    public function PurchaseReportfetch(Request $request){

        $vin = $request->input('vin');

        $modelName = $request->input('model_name');

        $start_date = $request->input('start_date');

        $end_date = $request->input('end_date');

    

        $query = DB::table('inventory as i')

            ->select(

                'i.id', 'i.name', 'b.name as branch', 'i.veriant', 'i.inventory_type',

                'i.ex_showroom_price', 'i.kin_invoice_no', 'i.fsc_code',

                DB::raw("DATE_FORMAT(i.kin_invoice_date, '%d-%m-%Y') as kin_invoice_date"),

                'i.status', 'i.aging_days', 'cv.name as varient_name', 'cm.name as car_name',

                'i.vin_number', DB::raw('count(obf.id) as obf_id'),

                DB::raw('CASE WHEN i.status = "allocated" THEN obf.customer_name END AS customer_name'),

                'i.purchase_price', 'i.kin_margin', 'i.manufacturing_year',

                'fule_type.title as fuel_type', 'interiorcolor.name as interior_color',

                'exteriorcolor.name as exterior_color',

                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

                'Team_master.team_name'

            )

            ->leftJoin('branches as b', 'b.id', 'i.branch_id')

            ->leftJoin('products', 'i.name', 'products.id')

            ->leftJoin('car_model as cm', 'cm.id', 'products.car_model')

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

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

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

            ->leftJoin('obf','obf.product_id','=','i.name')

            ->leftJoin('fule_type','fule_type.id','=','i.fuel_type')

            ->leftJoin('users','users.id','=','obf.sales_person_id')

            ->leftJoin('Team_master','Team_master.id','=','users.team_name')

            ->where('i.status','!=',"allocatedDealer")

            ->where('i.status','!=','deleted')

            ->groupBy('i.name')

            ->when($start_date && $end_date, function ($query) use ($start_date, $end_date) {

                return $query->whereBetween('i.created_at', [$start_date, $end_date]);

            });

    

        // Filters

        if (!empty($vin)) {

            $query->where('i.vin_number', 'like', "%$vin%");

        }

    

        if (!empty($modelName)) {

            $query->where('cm.name', 'like', "%$modelName%");

        }

    

        $data = $query->orderBy('i.id', 'desc')/*->get()*/;

    

        return DataTables::of($data)

            ->filter(function ($query){           

                if (request()->get('car_name')) {

                    $query->where('cm.name', 'like', '%' . request()->get('car_name') . '%');

                }

                if (request()->get('varient_name')) {

                    $query->where('cv.name', 'like', '%' . request()->get('varient_name') . '%');

                }

                if (request()->get('status')) {

                    $query->where('i.status', 'like', '%' . request()->get('status') . '%');

                }

                if (request()->get('vin_number')) {

                    $query->where('i.vin_number', 'like', '%' . request()->get('vin_number') . '%');

                }

                if (request()->get('branch')) {

                    $query->where('b.name', 'like', '%' . request()->get('branch') . '%');

                }

                if (request()->get('team_name')) {

                    $query->where('Team_master.team_name', 'like', '%' . request()->get('team_name') . '%');

                }

                if (request()->get('sales_person_name')) {

                    $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%" . request()->get('sales_person_name') . "%"]);

                }

                if (request()->get('ex_showroom_price')) {

                    $query->where('i.ex_showroom_price', 'like', '%' . request()->get('ex_showroom_price') . '%');

                }

                if (request()->get('purchase_price')) {

                    $query->where('i.purchase_price', 'like', '%' . request()->get('purchase_price') . '%');

                }

                if (request()->get('kin_margin')) {

                    $query->where('i.kin_margin', 'like', '%' . request()->get('kin_margin') . '%');

                }

                if (request()->get('fuel_type')) {

                    $query->where('fule_type.title', 'like', '%' . request()->get('fuel_type') . '%');

                }

                if (request()->get('customer_name')) {

                    $query->where('obf.customer_name', 'like', '%' . request()->get('customer_name') . '%');

                }

                if (request()->get('aging_days')) {

                    $query->where('i.aging_days', 'like', '%' . request()->get('aging_days') . '%');

                }

                if (request()->get('inventory_type')) {

                    $query->where('i.inventory_type', 'like', '%' . request()->get('inventory_type') . '%');

                }

                if (request()->get('fsc_code')) {

                    $query->where('i.fsc_code', 'like', '%' . request()->get('fsc_code') . '%');

                }

            })

            ->make(true);

    }

    

    public function purchaseExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportPurchaseReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

    

    public function UserReportFetch(Request $request)

    {

        $users = DB::table('users')

            ->select(

                'users.id',

                DB::raw("CONCAT(users.first_name, ' ', users.last_name) as user_name"), 

                'users.branch',

                'users.contact_number',

                'users.status',

                'users.email',

                DB::raw("CONCAT(us.first_name, ' ', us.last_name) AS kec_name"),

                'department.name as department_name'

            )

            ->leftJoin('obf', 'users.id', '=', 'obf.sales_person_id')

            ->leftJoin('users as us', 'us.id', '=', 'obf.sales_person_id')

            ->leftJoin('department', 'department.id', '=', 'users.department_id')

            ->distinct();

            // ->get();



        return DataTables::of($users)

        ->filter(function ($query){           

                    if (request()->get('user_name')) {

                        $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%" . request()->get('user_name') . "%"]);

                    }

                    if (request()->get('contact_number')) {

                        $query->where('users.contact_number', 'like', '%' . request()->get('contact_number') . '%');

                    }

                    if (request()->get('email')) {

                        $query->where('users.email', 'like', '%' . request()->get('email') . '%');

                    }

                    if (request()->get('department_name')) {

                        $query->where('department.name', 'like', '%' . request()->get('department_name') . '%');

                    }

                    if (request()->get('status')) {

                        $query->where('users.status', 'like', '%' . request()->get('status') . '%');

                    }

                })

                ->make(true);

    }

    public function userExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportUserReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

    

    public function TeamReportFetch(Request $request)

    {

        $data = Teammaster::select('Team_master.*','branches.name as branch_name', 'department.name as department')

                    ->leftJoin('branches','branches.id','=','Team_master.branch_name')

                    ->leftJoin('department','department.id','=','Team_master.department')

                    ->orderBy('id' , 'desc')->get();

    

        return Datatables::of($data)

                    ->addIndexColumn()

                    ->make(true);

    }

    

    public function TeamExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportTeamReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

    public function McpReportFetch(Request $request)

    {

        $mcp = DB::table('mcp')->select(

            'id',

            'name',

            'amount',

            'profit',

            'gst_percentage',

            'gst',

            'total_profit',

            'status'

        );

    

        return DataTables::of($mcp)->make(true);

    }

    

    public function ModelReportfetch(Request $request)

        {

            $vin = $request->input('vin');

            $obfRecords = OBF::query()

            ->select(

                'obf.id',

                'car_model.name as model_name',

                'car_varient.name as variant_name',

                DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)), 

                LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),

                'inventory.vin_number',

                'exteriorcolor.name as exterior_color',

                'interiorcolor.name as interior_color',

                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

                'Team_master.team_name'

            )

            ->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('inventory', 'inventory.name', '=', 'products.id')

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

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

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

            ->leftjoin('Team_master','Team_master.id','users.team_name')

            ->when($vin, function ($query) use ($vin) {

                return $query->where('inventory.vin_number', '=', $vin);

            },function ($query) {

                return $query; // Returns all records if VIN is not provided

            })

            ->groupBy('obf.id');

            // ->get();

            

            return DataTables::of($obfRecords)

            ->filter(function ($query){

                    if (request()->get('model_name')) {

                        $query->where('car_model.name', 'like', '%' . request()->get('model_name') . '%');

                    }

                

                    if (request()->get('variant_name')) {

                        $query->where('car_varient.name', 'like', '%' . request()->get('variant_name') . '%');

                    }

                    if (request()->get('status')) {

                        $query->where('obf.status', 'like', '%' . request()->get('status') . '%');

                    }

                    if (request()->get('vin_number')) {

                        $query->where('inventory.vin_number', 'like', '%' . request()->get('vin_number') . '%');

                    }

                    if (request()->get('exterior_color')) {

                        $query->where('exteriorcolor.name', 'like', '%' . request()->get('exterior_color') . '%');

                    }

                    if (request()->get('interior_color')) {

                        $query->where('interiorcolor.name', 'like', '%' . request()->get('interior_color') . '%');

                    }                

                    if (request()->get('team_name')) {

                        $query->where('Team_master.team_name', 'like', '%' . request()->get('team_name') . '%');

                    }

                    if (request()->get('sales_person_name')) {

                        $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%" . request()->get('sales_person_name') . "%"]);

                    }

                }) 

                ->make(true);

        }

        

        public function modelExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportModelReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

    

        public function SalesReportfetch(Request $request)

        {

            $taxes = Texmaster::where(['gst' => 28, 'status' => 'active'])

                ->whereIn('compensation_cess', [1, 3, 17, 22])

                ->orderByRaw("FIELD(compensation_cess, 1, 3, 17, 22)")

                ->get();

        

            $tax_labels = [];

            $tax_ids = [];

            foreach ($taxes as $tax) {

                $tax_labels[] = "({$tax->gst}%+{$tax->compensation_cess}%)";

                $tax_ids[] = $tax->id;

            }

        

            $branches = Branch::select('id', 'city')->where('status', 'active')->get();

            $cess = Texmaster::select('id','compensation_cess')->where('status','active')->orderBy('compensation_cess')->get();

        

            $columnDefs = [];

            $branchTaxKeys = [];

        

            foreach ($branches as $branch) {

                $b_name = '';

                if (str_contains($branch->city, 'Rajkot - Nana Mava')) {

                    $b_name = 'Sales- 1S -Local';

                } elseif (str_contains($branch->city, 'Rajkot')) {

                    $b_name = 'Sales-Rjt-Local';

                } elseif (str_contains($branch->city, 'Jamnagar')) {

                    $b_name = 'Sales-Jmgr-Local';

                } elseif (str_contains($branch->city, 'Junagadh')) {

                    $b_name = 'Sales-Jnd-Local';

                } elseif (str_contains($branch->city, 'Morbi')) {

                    $b_name = 'Sales-Morbi-Local';

                } elseif (str_contains($branch->city, 'Mehsana')) {

                    $b_name = 'Sales-Msn-Local';

                } elseif (str_contains($branch->city, 'Kadi')) {

                    $b_name = 'Sales-Kadi-Local';

                }

        

                foreach ($taxes as $tax) {

                    $colKey = Str::slug("{$b_name} ({$tax->gst}%+{$tax->compensation_cess}%)", '_');

                    $columnDefs[] = [

                        'data' => $colKey,

                        'title' => "{$b_name} ({$tax->gst}%+{$tax->compensation_cess}%)",

                        'class' => 'text-center',

                        'orderable' => false,

                        'searchable' => false

                    ];

                    $branchTaxKeys[$colKey] = [

                        'branch_id' => $branch->id,

                        'tax_id' => $tax->id

                    ];

                }

            }

        

            foreach ($taxes as $tax) {

                $interKey = Str::slug("Sales-Interstate ({$tax->gst}%+{$tax->compensation_cess}%)", '_');

                $columnDefs[] = [

                    'data' => $interKey,

                    'title' => "Sales-Interstate ({$tax->gst}%+{$tax->compensation_cess}%)",

                    'class' => 'text-center',

                    'orderable' => false,

                    'searchable' => false

                ];

            }

        

        

            if ($request->ajax()) {

                $obfRecords = Order::select(

                    DB::raw("DATE_FORMAT(orders.invoice_date, '%d-%m-%Y') as date"),

                    DB::raw("COALESCE(obf.customer_name, dealer_management.dealer_name) AS particulars"),

                    DB::raw("COALESCE(obf.customer_name, dealer_management.dealer_name) AS bill_to"),

                    DB::raw("COALESCE(obf.address, dealer_management.dealer_address) AS bill_to_address"),

                    'obf.ship_to_customer_name',

                    'obf.ship_to_address',

                    'orders.invoice_no',

                    'finance.name as hypo',

                    DB::raw("COALESCE(obf.gst, dealer_management.gst_no) AS gst_no"),

                    'obf.pan_number as pan_no',

                    'obf.adhar_number',

                    'obf.aadhar_pan_link',

                    DB::raw("'1.0 Qty' as qty"),

                    'orders.vin_number',

                    'orders.engine_number',

                    'car_model.name AS car_model',

                    'car_varient.name AS car_varient',

                    'exteriorcolor.name as exterior_color',

                    'orders.total as gross_total',

                    'orders.on_road_price as branch_wise_amt',

                    'orders.cgst',

                    'orders.sgst',

                    'orders.igst',

                    'orders.compensation_cess',

                    'orders.branch_id',

                    'tex_master.id as text_master_id',

                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

                    'Team_master.team_name',

                    'branches.name as branch_name',

                )

                ->leftJoin('obf', 'orders.obf_id', '=', 'obf.id')

                ->leftJoin('dealer_management', 'dealer_management.id', '=', 'orders.dealer_id')

                ->leftJoin('obf_finance', 'obf_finance.obf_id', '=', 'obf.id')

                ->leftJoin('finance', 'finance.id', '=', 'obf_finance.finance_name')

                ->leftJoin('inventory', 'inventory.id',  '=', 'orders.inventory_id')

                ->leftJoin('products', 'inventory.name', '=', 'products.id')

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

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

                ->leftJoin('tex_master', 'car_varient.tex_master_id', '=', 'tex_master.id')

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

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

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

                ->leftjoin('Team_master','Team_master.id','users.team_name')

                ->whereNotNull('orders.invoice_no')

                ->whereNotNull('orders.invoice_date') 

                ->groupBy('orders.id');

        

                $dataTable = DataTables::of($obfRecords);

        

                foreach ($columnDefs as $def) {

                    $key = $def['data'];

        

                    $dataTable->addColumn($key, function ($row) use ($key, $branchTaxKeys) {



                        if (isset($branchTaxKeys[$key])) {

                            $match = $branchTaxKeys[$key];

                            if (

                                $row->branch_id == $match['branch_id'] &&

                                $row->text_master_id == $match['tax_id']

                            ) {

                                return round($row->branch_wise_amt, 2);

                            }

                            return 0;

                        }

        

                        if (Str::startsWith($key, 'sales_interstate')) {

                            return 0;

                        }

                        

        

                        return 0;

                    });

                }

                

                foreach ($cess as $item) {

                    $cessKey = Str::slug("Compensation Cess Output @ {$item->compensation_cess} %", '_');

                

                    $dataTable->addColumn($cessKey, function ($row) use ($item) {

                        $cessPercentage = $item->compensation_cess;

                

                        if ($cessPercentage && is_numeric($row->compensation_cess)) {

                            $actualCessAmt = round((float) $row->compensation_cess, 2);

                            $expectedCessAmt = round(($row->branch_wise_amt * (float) $cessPercentage) / 100, 2);

                

                            if (abs($actualCessAmt - $expectedCessAmt) < 1) {

                                return number_format($expectedCessAmt, 2);

                            }

                        }

                

                        return '0';

                    });

                }

        

                return $dataTable->rawColumns(array_column($columnDefs, 'data'))

                ->filter(function ($query) use ($columnDefs, $branchTaxKeys, $cess) {

                    if (request()->get('branch_name',false)) {

                        $query->where('branches.name', "like", "%".request()->get("branch_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('team_name',false)) {

                        $query->where('Team_master.team_name', "like", "%".request()->get("team_name")."%");

                    }

                    if ($dateRange = request()->get('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('orders.invoice_date', [$start, $end]);

                            } catch (\Exception $e) {

                                \Log::error('Invalid date range format for Date filter', [

                                    'input' => $dateRange,

                                    'error' => $e->getMessage()

                                ]);

                            }

                        }

                    }

                    if (request()->get('particulars',false)) {

                        $particulars = request()->get('particulars');

                        $query->whereRaw("COALESCE(obf.customer_name, dealer_management.dealer_name) LIKE ?", ["%{$particulars}%"]);

                    }

                    if (request()->get('bill_to',false)) {

                        $bill_to = request()->get('bill_to');

                        $query->whereRaw("COALESCE(obf.customer_name, dealer_management.dealer_name) LIKE ?", ["%{$bill_to}%"]);

                    }

                    if (request()->get('bill_to_address',false)) {

                        $bill_to_address = request()->get('bill_to_address');

                        $query->whereRaw("COALESCE(obf.address, dealer_management.dealer_address) LIKE ?", ["%{$bill_to_address}%"]);

                    }

                    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('ship_to_address',false)) {

                        $query->where('obf.ship_to_address', "like", "%".request()->get("ship_to_address")."%");

                    }

                    if (request()->get('invoice_no',false)) {

                        $query->where('orders.invoice_no', "like", "%".request()->get("invoice_no")."%");

                    }

                    if (request()->get('hypo',false)) {

                        $query->where('finance.name', "like", "%".request()->get("hypo")."%");

                    }

                    if (request()->get('gst_no',false)) {

                        $gst_no = request()->get('gst_no');

                        $query->whereRaw("COALESCE(obf.gst, dealer_management.gst_no) LIKE ?", ["%{$gst_no}%"]);

                    }

                    if (request()->get('pan_no',false)) {

                        $query->where('obf.pan_number', "like", "%".request()->get("pan_no")."%");

                    }

                    if (request()->get('adhar_number',false)) {

                        $query->where('obf.adhar_number', "like", "%".request()->get("adhar_number")."%");

                    }

                    if (request()->get('aadhar_pan_link',false)) {

                        $query->where('obf.aadhar_pan_link', "like", "%".request()->get("aadhar_pan_link")."%");

                    }

                    if (request()->get('vin_number',false)) {

                        $query->where('orders.vin_number', "like", "%".request()->get("vin_number")."%");

                    }

                    if (request()->get('engine_number',false)) {

                        $query->where('orders.engine_number', "like", "%".request()->get("engine_number")."%");

                    }

                    if (request()->get('car_model',false)) {

                        $query->where('car_model.name', "like", "%".request()->get("car_model")."%");

                    }

                    if (request()->get('car_varient',false)) {

                        $query->where('car_varient.name', "like", "%".request()->get("car_varient")."%");

                    }

                    if (request()->get('exterior_color',false)) {

                        $query->where('exteriorcolor.name', "like", "%".request()->get("exterior_color")."%");

                    }

                    if (request()->get('gross_total',false)) {

                        $query->where('orders.total', "like", "%".request()->get("gross_total")."%");

                    }

                    foreach ($columnDefs as $column) {

                        $field = $column['data'];

                

                        if (request()->filled($field) && isset($branchTaxKeys[$field])) {

                            // Get the filter value

                            $value = request()->get($field);

                

                            // Get the branch_id and tax_id mapped

                            $match = $branchTaxKeys[$field];

                

                            // Add a where clause to match branch_id and tax_id

                            $query->where('orders.branch_id', $match['branch_id'])

                                  ->where('tex_master.id', $match['tax_id']);

                            

                            // Optional: you may also want to filter by amount using orders.on_road_price if necessary

                             $query->where('orders.on_road_price', 'like', "%{$value}%");

                        }

                    }

                    if (request()->get('cgst',false)) {

                        $query->where('orders.cgst', "like", "%".request()->get("cgst")."%");

                    }

                    if (request()->get('sgst',false)) {

                        $query->where('orders.sgst', "like", "%".request()->get("sgst")."%");

                    }

                    if (request()->get('igst',false)) {

                        $query->where('orders.igst', "like", "%".request()->get("igst")."%");

                    }

                    foreach ($cess as $item) {

                        $cessKey = Str::slug("Compensation Cess Output @ {$item->compensation_cess} %", '_');

                    

                        if (request()->filled($cessKey)) {

                            $inputValue = request()->get($cessKey);

                    

                            // Match if the entered amount is close to expected cess amount

                            $query->whereRaw("orders.compensation_cess LIKE ?", ["%{$inputValue}%"]);

                        }

                    }

                })->make(true);

            }

        

            return view('AllReport.salesreport', compact('branches', 'tax_labels', 'cess', 'columnDefs'));

        }

        public function salesExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportSalesReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function InsuranceFetchReport(Request $request){
            $vin = $request->input('filter');
            
            $permission_get = '';
            $data_v = auth()->user()->roles->pluck('data_permission');
            if (!empty($data_v)) {
                $permission_get = $data_v[0];
            }
            
            if($request->ajax()){

                $obfRecords = OBF::select(
                    'branches.name AS branch' ,
                    'obf.customer_name',
                    'car_model.name AS model', 
                    'car_varient.name AS car_varient_name', 
                    'inventory.vin_number',
                    'orders.invoice_date as invoice_date',
                    'orders.invoice_no as invoice_no',
                    'obf.ex_showroom_price',
                    'obf.insurance_id',
                    'insurance.name AS insurance_name',
                    DB::raw("
                        CASE 
                            WHEN obf_insurance.insurance_exist = '1' THEN 'Inhouse'
                            WHEN obf_insurance.insurance_exist = '0' THEN 'Self'
                            ELSE ''
                        END as insurance_type
                    "),
                    'obf_insurance.policy_number',
                    'obf_insurance.date_of_insurance',
                    'obf_insurance.own_damage_premium',
                    'obf_insurance.gross_premium_paid',
                    DB::raw("
                        CASE 
                            WHEN obf_insurance.status = 'insurance_in_progress' THEN 'In-progress'
                            WHEN obf_insurance.status = 'insurance_completed' THEN 'Completed'
                            ELSE ''
                        END as status
                    "),
                )
                ->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('obf_insurance', 'obf.id', '=', 'obf_insurance.obf_id')
                ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
                ->leftjoin('orders' ,'orders.obf_id','obf.id')
                ->leftjoin('inventory' ,'obf.inventory_id' ,'inventory.id')
                ->leftjoin('insurance' ,'obf_insurance.company_name' ,'insurance.id')
                ->whereNotNull('orders.invoice_no') 
                ->whereNotNull('orders.invoice_date') 
                ->whereNotNull('obf_insurance.obf_id')
                ->when($vin, function ($query) use ($vin) {
                    return $query->where('obf.vin', 'like', "%$vin%");
                })
                ->groupBy('obf.id')
                ->orderBy('obf.id','desc');
            
                return DataTables::of($obfRecords)
                    ->editColumn('invoice_date', function($obfRecords) {
                        return (!empty($obfRecords->invoice_date)) ? \Carbon\Carbon::parse($obfRecords->invoice_date)->format('d-m-Y') : '--';
                    })
                    
                    ->editColumn('date_of_insurance', function($obfRecords) {
                        return (!empty($obfRecords->date_of_insurance)) ? \Carbon\Carbon::parse($obfRecords->date_of_insurance)->format('d-m-Y') : '--';
                    })
                    
                    ->filter(function ($query) {
                        if (request()->get('branch')) {
                            $query->where('branches.name', 'like', '%' . request()->get('branch') . '%');
                        }
                        
                        if (request()->get('customer_name')) {
                            $query->where('obf.customer_name', 'like', '%' . request()->get('customer_name') . '%');
                        }
                        
                        if (request()->get('model')) {
                            $query->where('car_model.name', 'like', '%' . request()->get('model') . '%');
                        }
                        
                        if (request()->get('car_varient_name')) {
                            $query->where('car_varient.name', 'like', '%' . request()->get('car_varient_name') . '%');
                        }
                        
                        if (request()->get('vin_number')) {
                            $query->where('inventory.vin_number', 'like', '%' . request()->get('vin_number') . '%');
                        }
                        
                        if ($dateRange = request()->get('invoice_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('orders.invoice_date', [$start, $end]);
                                } catch (\Exception $e) {
                                    \Log::error('Invalid date range format for invoice date filter', [
                                        'input' => $dateRange,
                                        'error' => $e->getMessage()
                                    ]);
                                }
                            }
                        }
                        
                        if (request()->get('invoice_no', false)) {
                            $query->where('orders.invoice_no', 'like', "%" . request()->get("invoice_no") . "%");
                        }
                        
                        if (request()->get('ex_showroom_price')) {
                            $query->where('obf.ex_showroom_price', 'like', '%' . request()->get('ex_showroom_price') . '%');
                        }
                        
                        if (request()->get('insurance_id')) {
                            $query->where('obf.insurance_id', 'like', '%' . request()->get('insurance_id') . '%');
                        }
                        
                        if (request()->get('insurance_name')) {
                            $query->where('insurance.name', 'like', '%' . request()->get('insurance_name') . '%');
                        }
                        
                        if (request()->get('insurance_type',false)) {
                            $query->having('insurance_type', 'LIKE', '%' . request()->get('insurance_type') . '%');
                        }
                        
                        if (request()->get('policy_number')) {
                            $query->where('obf_insurance.policy_number', 'like', '%' . request()->get('policy_number') . '%');
                        }
                        
                        if ($dateRange = request()->get('date_of_insurance', 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_insurance.date_of_insurance', [$start, $end]);
                                } catch (\Exception $e) {
                                    \Log::error('Invalid date range format for insurance date filter', [
                                        'input' => $dateRange,
                                        'error' => $e->getMessage()
                                    ]);
                                }
                            }
                        }
                        
                        if (request()->get('own_damage_premium')) {
                            $query->where('obf_insurance.own_damage_premium', 'like', '%' . request()->get('own_damage_premium') . '%');
                        }
                        
                        if (request()->get('gross_premium_paid')) {
                            $query->where('obf_insurance.gross_premium_paid', 'like', '%' . request()->get('gross_premium_paid') . '%');
                        }
                        
                        if (request()->get('status',false)) {
                            $query->having('status', 'LIKE', '%' . request()->get('status') . '%');
                        }

                    })
                ->make(true);
            }
        }

        public function insuranceExport(Request $request){
            $request->validate([
                'slug' => 'required|string'
            ]);

            $slug = $request->input('slug');
            $name = 'InsuranceReport_' . now()->format('YmdHis') . '.xlsx';

            $fromDate = null;
            $toDate = null;

            if ($request->filter_booking_date) {

                $dates = preg_split('/\s+to\s+/i', trim($request->filter_booking_date));
            
                if (count($dates) == 2) {
            
                    $fromDate = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[0]))->startOfDay();
            
                    $toDate = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[1]))->endOfDay();
                }
            }

            try {

                return Excel::download(new ExportInsuranceReport($slug, $fromDate, $toDate), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function StatusReportFetch(Request $request)

        {

            $vin = $request->input('status');



            $obfRecords = OBF::select(

                    'car_model.name AS product', 

                    'car_varient.name AS car_varient_name', 

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)), 

                    LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),

                    'inventory.vin_number',

                    'obf.on_road_price',

                    'Team_master.team_name',

                    'obf.customer_name',

                    'obf.booking_date',

                    'branches.name AS branch_name',

                    DB::raw("CONCAT(us.first_name,' ',us.last_name) AS kec_name")

                )

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

                ->leftJoin('branches', 'obf.branch_id', '=', 'branches.id')

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

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

                ->leftjoin('Team_master','Team_master.id','us.team_name')

                ->join('inventory', 'inventory.name', '=', 'products.id')

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

                // ->groupBy('car_model.name', 'car_varient.name', 'obf.status')

                ->when($vin, function ($query) use ($vin) {

                    return $query->where('obf.status', 'like', "%$vin%"); 

                });

            

            return DataTables::of($obfRecords)

                        ->filter(function ($query){

                            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('status',false)) {

                                $query->where('obf.status', "like", "%".request()->get("status")."%");

                            }

                            if (request()->get('vin_number',false)) {

                                $query->where('inventory.vin_number', "like", "%".request()->get("vin_number")."%");

                            }

                            if (request()->get('sales_person_name',false)) {

                                $salesPersonName = request()->get('sales_person_name');

                                $query->whereRaw("CONCAT(us.first_name, ' ', us.last_name) LIKE ?", ["%{$salesPersonName}%"]);

                            }

                            if (request()->get('team_name',false)) {

                                $query->where('Team_master.team_name', "like", "%".request()->get("team_name")."%");

                            }

                            if (request()->get('on_road_price',false)) {

                                $query->where('obf.on_road_price', "like", "%".request()->get("on_road_price")."%");

                            }

                            if (request()->get('booking_date',false)) {

                                $query->where('obf.booking_date', "like", "%".request()->get("booking_date")."%");

                            }

                            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")."%");

                            }

                        })

                        ->make(true);

        }

        public function statuswiseExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportStatusWiseReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function getStatusCounts()

        {

            $statusCounts = DB::table('obf')

                ->select('status', DB::raw('COUNT(*) as count'))

                ->groupBy('status')

                ->get();

        

            return response()->json($statusCounts);

        }

    

        /*public function FinanceReportFetch(Request $request)

        {

            $obfRecords = OBF::from('obf as obf')

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

                ->leftJoin('inventory', 'inventory.name', '=', 'products.id')

                ->leftJoin('branches', 'obf.branch_id', '=', 'branches.id')

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

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

                ->leftJoin('obf_finance', 'obf.id', '=', 'obf_finance.obf_id')

                ->leftJoin('finance', 'obf_finance.finance_name', '=', 'finance.id')

                ->leftJoin('users', 'users.id', '=', 'obf.sales_person_id')

                ->leftJoin('Team_master', 'Team_master.id', '=', 'users.team_name')

                ->leftJoin('orders','orders.obf_id','=','obf.id')

                ->select(

                    'obf.id',

                    DB::raw("DATE_FORMAT(obf.booking_date, '%d-%m-%Y') as booking_date"),

                    'car_model.name AS product',

                    'car_varient.name AS car_varient_name',

                    'obf.customer_name',

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(branches.name, '_', ' '), 1)),

                        LOWER(SUBSTRING(REPLACE(branches.name, '_', ' '), 2))) AS branch_name"),

                    'inventory.vin_number AS vin_number',

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)),

                        LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),

                    'obf_finance.finance_required',

                    'obf_finance.disbursement AS disbursement_field',

                    'finance.name AS financer',

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf_finance.finance_type, '_', ' '), 1)),

                        LOWER(SUBSTRING(REPLACE(obf_finance.finance_type, '_', ' '), 2))) AS finance_type"),

                    'obf_finance.repo_rate',

                    'obf_finance.loan_amount',

                    'obf_finance.net_disbusment AS net_disbursement_amount',

                    'obf_finance.processing_fee',

                    'obf_finance.finance_discount',

                    'obf_finance.payout AS payout_percentage',

                    'obf_finance.payout_amount',

                    'obf_finance.lumsum_amount',

                    'obf_finance.pay_booster',

                    'obf_finance.total_payout_amount AS total_payout',

                    DB::raw("CONCAT(users.first_name, ' ', users.last_name) AS sales_person_name"),

                    'Team_master.team_name',

                    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(DATE_FORMAT(MAX(orders.invoice_date), '%d-%m-%Y'), '--') as invoice_date"),

                )

                ->whereNotNull('obf_finance.obf_id')

                ->whereNotNull('orders.invoice_no')

                ->where('obf_finance.finance_required', 'Yes')

                ->where('obf.status', '!=', 'deleted')

                ->where('obf.status', '!=', 'delete')

                ->groupBy('obf.id','obf.booking_date');

        

            return DataTables::of($obfRecords)

                ->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('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('status', false)) {

                        $query->where('obf.status', 'like', "%" . request()->get("status") . "%");

                    }

                    if (request()->get('customer_name', false)) {

                        $query->where('obf.customer_name', 'like', "%" . request()->get("customer_name") . "%");

                    }

                    if (request()->get('branch_name', false)) {

                        $branch = request()->get("branch_name");

                        $query->whereRaw("

                            CONCAT(

                                UCASE(LEFT(REPLACE(branches.name, '_', ' '), 1)),

                                LOWER(SUBSTRING(REPLACE(branches.name, '_', ' '), 2))

                            ) LIKE ?", ["%$branch%"]);

                    }

                    if (request()->get('vin_number', false)) {

                        $query->where('inventory.vin_number', 'like', "%" . request()->get("vin_number") . "%");

                    }

                    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('finance_required', false)) {

                        $query->where('obf_finance.finance_required', 'like', "%" . request()->get("finance_required") . "%");

                    }

                    if (request()->get('disbursement_field', false)) {

                        $query->where('obf_finance.disbursement', 'like', "%" . request()->get("disbursement_field") . "%");

                    }

                    if (request()->get('financer', false)) {

                        $query->where('finance.name', 'like', "%" . request()->get("financer") . "%");

                    }

                    if (request()->get('finance_type', false)) {

                        $query->where('obf_finance.finance_type', 'like', "%" . request()->get("finance_type") . "%");

                    }

                    if (request()->get('repo_rate', false)) {

                        $query->where('obf_finance.repo_rate', 'like', "%" . request()->get("repo_rate") . "%");

                    }

                    if (request()->get('loan_amount', false)) {

                        $query->where('obf_finance.loan_amount', 'like', "%" . request()->get("loan_amount") . "%");

                    }

                    if (request()->get('net_disbursement_amount', false)) {

                        $query->where('obf_finance.net_disbusment', 'like', "%" . request()->get("net_disbursement_amount") . "%");

                    }

                    if (request()->get('processing_fee', false)) {

                        $query->where('obf_finance.processing_fee', 'like', "%" . request()->get("processing_fee") . "%");

                    }

                    if (request()->get('finance_discount', false)) {

                        $query->where('obf_finance.finance_discount', 'like', "%" . request()->get("finance_discount") . "%");

                    }

                    if (request()->get('payout_percentage', false)) {

                        $query->where('obf_finance.payout', 'like', "%" . request()->get("payout_percentage") . "%");

                    }

                    if (request()->get('payout_amount', false)) {

                        $query->where('obf_finance.payout_amount', 'like', "%" . request()->get("payout_amount") . "%");

                    }

                    if (request()->get('lumsum_amount', false)) {

                        $query->where('obf_finance.lumsum_amount', 'like', "%" . request()->get("lumsum_amount") . "%");

                    }

                    if (request()->get('pay_booster', false)) {

                        $query->where('obf_finance.pay_booster', 'like', "%" . request()->get("pay_booster") . "%");

                    }

                    if (request()->get('total_payout', false)) {

                        $query->where('obf_finance.total_payout_amount', 'like', "%" . request()->get("total_payout") . "%");

                    }

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

        }*/
        
        public function FinanceReportFetch(Request $request){

            $obfRecords = OBF::from('obf as obf')
                ->leftJoin('products', 'obf.product_id', '=', 'products.id')
                ->leftJoin('inventory', 'inventory.name', '=', 'products.id')
                ->leftJoin('branches', 'obf.branch_id', '=', 'branches.id')
                ->leftJoin('car_varient', 'car_varient.id', '=', 'products.veriant')
                ->leftJoin('car_model', 'car_model.id', '=', 'products.car_model')
                ->leftJoin('obf_finance', 'obf.id', '=', 'obf_finance.obf_id')
                ->leftJoin('finance', 'obf_finance.finance_name', '=', 'finance.id')
                ->leftJoin('users', 'users.id', '=', 'obf.sales_person_id')
                ->leftJoin('Team_master', 'Team_master.id', '=', 'users.team_name')
                ->leftJoin('orders','orders.obf_id','=','obf.id')
                ->select(
                    'obf.id',
                    DB::raw("DATE_FORMAT(obf.booking_date, '%d-%m-%Y') as booking_date"),
                    'car_model.name AS product',
                    'car_varient.name AS car_varient_name',
                    'obf.customer_name',
                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(branches.name, '_', ' '), 1)),LOWER(SUBSTRING(REPLACE(branches.name, '_', ' '), 2))) AS branch_name"),
                    'inventory.vin_number AS vin_number',
                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)),LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),
                    'obf_finance.finance_required',
                    'obf_finance.disbursement AS disbursement_field',
                    'finance.name AS financer',
                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf_finance.finance_type, '_', ' '), 1)),LOWER(SUBSTRING(REPLACE(obf_finance.finance_type, '_', ' '), 2))) AS finance_type"),
                    'obf_finance.repo_rate',
                    'obf_finance.loan_amount',
                    'obf_finance.net_disbusment AS net_disbursement_amount',
                    'obf_finance.processing_fee',
                    'obf_finance.finance_discount',
                    'obf_finance.payout AS payout_percentage',
                    'obf_finance.payout_amount',
                    'obf_finance.lumsum_amount',
                    'obf_finance.pay_booster',
                    'obf_finance.booster_percentage',
                    'obf_finance.total_payout_amount AS total_payout',
                    DB::raw("CONCAT(users.first_name, ' ', users.last_name) AS sales_person_name"),
                    'Team_master.team_name',
                    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(DATE_FORMAT(MAX(orders.invoice_date), '%d-%m-%Y'), '--') as invoice_date"),
                )
        
                ->where('obf_finance.finance_required', 'Yes')
                ->whereNotNull('obf_finance.obf_id')
        
                // remove deleted
                ->whereNotIn('obf.status', ['deleted','delete'])
        
                // only invoice created data
                ->whereNotNull('orders.invoice_no')
                ->where('orders.invoice_no','!=','')
        
                ->groupBy('obf.id')
        
                ->orderBy('finance.name','asc');
        
            return DataTables::of($obfRecords)
                ->filter(function ($query) {
                    
                    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('customer_name', false)) {
                        $query->where('obf.customer_name', 'like', "%" . request()->get("customer_name") . "%");
                    }
        
                    if (request()->get('branch_name', false)) {
                        $branch = request()->get("branch_name");
                        $query->whereRaw("
                            CONCAT(
                                UCASE(LEFT(REPLACE(branches.name, '_', ' '), 1)),
                                LOWER(SUBSTRING(REPLACE(branches.name, '_', ' '), 2))
                            ) LIKE ?", ["%$branch%"]);
                    }
        
                    if (request()->get('vin_number', false)) {
                        $query->where('inventory.vin_number', 'like', "%" . request()->get("vin_number") . "%");
                    }
        
                    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('financer', false)) {
                        $query->where('finance.name', 'like', "%" . request()->get("financer") . "%");
                    }
        
                    if (request()->get('finance_type', false)) {
                        $query->where('obf_finance.finance_type', 'like', "%" . request()->get("finance_type") . "%");
                    }
        
                    if (request()->get('repo_rate', false)) {
                        $query->where('obf_finance.repo_rate', 'like', "%" . request()->get("repo_rate") . "%");
                    }
        
                    if (request()->get('loan_amount', false)) {
                        $query->where('obf_finance.loan_amount', 'like', "%" . request()->get("loan_amount") . "%");
                    }
        
                    if (request()->get('net_disbursement_amount', false)) {
                        $query->where('obf_finance.net_disbusment', 'like', "%" . request()->get("net_disbursement_amount") . "%");
                    }
        
                    if (request()->get('processing_fee', false)) {
                        $query->where('obf_finance.processing_fee', 'like', "%" . request()->get("processing_fee") . "%");
                    }
        
                    if (request()->get('finance_discount', false)) {
                        $query->where('obf_finance.finance_discount', 'like', "%" . request()->get("finance_discount") . "%");
                    }
        
                    if (request()->get('payout_percentage', false)) {
                        $query->where('obf_finance.payout', 'like', "%" . request()->get("payout_percentage") . "%");
                    }
        
                    if (request()->get('payout_amount', false)) {
                        $query->where('obf_finance.payout_amount', 'like', "%" . request()->get("payout_amount") . "%");
                    }
        
                    if (request()->get('lumsum_amount', false)) {
                        $query->where('obf_finance.lumsum_amount', 'like', "%" . request()->get("lumsum_amount") . "%");
                    }
        
                    if (request()->get('pay_booster', false)) {
                        $query->where('obf_finance.pay_booster', 'like', "%" . request()->get("pay_booster") . "%");
                    }
                    
                    if (request()->get('booster_percentage', false)) {
                        $query->where('obf_finance.booster_percentage', 'like', "%" . request()->get("booster_percentage") . "%");
                    }
                    
                    if (request()->get('total_payout', false)) {
                        $query->where('obf_finance.total_payout_amount', 'like', "%" . request()->get("total_payout") . "%");
                    }
        
                    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);
        }



        public function financeExport(Request $request){

            $request->validate([

                'slug' => 'required|string'

            ]);

            $slug = $request->input('slug');
            
            $fromDate = null;

            $toDate = null;

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

            if ($request->filter_booking_date) {

                [$from, $to] = array_map('trim', explode('to', $request->filter_booking_date));

        
                $fromDate = \Carbon\Carbon::createFromFormat('d-m-Y', $from)->startOfDay();

                $toDate   = \Carbon\Carbon::createFromFormat('d-m-Y', $to)->endOfDay();

            }

            try {

                return Excel::download(new ExportFinanceReport($slug, $fromDate, $toDate), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        // public function getExtendedWarranty(Request $request)

        // {

        //     $vin = $request->input('filter'); // Filter by VIN if provided

    

        //     $obfRecords = OBF::select(

        //             'car_model.name AS product', 

        //             'car_varient.name AS car_varient_name', 

        //             'obf.status',

        //             'obf.ew_status',

        //             'obf.customer_name',

        //             'extand_warranties.years AS ew_years'

        //         )

        //         ->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('extand_warranties', 'obf.extanded_warranty_id', '=', 'extand_warranties.id')

        //         ->whereNotNull('obf.ew_status')

        //         ->whereNotNull('extand_warranties.years')

        //         ->groupBy(

        //             'car_model.name',

        //             'car_varient.name',

        //             'obf.status',

        //             'obf.ew_status',

        //             'obf.customer_name',

        //             'extand_warranties.years'

        //         )

        //         ->when($vin, function ($query) use ($vin) {

        //             return $query->where('obf.vin', 'like', "%$vin%");

        //         })

        //         ->get();

        //     return DataTables::of($obfRecords)->make(true);

        // }

        // CHANGED BY HIRAL

        public function getExtendedWarranty(Request $request)

        {

            $vin = $request->input('filter'); // Filter by VIN if provided

    

            $obfRecords = OBF::select(

                    'obf.id as id',

                    'car_model.name AS product', 

                    'car_varient.name AS car_varient_name', 

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)), 

                    LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),

                    'obf.ew_status',

                    'obf.customer_name',

                    'extand_warranties.years AS ew_years',

                    'extand_warranties.amount AS extand_warranties_amount',

                    'ew_process_dms.ew_invoice', 

                    'ew_process_dms.ew_invoice_date', 

                    'ew_process_dms.dms_invoice_no',

                    'ew_process_dms.dms_invoice_date', 

                    'ew_process_dms.dms_gatepass_date', 

                    'ew_process_dms.dms_location', 

                    'ew_process_dms.dms_ew_create_date', 

                    'ew_process_dms.dms_ew_certificate',

                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

                    'Team_master.team_name'

                )

                ->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('extand_warranties', 'obf.extanded_warranty_id', '=', 'extand_warranties.id')

                ->leftJoin('ew_process_dms', 'obf.id', '=', 'ew_process_dms.obf_id')

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

                ->leftjoin('Team_master','Team_master.id','users.team_name')

                ->whereNotNull('obf.ew_status')

                ->whereNotNull('extand_warranties.years')

                ->whereNotNull('ew_process_dms.obf_id')

                ->groupBy(

                    'obf_id',

                    'car_model.name',

                    'car_varient.name',

                    'obf.status',

                    'obf.ew_status',

                    'obf.customer_name',

                    'extand_warranties.years',

                    'extand_warranties.amount',

                    'ew_process_dms.ew_invoice',

                    'ew_process_dms.ew_invoice_date',

                    'ew_process_dms.dms_invoice_no',

                    'ew_process_dms.dms_invoice_date',

                    'ew_process_dms.dms_gatepass_date',

                    'ew_process_dms.dms_location',

                    'ew_process_dms.dms_ew_create_date',

                    'ew_process_dms.dms_ew_certificate'

                )

                ->when($vin, function ($query) use ($vin) {

                    return $query->where('obf.vin', 'like', "%$vin%");

                });

            return DataTables::of($obfRecords)

                        ->filter(function ($query){

                            if (request()->get('customer_name',false)) {

                                $query->where('obf.customer_name', "like", "%".request()->get("customer_name")."%");

                            }

                            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('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('ew_years',false)) {

                                $query->where('ew.name', "like", "%".request()->get("ew_years")."%");

                            }

                            if (request()->get('extand_warranties_amount',false)) {

                                $query->where('ew.amount', "like", "%".request()->get("extand_warranties_amount")."%");

                            }

                            if (request()->get('ew_invoice',false)) {

                                $query->where('ew_process_dms.ew_invoice', "like", "%".request()->get("ew_invoice")."%");

                            }

                            if (request()->get('ew_invoice_date',false)) {

                                $query->where('ew_process_dms.ew_invoice_date', "like", "%".request()->get("ew_invoice_date")."%");

                            }

                            

                            if (request()->get('status',false)) {

                                $query->where('obf.status', "like", "%".request()->get("status")."%");

                            }

                            if (request()->get('ew_status',false)) {

                                $query->where('obf.ew_status', "like", "%".request()->get("ew_status")."%");

                            }

                            if (request()->get('dms_invoice_no',false)) {

                                $query->where('ew_process_dms.dms_invoice_no', "like", "%".request()->get("dms_invoice_no")."%");

                            }

                            if (request()->get('dms_invoice_date',false)) {

                                $query->where('ew_process_dms.dms_invoice_date', "like", "%".request()->get("dms_invoice_date")."%");

                            }

                            if (request()->get('dms_gatepass_date',false)) {

                                $query->where('ew_process_dms.dms_gatepass_date', "like", "%".request()->get("dms_gatepass_date")."%");

                            }

                            if (request()->get('dms_location',false)) {

                                $query->where('ew_process_dms.dms_location', "like", "%".request()->get("dms_location")."%");

                            }

                            if (request()->get('dms_ew_create_date',false)) {

                                $query->where('ew_process_dms.dms_ew_create_date', "like", "%".request()->get("dms_ew_create_date")."%");

                            }

                            if (request()->get('dms_ew_certificate',false)) {

                                $query->where('ew_process_dms.dms_ew_certificate', "like", "%".request()->get("dms_ew_certificate")."%");

                            }

                        })

                        ->make(true);

        }

        

        public function EWExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportEWReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }



    //   public function getMCP(Request $request)

    //     {

    //         $vin = $request->input('filter');

    //         $obfRecords = OBF::select(

    //                 'car_model.name AS product', 

    //                 'car_varient.name AS car_varient_name', 

    //                 'obf.status',

    //                 'obf.mcp_status',

    //                 'obf.convinience_program as mcp'

    //             )

    //             ->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('mcp','obf.convinience_program','=','mcp.id')

    //             ->whereNotNull('obf.mcp_status')

    //             ->whereNotNull('obf.convinience_program')

    //             ->groupBy('car_model.name', 'car_varient.name', 'obf.status','obf.mcp_status')

    //             ->when($vin, function ($query) use ($vin) {

    //                 return $query->where('obf.vin', 'like', "%$vin%"); 

    //             })

    //             ->get();

            

    //         return DataTables::of($obfRecords)->make(true);

    //     }

        // CHANGES BY HIRAL

        public function getMCP(Request $request)

            {

                $vin = $request->input('filter');

                $obfRecords = OBF::select(

                        'obf.id as id',

                        'car_model.name AS product', 

                        'car_varient.name AS car_varient_name', 

                        DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)), 

                        LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),

                        'obf.mcp_status',

                        'obf.convinience_program as mcp',

                        'mcp.name AS mcp_name',

                        'mcp.amount AS mcp_amount',

                        'mcp_process_dms.mcp_invoice', 

                        'mcp_process_dms.mcp_invoice_date', 

                        'mcp_process_dms.dms_invoice_no',

                        'mcp_process_dms.dms_invoice_date', 

                        'mcp_process_dms.dms_gatepass_date', 

                        'mcp_process_dms.dms_location', 

                        'mcp_process_dms.dms_mcp_create_date', 

                        'mcp_process_dms.dms_mcp_certificate',

                        DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

                        'Team_master.team_name'

                    )

                    ->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('mcp','obf.convinience_program','=','mcp.id')

                    ->leftJoin('mcp_process_dms', 'obf.id', '=', 'mcp_process_dms.obf_id')

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

                    ->leftjoin('Team_master','Team_master.id','users.team_name')

                    ->whereNotNull('obf.mcp_status')

                    ->whereNotNull('obf.convinience_program')

                    ->whereNotNull('mcp_process_dms.obf_id')

                    ->groupBy(

                        'car_model.name', 

                        'car_varient.name', 

                        'obf.status',

                        'obf.mcp_status',

                        'mcp.name',

                        'mcp.amount',

                        'mcp_process_dms.mcp_invoice',

                        'mcp_process_dms.mcp_invoice_date',

                        'mcp_process_dms.dms_invoice_no',

                        'mcp_process_dms.dms_invoice_date',

                        'mcp_process_dms.dms_gatepass_date',

                        'mcp_process_dms.dms_location',

                        'mcp_process_dms.dms_mcp_create_date',

                        'mcp_process_dms.dms_mcp_certificate')

                    ->when($vin, function ($query) use ($vin) {

                        return $query->where('obf.vin', 'like', "%$vin%"); 

                    });

                

                return DataTables::of($obfRecords)

                                        ->filter(function ($query){

                            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('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('mcp_name',false)) {

                                $query->where('mcp.name', "like", "%".request()->get("mcp_name")."%");

                            }

                            if (request()->get('mcp_amount',false)) {

                                $query->where('mcp.amount', "like", "%".request()->get("mcp_amount")."%");

                            }

                            if (request()->get('mcp_invoice',false)) {

                                $query->where('mcp_process_dms.mcp_invoice', "like", "%".request()->get("mcp_invoice")."%");

                            }

                            if (request()->get('mcp_invoice_date',false)) {

                                $query->where('mcp_process_dms.mcp_invoice_date', "like", "%".request()->get("mcp_invoice_date")."%");

                            }

                            

                            if (request()->get('status',false)) {

                                $query->where('obf.status', "like", "%".request()->get("status")."%");

                            }

                            if (request()->get('mcp_status',false)) {

                                $query->where('obf.mcp_status', "like", "%".request()->get("mcp_status")."%");

                            }

                            if (request()->get('dms_invoice_no',false)) {

                                $query->where('mcp_process_dms.dms_invoice_no', "like", "%".request()->get("dms_invoice_no")."%");

                            }

                            if (request()->get('dms_invoice_date',false)) {

                                $query->where('mcp_process_dms.dms_invoice_date', "like", "%".request()->get("dms_invoice_date")."%");

                            }

                            if (request()->get('dms_gatepass_date',false)) {

                                $query->where('mcp_process_dms.dms_gatepass_date', "like", "%".request()->get("dms_gatepass_date")."%");

                            }

                            if (request()->get('dms_location',false)) {

                                $query->where('mcp_process_dms.dms_location', "like", "%".request()->get("dms_location")."%");

                            }

                            if (request()->get('dms_mcp_create_date',false)) {

                                $query->where('mcp_process_dms.dms_mcp_create_date', "like", "%".request()->get("dms_mcp_create_date")."%");

                            }

                            if (request()->get('dms_mcp_certificate',false)) {

                                $query->where('mcp_process_dms.dms_mcp_certificate', "like", "%".request()->get("dms_mcp_certificate")."%");

                            }

                        })

                        ->make(true);

            }



        public function MCPExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportMCPReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        // public function getRSA(Request $request)

        // {

        //     $vin = $request->input('filter');

    

        //     $obfRecords = OBF::select(

        //             'car_model.name AS product', 

        //             'car_varient.name AS car_varient_name', 

        //             'obf.status',

        //             'obf.rsa_status',

        //             'rsa.name AS rsa_name',

        //             'obf.customer_name',

                    

        //         )

        //         ->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('rsa', 'obf.rsa_master_obf', '=', 'rsa.id')

        //         ->whereNotNull('obf.rsa_status')

        //         ->whereNotNull('rsa.name')   

        //         ->where('rsa.name', '<>', '') 

        //         ->groupBy('car_model.name', 'car_varient.name', 'obf.status', 'obf.rsa_status', 'rsa.name')

        //         ->when($vin, function ($query) use ($vin) {

        //             return $query->where('obf.vin', 'like', "%$vin%");

        //         })

        //         ->get();

            

        //     return DataTables::of($obfRecords)->make(true);



        // }

        // CHANGES BY HIRAL

        public function getRSA(Request $request)

        {

            $vin = $request->input('filter');

    

            $obfRecords = OBF::select(

                    // 'obf.id',

                    'rsa_process_dms.id as id',

                    'car_model.name AS product', 

                    'car_varient.name AS car_varient_name', 

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)), 

                    LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),

                    'obf.rsa_status',

                    'rsa.name AS rsa_name',

                    'obf.customer_name',

                    'rsa.amount AS rsa_amount',

                    'rsa_process_dms.rsa_invoice', 

                    'rsa_process_dms.rsa_invoice_date', 

                    'rsa_process_dms.dms_invoice_no',

                    'rsa_process_dms.dms_invoice_date', 

                    'rsa_process_dms.dms_gatepass_date', 

                    'rsa_process_dms.dms_location', 

                    'rsa_process_dms.dms_rsa_create_date', 

                    'rsa_process_dms.dms_rsa_certificate',

                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

                    'Team_master.team_name'

                    

                )

                ->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('rsa', 'obf.rsa_master_obf', '=', 'rsa.id')

                ->leftJoin('rsa_process_dms', 'obf.id', '=', 'rsa_process_dms.obf_id')

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

                ->leftjoin('Team_master','Team_master.id','users.team_name')

                ->whereNotNull('obf.rsa_master_obf')

                // ->whereNotNull('rsa.name')   

                // ->where('rsa.name', '<>', '') 

                // ->groupBy('car_model.name', 'car_varient.name', 'obf.status', 'obf.rsa_status', 'rsa.name','rsa.amount','rsa_process_dms.rsa_invoice','rsa_process_dms.rsa_invoice_date','rsa_process_dms.dms_invoice_no','rsa_process_dms.dms_invoice_date','rsa_process_dms.dms_gatepass_date','rsa_process_dms.dms_location','rsa_process_dms.dms_rsa_create_date','rsa_process_dms.dms_rsa_certificate')

                ->when($vin, function ($query) use ($vin) {

                    return $query->where('obf.vin', 'like', "%$vin%");

                });

            

            return DataTables::of($obfRecords)

                        ->filter(function ($query){

                            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('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('rsa_name',false)) {

                                $query->where('rsa.name', "like", "%".request()->get("rsa_name")."%");

                            }

                            if (request()->get('rsa_amount',false)) {

                                $query->where('rsa.amount', "like", "%".request()->get("rsa_amount")."%");

                            }

                            if (request()->get('rsa_invoice',false)) {

                                $query->where('rsa_process_dms.rsa_invoice', "like", "%".request()->get("rsa_invoice")."%");

                            }

                            if (request()->get('rsa_invoice_date',false)) {

                                $query->where('rsa_process_dms.rsa_invoice_date', "like", "%".request()->get("rsa_invoice_date")."%");

                            }

                            

                            if (request()->get('status',false)) {

                                $query->where('obf.status', "like", "%".request()->get("status")."%");

                            }

                            if (request()->get('rsa_status',false)) {

                                $query->where('obf.rsa_status', "like", "%".request()->get("rsa_status")."%");

                            }

                            if (request()->get('dms_invoice_no',false)) {

                                $query->where('rsa_process_dms.dms_invoice_no', "like", "%".request()->get("dms_invoice_no")."%");

                            }

                            if (request()->get('dms_invoice_date',false)) {

                                $query->where('rsa_process_dms.dms_invoice_date', "like", "%".request()->get("dms_invoice_date")."%");

                            }

                            if (request()->get('dms_gatepass_date',false)) {

                                $query->where('rsa_process_dms.dms_gatepass_date', "like", "%".request()->get("dms_gatepass_date")."%");

                            }

                            if (request()->get('dms_location',false)) {

                                $query->where('rsa_process_dms.dms_location', "like", "%".request()->get("dms_location")."%");

                            }

                            if (request()->get('dms_rsa_create_date',false)) {

                                $query->where('rsa_process_dms.dms_rsa_create_date', "like", "%".request()->get("dms_rsa_create_date")."%");

                            }

                            if (request()->get('dms_rsa_certificate',false)) {

                                $query->where('rsa_process_dms.dms_rsa_certificate', "like", "%".request()->get("dms_rsa_certificate")."%");

                            }

                        })

                        

                        ->addColumn('dms_rsa_certificate_image', function ($row) {

                            if (!empty($row->dms_rsa_certificate)) {

                                return '<img src="' . asset($row->dms_rsa_certificate) . '" width="100"/>';

                            }

                            return 'No Image';

                        })

                        ->editColumn('rsa_invoice_date', function ($data) {

                            return !empty($data->rsa_invoice_date) ? \Carbon\Carbon::parse($data->rsa_invoice_date)->format('d-m-Y') : '';

                        })

                        ->editColumn('dms_invoice_date', function ($data) {

                            return !empty($data->dms_invoice_date) ? \Carbon\Carbon::parse($data->dms_invoice_date)->format('d-m-Y') : '';

                        })

                        ->editColumn('dms_gatepass_date', function ($data) {

                            return !empty($data->dms_gatepass_date) ? \Carbon\Carbon::parse($data->dms_gatepass_date)->format('d-m-Y') : '';

                        })

                        ->editColumn('dms_rsa_create_date', function ($data) {

                            return !empty($data->dms_rsa_create_date) ? \Carbon\Carbon::parse($data->dms_rsa_create_date)->format('d-m-Y') : '';

                        })



                        ->rawColumns(['dms_rsa_certificate_image'])

                        ->make(true);



        }

        

        public function RSAExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportRSAReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function getCCS(Request $request)

        {

            $vin = $request->input('filter');

    

            $obfRecords = OBF::select(

                    // 'obf.id',

                    'rsa_process_dms.id as id',

                    'car_model.name AS product', 

                    'car_varient.name AS car_varient_name', 

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)), 

                    LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.rsa_status, '_', ' '), 1)), 

                    LOWER(SUBSTRING(REPLACE(obf.rsa_status, '_', ' '), 2))) AS rsa_status"),

                    // 'obf.rsa_status',

                    'ccs.name AS ccs_name',

                    'obf.customer_name',

                    'ccs.amount AS ccs_amount',

                    'rsa_process_dms.rsa_invoice', 

                    'rsa_process_dms.rsa_invoice_date', 

                    'rsa_process_dms.dms_invoice_no',

                    'rsa_process_dms.dms_invoice_date', 

                    'rsa_process_dms.dms_gatepass_date', 

                    'rsa_process_dms.dms_location', 

                    'rsa_process_dms.dms_rsa_create_date', 

                    'rsa_process_dms.dms_rsa_certificate',

                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

                    'Team_master.team_name'

                    

                )

                ->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('rsa as ccs', 'obf.ccs_master_obf', '=', 'ccs.id')

                ->leftJoin('rsa_process_dms', 'obf.id', '=', 'rsa_process_dms.obf_id')

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

                ->leftjoin('Team_master','Team_master.id','users.team_name')

                ->whereNotNull('obf.ccs_master_obf')

                ->when($vin, function ($query) use ($vin) {

                    return $query->where('obf.vin', 'like', "%$vin%");

                });

            

            return DataTables::of($obfRecords)

            ->filter(function ($query){

                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('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('rsa_name',false)) {

                    $query->where('rsa.name', "like", "%".request()->get("rsa_name")."%");

                }

                if (request()->get('rsa_amount',false)) {

                    $query->where('rsa.amount', "like", "%".request()->get("rsa_amount")."%");

                }

                if (request()->get('rsa_invoice',false)) {

                    $query->where('rsa_process_dms.rsa_invoice', "like", "%".request()->get("rsa_invoice")."%");

                }

                if (request()->get('rsa_invoice_date',false)) {

                    $query->where('rsa_process_dms.rsa_invoice_date', "like", "%".request()->get("rsa_invoice_date")."%");

                }

                

                if (request()->get('status',false)) {

                    $query->where('obf.status', "like", "%".request()->get("status")."%");

                }

                if (request()->get('rsa_status',false)) {

                    $query->where('obf.rsa_status', "like", "%".request()->get("rsa_status")."%");

                }

                if (request()->get('dms_invoice_no',false)) {

                    $query->where('rsa_process_dms.dms_invoice_no', "like", "%".request()->get("dms_invoice_no")."%");

                }

                if (request()->get('dms_invoice_date',false)) {

                    $query->where('rsa_process_dms.dms_invoice_date', "like", "%".request()->get("dms_invoice_date")."%");

                }

                if (request()->get('dms_gatepass_date',false)) {

                    $query->where('rsa_process_dms.dms_gatepass_date', "like", "%".request()->get("dms_gatepass_date")."%");

                }

                if (request()->get('dms_location',false)) {

                    $query->where('rsa_process_dms.dms_location', "like", "%".request()->get("dms_location")."%");

                }

                if (request()->get('dms_rsa_create_date',false)) {

                    $query->where('rsa_process_dms.dms_rsa_create_date', "like", "%".request()->get("dms_rsa_create_date")."%");

                }

                if (request()->get('dms_rsa_certificate',false)) {

                    $query->where('rsa_process_dms.dms_rsa_certificate', "like", "%".request()->get("dms_rsa_certificate")."%");

                }

            })

            

            ->addColumn('dms_rsa_certificate_image', function ($row) {

                if (!empty($row->dms_rsa_certificate)) {

                    return '<img src="' . asset($row->dms_rsa_certificate) . '" width="100"/>';

                }

                return 'No Image';

            })

            ->editColumn('rsa_invoice_date', function ($data) {

                return !empty($data->rsa_invoice_date) ? \Carbon\Carbon::parse($data->rsa_invoice_date)->format('d-m-Y') : '';

            })

            ->editColumn('dms_invoice_date', function ($data) {

                return !empty($data->dms_invoice_date) ? \Carbon\Carbon::parse($data->dms_invoice_date)->format('d-m-Y') : '';

            })

            ->editColumn('dms_gatepass_date', function ($data) {

                return !empty($data->dms_gatepass_date) ? \Carbon\Carbon::parse($data->dms_gatepass_date)->format('d-m-Y') : '';

            })

            ->editColumn('dms_rsa_create_date', function ($data) {

                return !empty($data->dms_rsa_create_date) ? \Carbon\Carbon::parse($data->dms_rsa_create_date)->format('d-m-Y') : '';

            })



            ->rawColumns(['dms_rsa_certificate_image'])

            ->make(true);



        }

        

        public function CcsExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportCCSReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        public function getRto(Request $request)

        {

            $vin = $request->input('filter');



            $data = DB::table('obf')

                ->join('obf_rto', 'obf.id', '=', 'obf_rto.obf_id')

                ->leftJoin('rto_process_dms', 'obf.id', '=', 'rto_process_dms.obf_id')

                ->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('users','users.id','=','obf.sales_person_id')

                ->leftjoin('Team_master','Team_master.id','users.team_name')

                ->select(

                    'obf.id as obf_id',

                    'obf.created_at', 

                    'obf.updated_at',

                

                    'obf_rto.id as obf_rto_id',

                    // 'obf_rto.rto_type',

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf_rto.rto_type, '_', ' '), 1)), 

                    LOWER(SUBSTRING(REPLACE(obf_rto.rto_type, '_', ' '), 2))) AS rto_type"),

                    'obf_rto.registration_date',

                    'obf_rto.application_number',

                    'obf_rto.final_amount',

                    'obf_rto.vehicle_number',

                    'obf_rto.temporary_number',

                    'obf.number_plate',

                    'car_model.name AS product', 

                    'car_varient.name AS car_varient_name', 

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)), 

                    LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),

                    'obf.rto_status',

                    'rto_process_dms.rto_invoice',

                    'rto_process_dms.rto_invoice_date',

                    'rto_process_dms.dms_invoice_no',

                    'rto_process_dms.dms_invoice_date',

                    'rto_process_dms.dms_gatepass_date',

                    'rto_process_dms.dms_location',

                    'rto_process_dms.dms_rto_create_date',

                    'rto_process_dms.dms_rto_certificate',

                    'rto_process_dms.status as rto_process_status',

                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

                    'Team_master.team_name'

                )

                ->groupBy('obf.id','obf_rto.id','obf_rto.rto_type','obf_rto.registration_date','obf_rto.application_number','obf_rto.final_amount','obf_rto.vehicle_number','obf.number_plate','car_model.name','car_varient.name','obf.status','obf.rto_status',

                'rto_process_dms.rto_invoice', 'rto_process_dms.rto_invoice_date', 'rto_process_dms.dms_invoice_no','rto_process_dms.dms_invoice_date', 'rto_process_dms.dms_gatepass_date', 'rto_process_dms.dms_location','rto_process_dms.dms_rto_create_date', 'rto_process_dms.dms_rto_certificate', 'rto_process_dms.status','users.first_name',

                'users.last_name')

                ->when($vin, function ($query) use ($vin) {

                    return $query->where('obf.vin', 'like', "%$vin%");

                })/*->get()*/;



            return DataTables::of($data)

                ->filter(function ($query){           

                    if (request()->get('product')) {

                        $query->where('car_model.name', 'like', '%' . request()->get('product') . '%');

                    }

                    if (request()->get('car_varient_name')) {

                        $query->where('car_varient.name', 'like', '%' . request()->get('car_varient_name') . '%');

                    }

                    if (request()->get('status')) {

                        $query->where('obf.status', 'like', '%' . request()->get('status') . '%');

                    }

                    if (request()->get('team_name')) {

                        $query->where('Team_master.team_name', 'like', '%' . request()->get('team_name') . '%');

                    }

                    if (request()->get('sales_person_name')) {

                        $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%" . request()->get('sales_person_name') . "%"]);

                    }

                    if (request()->get('rto_status')) {

                        $query->where('obf_rto.rto_status', 'like', '%' . request()->get('rto_status') . '%');

                    }

                    if (request()->get('rto_type')) {

                        $query->where('obf_rto.rto_type', 'like', '%' . request()->get('rto_type') . '%');

                    }

                    if (request()->get('number_plate')) {

                        $query->where('obf.number_plate', 'like', '%' . request()->get('number_plate') . '%');

                    }

                    if (request()->get('registration_date')) {

                        $query->where('obf_rto.registration_date', 'like', '%' . request()->get('registration_date') . '%');

                    }

                    if (request()->get('application_number')) {

                        $query->where('obf_rto.application_number', 'like', '%' . request()->get('application_number') . '%');

                    }

                    if (request()->get('temporary_number')) {

                        $query->where('obf_rto.temporary_number', 'like', '%' . request()->get('temporary_number') . '%');

                    }

                    if (request()->get('final_amount')) {

                        $query->where('obf_rto.final_amount', 'like', '%' . request()->get('final_amount') . '%');

                    }

                    if (request()->get('vehicle_number')) {

                        $query->where('obf_rto.vehicle_number', 'like', '%' . request()->get('vehicle_number') . '%');

                    }

                    if (request()->get('rto_invoice')) {

                        $query->where('rto_process_dms.rto_invoice', 'like', '%' . request()->get('rto_invoice') . '%');

                    }

                    if (request()->get('rto_invoice_date')) {

                        $query->where('rto_process_dms.rto_invoice_date', 'like', '%' . request()->get('rto_invoice_date') . '%');

                    }

                    if (request()->get('dms_invoice_no')) {

                        $query->where('rto_process_dms.dms_invoice_no', 'like', '%' . request()->get('dms_invoice_no') . '%');

                    }

                    if (request()->get('dms_invoice_date')) {

                        $query->where('rto_process_dms.dms_invoice_date', 'like', '%' . request()->get('dms_invoice_date') . '%');

                    }

                    if (request()->get('dms_gatepass_date')) {

                        $query->where('rto_process_dms.dms_gatepass_date', 'like', '%' . request()->get('dms_gatepass_date') . '%');

                    }

                    if (request()->get('dms_location')) {

                        $query->where('rto_process_dms.dms_location', 'like', '%' . request()->get('dms_location') . '%');

                    }

                    if (request()->get('dms_rto_create_date')) {

                        $query->where('rto_process_dms.dms_rto_create_date', 'like', '%' . request()->get('dms_rto_create_date') . '%');

                    }

                    if (request()->get('dms_rto_certificate')) {

                        $query->where('rto_process_dms.dms_rto_certificate', 'like', '%' . request()->get('dms_rto_certificate') . '%');

                    }

                    if (request()->get('rto_process_status')) {

                        $query->where('rto_process_dms.rto_process_status', 'like', '%' . request()->get('rto_process_status') . '%');

                    }

                })

                ->make(true);

        }

        public function RTOExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportRTOReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function getTransfer(Request $request)

        {

            $vin = $request->input('filter');



            $collection = DB::table('transfer as t')

                ->select(

                    't.id',

                    't.to_branch as to_branch_id',

                    't.from_branch as from_branch_id',

                    'tb.name as to_branch',

                    'fb.name as from_branch',

                    'p.name as product',

                    't.status',

                    'cm.name as cm_name',

                    'cv.name as cv_name',

                    'i.vin_number as vin_number',

                    't.driver_name as d_name',

                    't.driver_lic as d_lic',

                    't.driver_pan as d_pan',

                    't.remark as remark',

                    DB::raw("CASE WHEN t.toolkit = 1 THEN 'Yes' ELSE 'No' END AS tolkit"),

                    DB::raw("CASE WHEN t.medikit = 1 THEN 'Yes' ELSE 'No' END AS medkit"),

                    DB::raw("CASE WHEN t.spare_bulb = 1 THEN 'Yes' ELSE 'No' END AS sparbulb"),

                    DB::raw("CASE WHEN t.hazard_trinagle = 1 THEN 'Yes' ELSE 'No' END AS hzdtringle"),

                    DB::raw("CASE WHEN t.good_condtiton = 1 THEN 'Yes' ELSE 'No' END AS gudcondition"),

                    't.created_at as transfer_date'

                )

                ->leftJoin('branches as tb', 'tb.id', '=', 't.to_branch')

                ->leftJoin('branches as fb', 'fb.id', '=', 't.from_branch')

                ->leftJoin('inventory as i', 'i.id', '=', 't.inventory_id')

                ->leftJoin('products as p', 'p.id', '=', 'i.name')

                ->leftJoin('car_model as cm', 'cm.id', '=', 'p.car_model')

                ->leftJoin('car_varient as cv', 'cv.id', '=', 'p.veriant')

                ->when($vin, function ($query) use ($vin) {

                    return $query->where('i.vin_number', 'like', "%$vin%");

                });

            

            $data = $collection/*->get()*/;

            

            return DataTables::of($data)

                        ->filter(function ($query){

                            if (request()->get('from_branch',false)) {

                                $query->where('fb.name', "like", "%".request()->get("from_branch")."%");

                            }

                            if (request()->get('to_branch',false)) {

                                $query->where('tb.name', "like", "%".request()->get("to_branch")."%");

                            }

                            if (request()->get('cm_name',false)) {

                                $query->where('cm.name', "like", "%".request()->get("cm_name")."%");

                            }

                            if (request()->get('cv_name',false)) {

                                $query->where('cv.name', "like", "%".request()->get("cv_name")."%");

                            }

                            if (request()->get('vin_number',false)) {

                                $query->where('i.vin_number', "like", "%".request()->get("vin_number")."%");

                            }

                            if (request()->get('d_name',false)) {

                                $query->where('t.driver_name', "like", "%".request()->get("d_name")."%");

                            }

                            if (request()->get('d_lic',false)) {

                                $query->where('t.driver_lic', "like", "%".request()->get("d_lic")."%");

                            }

                            if (request()->get('d_pan',false)) {

                                $query->where('t.driver_pan', "like", "%".request()->get("d_pan")."%");

                            }

                            if (request()->get('remark',false)) {

                                $query->where('t.remark', "like", "%".request()->get("remark")."%");

                            }

                            if ($toolkit = request()->get('tolkit')) {

                                $query->havingRaw("tolkit LIKE ?", ["%{$toolkit}%"]);

                            }

                            if ($medikit = request()->get('medkit')) {

                                $query->havingRaw("medkit LIKE ?", ["%{$medikit}%"]);

                            }

                            if ($spareBulb = request()->get('sparbulb')) {

                                $query->havingRaw("sparbulb LIKE ?", ["%{$spareBulb}%"]);

                            }

                            if ($hazardTriangle = request()->get('hzdtringle')) {

                                $query->havingRaw("hzdtringle LIKE ?", ["%{$hazardTriangle}%"]);

                            }

                            if ($goodCondition = request()->get('gudcondition')) {

                                $query->havingRaw("gudcondition LIKE ?", ["%{$goodCondition}%"]);

                            }

                        })

                ->make(true);



        }

        public function transferExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportTransferReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function getInventory(Request $request)

        {

            $data = DB::table('inventory as i')

                ->select('i.id',  'i.name', 'b.name as branch', 'i.veriant','i.inventory_type','i.ex_showroom_price', 'i.status','i.aging_days', 'cv.name as varient_name', 'cm.name as car_name','i.fsc_code','i.vin_number',DB::raw('count(obf.id) as obf_id'),DB::raw('(CASE 

                        WHEN i.status = "allocated" THEN obf.customer_name                         

                        END) AS customer_name'),'i.purchase_price','i.kin_margin','i.manufacturing_year', 'fule_type.title as fuel_type',DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'Team_master.team_name')

                ->leftjoin('branches as b', 'b.id', 'i.branch_id')

                ->leftjoin('products', 'i.name', 'products.id')

                ->leftjoin('car_model as cm', 'cm.id', 'products.car_model')

                ->leftjoin('car_varient as cv', 'cv.id', 'products.veriant')

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

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

                ->leftJoin('obf','obf.product_id','=','i.name')

                ->leftjoin('fule_type','fule_type.id','=','i.fuel_type')

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

                ->leftjoin('Team_master','Team_master.id','users.team_name')

                ->groupBy('i.name')

                // ->orderBy('i.id', 'desc')
                ->orderBy('i.aging_days', 'desc')

                

                ->where('i.status','!=',"allocatedDealer")

                ->where('i.status','!=','deleted')/*->get()*/; 

                

                return Datatables::of($data)

                    ->filter(function ($query){           

                        if (request()->get('car_name')) {

                            $query->where('cm.name', 'like', '%' . request()->get('car_name') . '%');

                        }

                        if (request()->get('varient_name')) {

                            $query->where('cv.name', 'like', '%' . request()->get('varient_name') . '%');

                        }

                        if (request()->get('status')) {

                            $query->where('i.status', 'like', '%' . request()->get('status') . '%');

                        }

                        if (request()->get('vin_number')) {

                            $query->where('i.vin_number', 'like', '%' . request()->get('vin_number') . '%');

                        }

                        if (request()->get('branch')) {

                            $query->where('b.name', 'like', '%' . request()->get('branch') . '%');

                        }

                        if (request()->get('team_name')) {

                            $query->where('Team_master.team_name', 'like', '%' . request()->get('team_name') . '%');

                        }

                        if (request()->get('sales_person_name')) {

                            $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%" . request()->get('sales_person_name') . "%"]);

                        }

                        if (request()->get('ex_showroom_price')) {

                            $query->where('i.ex_showroom_price', 'like', '%' . request()->get('ex_showroom_price') . '%');

                        }

                        if (request()->get('purchase_price')) {

                            $query->where('i.purchase_price', 'like', '%' . request()->get('purchase_price') . '%');

                        }

                        if (request()->get('kin_margin')) {

                            $query->where('i.kin_margin', 'like', '%' . request()->get('kin_margin') . '%');

                        }

                        if (request()->get('fuel_type')) {

                            $query->where('fule_type.title', 'like', '%' . request()->get('fuel_type') . '%');

                        }

                        if (request()->get('customer_name')) {

                            $query->where('obf.customer_name', 'like', '%' . request()->get('customer_name') . '%');

                        }

                        if (request()->get('aging_days')) {

                            $query->where('i.aging_days', 'like', '%' . request()->get('aging_days') . '%');

                        }

                        if (request()->get('inventory_type')) {

                            $query->where('i.inventory_type', 'like', '%' . request()->get('inventory_type') . '%');

                        }

                        if (request()->get('fsc_code')) {

                            $query->where('i.fsc_code', 'like', '%' . request()->get('fsc_code') . '%');

                        }

                    })

                    ->make(true);

        }

        public function InventoryExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportInventoryReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function getPieChart(Request $request)

        {

            $modelCounts = DB::table('car_model')

                ->select('name AS model_name', DB::raw('COUNT(*) as count'))

                ->where('status', 'active')

                ->groupBy('name')

                ->get();

            

            $statusCounts = DB::table('obf')

                ->select('status AS status', DB::raw('COUNT(*) as count'))

                ->groupBy('status')

                ->get();

            

            $varientCounts = DB::table('car_varient')

                ->select('name AS varient_name', DB::raw('COUNT(*) as count'))

                ->groupBy('name')

                ->get();

            

            // Prepare the data for frontend

            $data = [

                'model' => [

                    'modelLabels' => $modelCounts->pluck('model_name')->toArray(),

                    'modelCounts' => $modelCounts->pluck('count')->toArray(),

                ],

                'status' => [

                    'statusLabels' => $statusCounts->pluck('status')->toArray(),

                    'statusCounts' => $statusCounts->pluck('count')->toArray(),

                ],

                'varient' => [

                    'varientLabels' => $varientCounts->pluck('varient_name')->toArray(),

                    'varientCounts' => $varientCounts->pluck('count')->toArray(),

                ],

            ];

            

            return response()->json($data);

        }



        public function model_wise_inventory_chart(){

            $data = DB::table('inventory as i')

                ->select('cm.id AS model_id', 'cm.name AS model_name', DB::raw('COUNT(i.id) AS total_inventory'))

                ->join('products', 'i.name', 'products.id')

                ->join('car_model as cm', 'cm.id', 'products.car_model')

                ->where('i.status','active')

                ->where('cm.status','active')

                ->groupBy('cm.id')

                ->get(); 

            $totalModels = $data->count();

            $totalInventorySum = $data->sum('total_inventory');



            foreach ($data as $key => $value) {

                $value->percentage_value =  number_format(($value->total_inventory / $totalInventorySum) * 100,2);

            }

            return response()->json($data);

        }

        

        public function fuel_type_inventory_chart(){

            $data = DB::table('inventory as i')

                ->select('fule_type.id AS fuel_id', 'fule_type.title AS fuel_name', DB::raw('COUNT(i.id) AS total_inventory'))

                ->join('fule_type', 'i.fuel_type', 'fule_type.id')

                ->where('i.status','active')

                ->where('fule_type.status','active')

                ->groupBy('i.fuel_type')

                ->get();

            $totalModels = $data->count();

            $totalInventorySum = $data->sum('total_inventory');



            foreach ($data as $key => $value) {

                $value->percentage_value =  number_format(($value->total_inventory / $totalInventorySum) * 100,2);

            }

            return response()->json($data);

        } 

        

        public function inventory_type_chart(){

            // $data = DB::table('inventory as i')

            //     ->select('inventory_type.id AS inventory_type_id', 'inventory_type.title AS inventory_type_name', DB::raw('COUNT(i.id) AS total_inventory'))

            //     ->join('inventory_type', 'i.inventory_type', 'inventory_type.id')

            //     ->where('i.status','active')

            //     ->where('inventory_type.status','active')

            //     ->groupBy('i.inventory_type')

            //     ->get();

            $data = DB::table('inventory as i')

                    ->select('i.inventory_type AS inventory_type_name', DB::raw('COUNT(i.id) AS total_inventory'))

                    ->whereNotNull('i.inventory_type')  // Ensure no NULL values

                    ->where('i.status', 'active')

                    ->groupBy('i.inventory_type')

                    ->get();

                

                // Debugging: Check backend response

                \Log::info('Inventory Type Chart Data:', $data->toArray()); // Laravel Log

                

                $totalInventorySum = $data->sum('total_inventory');

                

                foreach ($data as $key => $value) {

                    $value->percentage_value = number_format(($value->total_inventory / $totalInventorySum) * 100, 2);

                }

                

                return response()->json($data);

        }



        public function branches_wise_obf_chart(){

            $data = DB::table('branches as b')

                ->select('b.name',DB::raw('COUNT(obf.id) AS total_inventory'))

                ->leftjoin('obf as obf', 'obf.branch_id', 'b.id')

                ->where('b.status','active')

                ->groupBy('b.id', 'b.name')

                ->get(); 

            $totalModels = $data->count();

            $totalInventorySum = $data->sum('total_inventory');



            foreach ($data as $key => $value) {

                if(!empty($value->total_inventory)) {

                    $value->percentage_value =  number_format(($value->total_inventory / $totalInventorySum) * 100,2);

                } else {

                    $value->percentage_value = 0;

                }

            }

            return response()->json($data);

        }



        public function car_model_wise_obf_chart(){

            $data = DB::table('obf')

                ->select('car_model.name',DB::raw('COUNT(obf.product_id) AS total_inventory'))

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

                ->leftjoin('car_model', 'products.car_model', 'car_model.id')

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

                ->groupBy('car_model.id')

                ->get(); 

            

            /* $data = DB::table('car_model as b')

                ->select('b.name',DB::raw('COUNT(obf.product_id) AS total_inventory'))

                ->leftjoin('obf as obf', 'obf.product_id', 'b.id')

                ->groupBy('b.id', 'b.name')

                ->get();  */

            $totalModels = $data->count();

            $totalInventorySum = $data->sum('total_inventory');



            foreach ($data as $key => $value) {

                if(!empty($value->total_inventory)) {

                    $value->percentage_value =  number_format(($value->total_inventory / $totalInventorySum) * 100,2);

                } else {

                    $value->percentage_value = 0;

                }

            }

            return response()->json($data);

        }



        public function fuel_type_obf_chart(){

            $data = DB::table('obf')

                ->select('fule_type.title as fuel_type_name',DB::raw('COUNT(obf.product_id) AS total_inventory'))

                ->join('fule_type', 'obf.fuel_type', 'fule_type.id')

                ->where('fule_type.status','active')

                ->groupBy('fule_type.id')

                ->get(); 

            $totalModels = $data->count();

            $totalInventorySum = $data->sum('total_inventory');



            foreach ($data as $key => $value) {

                if(!empty($value->total_inventory)) {

                    $value->percentage_value =  number_format(($value->total_inventory / $totalInventorySum) * 100,2);

                } else {

                    $value->percentage_value = 0;

                }

            }

            return response()->json($data);

        }

        

        public function car_wise_inventory_chart()

        {

            try {

                $data = DB::table('inventory as i')

                    ->select('cm.id AS model_id', 'cm.name AS model_name', DB::raw('COUNT(i.id) AS total_inventory'))

                    ->join('products', 'i.name', 'products.id')

                    ->join('car_model as cm', 'cm.id', 'products.car_model')

                    ->where('i.status', 'active')

                    ->where('cm.status', 'active')

                    ->groupBy('cm.id')

                    ->get(); 

    

                if ($data->isEmpty()) {

                    return response()->json(['message' => 'No data found'], 404);

                }

    

                $totalInventorySum = $data->sum('total_inventory');

    

                foreach ($data as $item) {

                    $item->percentage_value = number_format(($item->total_inventory / $totalInventorySum) * 100, 2);

                }

    

                return response()->json($data);

            } catch (\Exception $e) {

                return response()->json(['error' => $e->getMessage()], 500);

            }

        }

        

         public function branches_wise_bar_chart() {

            try {

                $data = DB::table('branches as b')

                    ->select('b.name', DB::raw('COUNT(obf.id) AS total_inventory'))

                    ->leftJoin('obf as obf', 'obf.branch_id', 'b.id')

                    ->where('b.status', 'active')

                    ->groupBy('b.id', 'b.name')

                    ->get();

                

                if ($data->isEmpty()) {

                    return response()->json([], 200); // Return empty array if no data

                }

        

                return response()->json($data, 200);

        

            } catch (\Exception $e) {

               

                return response()->json(['error' => $e->getMessage()], 500);

            }

        }

        

        public function obf_pie_chart()

        {

            $allStatuses = DB::table('obf')->distinct()->pluck('status')->toArray();



            $data = DB::table('obf')

                ->select('status', DB::raw('COUNT(*) as count'))

                ->groupBy('status')

                ->get()

                ->pluck('count', 'status')

                ->toArray();

        

            $result = [];

            foreach ($allStatuses as $status) {

                $result[] = [

                    "status" => $status,

                    "count"  => $data[$status] ?? 0 

                ];

            }

            return response()->json($result);

        }

        

        public function DayBookReport(){

            return view('AllReport.day_book_report');

        }

        

        public function DayBookReportFetch(Request $request)

        {

            if($request->ajax()){

                $day_book = OBF::from('obf as obf')

                    ->leftJoin('branches', 'branches.id', '=', 'obf.branch_id')

                    ->leftJoin('users as us', 'us.id', '=', 'obf.sales_person_id')

                    ->leftJoin('Team_master', 'Team_master.id', '=', 'us.team_name')

                    ->leftJoin('district', 'district.id', '=', 'obf.district_id')

                    ->leftJoin('common_state', 'common_state.id', '=', 'obf.state_id')

                    ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id')

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

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

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

                    ->leftJoin('inventory', 'inventory.id', '=', 'obf.inventory_id')

                    ->leftjoin('pricelist_master','pricelist_master.id','=', 'obf.pricelist_id')

                    ->leftJoin('make_deal', 'make_deal.obf_id', '=', 'obf.id')

                    ->leftJoin('obf_insurance', 'obf.id', '=', 'obf_insurance.obf_id')

                    ->leftJoin('insurance','obf_insurance.company_name', '=', 'insurance.id')

                    ->leftjoin('rsa','rsa.id','=','obf.rsa_master_obf')

                    ->leftjoin('rsa as ccs','ccs.id','=','obf.ccs_master_obf')

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

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

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

                    ->leftJoin('obf_finance', 'obf.id', '=', 'obf_finance.obf_id')

                    ->leftJoin('finance', 'obf_finance.finance_name', '=', 'finance.id')

                    ->leftJoin('obf_rto', 'obf_rto.obf_id', '=', 'obf.id')

                    ->leftJoin('customer_type_master', 'customer_type_master.id', '=', 'obf.customer_type_new')

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

                    ->leftJoin('exchange_purchase', function ($join) {

                        $join->on('exchange_purchase.obf_id', '=', 'obf.id')

                             ->whereIn('exchange_purchase.status', ['active','sell']);

                    })

                    ->leftJoin(DB::raw('(SELECT obf_id, 

                                SUM(CASE WHEN receipt_type = "booking_receipt" AND status != "rejected" THEN amount ELSE 0 END) as booking_amount,

                                SUM(CASE WHEN receipt_type = "downpayment_receipt" AND status != "rejected" THEN amount ELSE 0 END) as dp_amount,

                                SUM(CASE WHEN receipt_type = "disbusment_receipt" AND status != "rejected" THEN amount ELSE 0 END) as finance_discount,

                                SUM(CASE WHEN receipt_type = "access_sort_receipt" AND status != "rejected" THEN amount ELSE 0 END) as access_sort_amount,

                                SUM(CASE WHEN receipt_type = "other_receipt" AND status != "rejected" THEN amount ELSE 0 END) as other_amount

                            FROM cash_receipt

                            GROUP BY obf_id) as cr'), 'cr.obf_id', '=', 'obf.id')

                    ->select(

                        'obf.id',

                        DB::raw('DATE(obf.booking_date) as booking_date'),

                        DB::raw("DATE_FORMAT(orders.invoice_date, '%b-%y') as booking_month_year"),    

                        'obf.customer_name',

                        'obf.company_name',

                        'obf.registration',

                        'obf.einvoicing_applicable',

                        'obf.gst',

                        'obf.ship_to_customer_name',

                        'obf.ship_to_address',

                        'obf.contact_number',

                        'obf.pan_number',

                        'obf.adhar_number',

                        'obf.aadhar_pan_link',

                        'obf.on_road_price',

                        'branches.name AS location',

                        DB::raw("CONCAT(us.first_name,' ',us.last_name) AS kec_name"),

                        'Team_master.team_name as tl_name',

                        'district.name as district_name',

                        'common_state.name as state_name',

                        'obf.customer_type as rto_type',

                        'customer_type_master.name as customer_type_master', 

                        'orders.invoice_date as ibs_invoice_date',

                        'orders.invoice_no as ibs_invoice_no',

                        'car_model.name AS model', 

                        'car_varient.name AS varient', 

                        'fule_type.title as fuel_type',

                        'inventory.vin_number',

                        'inventory.engine_number',

                        DB::raw("CASE WHEN pricelist_master.is_csd = 'No' THEN pricelist_master.ex_showroom_price WHEN pricelist_master.is_csd = 'Yes' THEN (pricelist_master.basic + pricelist_master.gst_amount) END AS ex_showroom_price"),

                        'make_deal.deal_amt as basic',

                        DB::raw('make_deal.gst_tax_deal / 2 as cgst'),

                        DB::raw('make_deal.gst_tax_deal / 2 as sgst'),

                        DB::raw("0 as igst"),

                        'make_deal.gst_tax_deal',

                        'make_deal.cess_tax_deal as cess',

                        'make_deal.tcs_tax_deal as tcs',

                        'make_deal.rto_deal as rto',

                        'make_deal.rto_cutom_handling_charges_deal as rto_custom_handling_charges',

                        'make_deal.municipal_tax_deal as municipal_tax',

                        'make_deal.insurance_deal as insurance',

                        'insurance.name AS insurance_name',

                        'insurance.type AS insurance_type',

                        DB::raw("CASE WHEN rsa.rsa_ccs = 'RSA' THEN rsa.amount ELSE 0 END as rsa"),

                        DB::raw("CASE WHEN ccs.rsa_ccs = 'CCS' THEN ccs.amount ELSE 0 END as ccs"),

                        'extand_warranties.amount as ew',

                        'mcp.amount as mcp',

                        'fasttags.amount as fastag',

                        DB::raw("(IFNULL((SELECT SUM(accessories.price) FROM accessories WHERE FIND_IN_SET(accessories.id, obf.accessory_id)), 0) + IFNULL(obf.other_accesssories_prise, 0)) as accessory_amount"),

                        DB::raw('cr.booking_amount as booking_amount'),

                        DB::raw('cr.dp_amount as dp_amount'),

                        'finance.name AS financer_name',

                        'obf_finance.finance_type',

                        'obf_rto.vehicle_number',

                        DB::raw('cr.finance_discount as finance_discount'),

                        DB::raw('exchange_purchase.total_exchange_amount as exchange_amount'),

                        DB::raw('cr.access_sort_amount as access_sort_amount'),

                        DB::raw('cr.other_amount as other_amount'),

                        DB::raw("0 as refund_amt_process"),

                        DB::raw("0 as refund_amt_date"),

                        DB::raw("0 as refund_diff"),

                        DB::raw("0 as date"),

                        DB::raw("0 as payment_ref_no"),

                        'obf.step1_remarks as remarks',

                        'inventory.kin_invoice_no',

                        'inventory.kin_invoice_date',

                        'inventory.purchase_price',

                        'inventory.manufacturing_year',

                        'pricelist_master.price_list_name',

                        DB::raw("CONCAT(exchange_purchase.company_name, ' - ', exchange_purchase.variant) AS exchange_name"),

                        'exchange_purchase.registration_number',
                        
                        DB::raw("DATEDIFF(orders.invoice_date, obf.booking_date) as tat_days"),

                        DB::raw("
                            CASE 
                                WHEN orders.invoice_date IS NULL THEN 'Pending Invoice'
                        
                                WHEN DATEDIFF(orders.invoice_date, obf.booking_date) BETWEEN 0 AND 10 
                                    THEN 'Within TAT (10 Days)'
                        
                                WHEN DATEDIFF(orders.invoice_date, obf.booking_date) BETWEEN 11 AND 15 
                                    THEN 'Delay (11-15 Days)'
                        
                                WHEN DATEDIFF(orders.invoice_date, obf.booking_date) > 15 
                                    THEN 'Delay (Above 15 Days)'
                        
                                ELSE 'Invalid Date'
                            END as tat_status
                        "), 
                        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"),
                        'obf.way_off as kec_discount',         
                        'obf.tl_discount',
                        'obf.sm_discount',
                        'obf.gm_discount',
                        'obf.bh_discount',
                        'obf.ceo_discount',
                        'obf.md_discount',
                    )

                ->whereNotNull('orders.invoice_no') 

                ->groupBy('obf.id')

                ->orderBy('obf.id', 'DESC');



                

                return Datatables::of($day_book)

                ->order(function ($query) {

                    $query->orderBy('obf.id', 'desc');

                })

                ->addIndexColumn()

                ->editColumn('discount_with_gst', function($data) {

                    $ex_showroom_price = ($data->ex_showroom_price ?? 0);

                    $after_dis_ex_showroom_price = ($data->basic ?? 0) + ($data->gst_tax_deal ?? 0) + ($data->cess ?? 0);

                    $discount_with_gst = $ex_showroom_price - $after_dis_ex_showroom_price;

                    return $discount_with_gst;

                })

                ->editColumn('after_dis_ex_showroom_price', function($data) {

                    $after_dis_ex_showroom_price = ($data->basic ?? 0) + ($data->gst_tax_deal ?? 0) + ($data->cess ?? 0);

                    return $after_dis_ex_showroom_price;

                })

                ->editColumn('total', function($data) {

                    $total = ($data->basic ?? 0) + ($data->gst_tax_deal ?? 0) + ($data->cess ?? 0) + ($data->tcs ?? 0) + ($data->rto ?? 0) + ($data->rto_custom_handling_charges ?? 0) + ($data->municipal_tax ?? 0) + ($data->insurance ?? 0) + ($data->rsa ?? 0) + ($data->css ?? 0) + ($data->ew ?? 0) + ($data->mcp ?? 0) + ($data->fastag ?? 0) + ($data->accessory_amount ?? 0);

                    return $total;

                })

                ->editColumn('total_amt_received', function($data) {

                    $total_amt_received = ($data->booking_amount ?? 0) + ($data->dp_amount ?? 0) + ($data->finance_discount ?? 0) + ($data->exchange_amount ?? 0) + ($data->access_sort_amount ?? 0) + ($data->other_amount ?? 0);

                    return $total_amt_received;

                })

                ->editColumn('refund_amount', function($data) {

                    $total = ($data->basic ?? 0) + ($data->gst_tax_deal ?? 0) + ($data->cess ?? 0) + ($data->tcs ?? 0) + ($data->rto ?? 0) + ($data->rto_custom_handling_charges ?? 0) + ($data->municipal_tax ?? 0) + ($data->insurance ?? 0) + ($data->rsa ?? 0) + ($data->ccs ?? 0) + ($data->ew ?? 0) + ($data->mcp ?? 0) + ($data->fastag ?? 0) + ($data->accessory_amount ?? 0);

                    $total_amt_received = ($data->booking_amount ?? 0) + ($data->dp_amount ?? 0) + ($data->finance_discount ?? 0) + ($data->exchange_amount ?? 0) + ($data->access_sort_amount ?? 0) + ($data->other_amount ?? 0);

                    $refund_amount = ($total ?? 0) - ($total_amt_received ?? 0);

                    return $refund_amount;

                })
                
                ->editColumn('offer_discount', function($data) {
                    $output = [];

                    // KIN OFFERS
                    if(!empty($data->kin_offer_titles)){
                
                        $titles  = explode(',', $data->kin_offer_titles);
                        $amounts = explode(',', $data->kin_offer_amounts);
                
                        foreach($titles as $key => $title){
                
                            $amount = $amounts[$key] ?? '';
                
                            $output[] = $title.' - '.$amount;
                        }
                    }
                
                    // IB OFFERS
                    if(!empty($data->ib_offer_titles)){
                
                        $titles  = explode(',', $data->ib_offer_titles);
                        $amounts = explode(',', $data->ib_offer_amounts);
                
                        foreach($titles as $key => $title){
                
                            $amount = $amounts[$key] ?? '';
                
                            $output[] = $title.' - '.$amount;
                        }
                    }
                
                    return implode(',<br>', $output);
                    
                })
                
                ->addColumn('approval_discount', function($data) {

                    $output = [];
                
                    if(!empty($data->kec_discount))
                        $output[] = 'KEC - '.$data->kec_discount;
                
                    if(!empty($data->tl_discount))
                        $output[] = 'TL - '.$data->tl_discount;
                
                    if(!empty($data->sm_discount))
                        $output[] = 'SM - '.$data->sm_discount;
                
                    if(!empty($data->gm_discount))
                        $output[] = 'GM - '.$data->gm_discount;
                
                    if(!empty($data->bh_discount))
                        $output[] = 'BH - '.$data->bh_discount;
                
                    if(!empty($data->ceo_discount))
                        $output[] = 'CEO - '.$data->ceo_discount;
                
                    if(!empty($data->md_discount))
                        $output[] = 'MD - '.$data->md_discount;
                
                    return implode(',<br>', $output); 
                })
                
                ->addColumn('total_discount', function($data) {

                    $total = 0;
                
                    // KIN OFFERS
                    if(!empty($data->kin_offer_amounts)){
                        $amounts = explode(',', $data->kin_offer_amounts);
                        foreach($amounts as $amount){
                            $total += (float)$amount;
                        }
                    }
                
                    // IB OFFERS
                    if(!empty($data->ib_offer_amounts)){
                        $amounts = explode(',', $data->ib_offer_amounts);
                        foreach($amounts as $amount){
                            $total += (float)$amount;
                        }
                    }
                
                    // Approval Discounts
                    $total += (float)($data->kec_discount ?? 0);
                    $total += (float)($data->tl_discount ?? 0);
                    $total += (float)($data->sm_discount ?? 0);
                    $total += (float)($data->gm_discount ?? 0);
                    $total += (float)($data->bh_discount ?? 0);
                    $total += (float)($data->ceo_discount ?? 0);
                    $total += (float)($data->md_discount ?? 0);
                
                    return $total;
                })
                
                ->editColumn('on_road_discount', function($data) {

                    $total = ($data->basic ?? 0) + ($data->gst_tax_deal ?? 0) + ($data->cess ?? 0) + ($data->tcs ?? 0) + ($data->rto ?? 0) + ($data->rto_custom_handling_charges ?? 0) + ($data->municipal_tax ?? 0) + ($data->insurance ?? 0) + ($data->rsa ?? 0) + ($data->ccs ?? 0) + ($data->ew ?? 0) + ($data->mcp ?? 0) + ($data->fastag ?? 0) + ($data->accessory_amount ?? 0);

                    $on_road_discount = ($data->on_road_price ?? 0) - ($total ?? 0);

                    return $on_road_discount;

                })

                ->editColumn('booking_date', function ($data) {

                     return !empty($data->booking_date) ? \Carbon\Carbon::parse($data->booking_date)->format('d-m-Y') : ''; 

                })

                ->editColumn('ibs_invoice_date', function ($data) {

                     return !empty($data->ibs_invoice_date) ? \Carbon\Carbon::parse($data->ibs_invoice_date)->format('d-m-Y') : ''; 

                })

                ->editColumn('rto_type', function ($data) {

                     return ucwords(str_replace('_',' ',$data->rto_type)); 

                })

                ->editColumn('remarks', function ($data) {

                    $full = htmlspecialchars($data->remarks ?? '', ENT_QUOTES, 'UTF-8');

                    $short = mb_strimwidth($full, 0, 20, '...');

                    return '<span title="'.$full.'">'.$short.'</span>';

                })

                ->rawColumns(['remarks','offer_discount','approval_discount'])

                ->filter(function ($query) {

                    if (request()->get('location', false)) {

                        $query->where('branches.name', 'like', "%" . request()->get("location") . "%");

                    }

                    if (request()->get('kec_name', false)) {

                        $salesPersonName = request()->get('kec_name');

                        $query->whereRaw("CONCAT(us.first_name, ' ', us.last_name) LIKE ?", ["%{$salesPersonName}%"]);

                    }

                    if (request()->get('tl_name', false)) {

                        $query->where('Team_master.team_name', 'like', "%" . request()->get("tl_name") . "%");

                    }

                    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('orders.invoice_date', [$start, $end]);
                                // $query->whereBetween('obf.booking_date', [$start, $end]);

                            } catch (\Exception $e) {

                                \Log::error('Invalid date range format for Booking Date filter', [

                                    'input' => $dateRange,

                                    'error' => $e->getMessage()

                                ]);

                            }

                        }

                    }

                    if (request()->get('price_list_name', false)) {

                        $query->where('pricelist_master.price_list_name', 'like', "%" . request()->get("price_list_name") . "%");

                    }

                    if (request()->get('customer_name', false)) {

                        $query->where('obf.customer_name', 'like', "%" . request()->get("customer_name") . "%");

                    }

                    if (request()->get('company_name', false)) {

                        $query->where('obf.company_name', 'like', "%" . request()->get("company_name") . "%");

                    }

                    if (request()->get('registration', false)) {

                        $query->where('obf.registration', 'like', "%" . request()->get("registration") . "%");

                    }

                    if (request()->get('district_name', false)) {

                        $query->where('district.name', 'like', "%" . request()->get("district_name") . "%");

                    }

                    if (request()->get('state_name', false)) {

                        $query->where('common_state.name', 'like', "%" . request()->get("state_name") . "%");

                    }

                    if (request()->get('einvoicing_applicable', false)) {

                        $query->where('obf.einvoicing_applicable', 'like', "%" . request()->get("einvoicing_applicable") . "%");

                    }

                    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('ship_to_address', false)) {

                        $query->where('obf.ship_to_address', 'like', "%" . request()->get("ship_to_address") . "%");

                    }

                    if (request()->get('rto_type',false)) {

                        $query->where('obf_rto.rto_type', "like", "%".request()->get("rto_type")."%");

                    }

                    if (request()->get('customer_type_master',false)) {

                        $query->where('customer_type_master.name', "like", "%".request()->get("customer_type_master")."%");

                    }

                    if (request()->get('contact_number', false)) {

                        $query->where('obf.contact_number', 'like', "%" . request()->get("contact_number") . "%");

                    }

                    if (request()->get('pan_number', false)) {

                        $query->where('obf.pan_number', 'like', "%" . request()->get("pan_number") . "%");

                    }

                    if (request()->get('adhar_number', false)) {

                        $query->where('obf.adhar_number', 'like', "%" . request()->get("adhar_number") . "%");

                    }

                    if (request()->get('aadhar_pan_link', false)) {

                        $query->where('obf.aadhar_pan_link', 'like', "%" . request()->get("aadhar_pan_link") . "%");

                    }

                    if ($dateRange = request()->get('ibs_invoice_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('orders.invoice_date', [$start, $end]);

                            } catch (\Exception $e) {

                                \Log::error('Invalid date range format for IBS invoice_date filter', [

                                    'input' => $dateRange,

                                    'error' => $e->getMessage()

                                ]);

                            }

                        }

                    }

                    if (request()->get('ibs_invoice_no', false)) {

                        $query->where('orders.invoice_no', 'like', "%" . request()->get("ibs_invoice_no") . "%");

                    }

                    if (request()->get('model', false)) {

                        $query->where('car_model.name', 'like', "%" . request()->get("model") . "%");

                    }

                    if (request()->get('varient', false)) {

                        $query->where('car_varient.name', 'like', "%" . request()->get("varient") . "%");

                    }

                    if (request()->get('vin_number', false)) {

                        $query->where('inventory.vin_number', 'like', "%" . request()->get("vin_number") . "%");

                    }

                    if (request()->get('engine_number', false)) {

                        $query->where('inventory.engine_number', 'like', "%" . request()->get("engine_number") . "%");

                    }

                    if (request()->get('ex_showroom_price', false)) {

                        $query->where('pricelist_master.ex_showroom_price', 'like', "%" . request()->get("ex_showroom_price") . "%");

                    }

                    if ($discount_with_gst = request()->get('discount_with_gst')) {

                        $query->havingRaw("discount_with_gst LIKE ?", ["%{$discount_with_gst}%"]);

                    }

                    if ($after_dis_ex_showroom_price = request()->get('after_dis_ex_showroom_price')) {

                        $query->havingRaw("after_dis_ex_showroom_price LIKE ?", ["%{$after_dis_ex_showroom_price}%"]);

                    }

                    if (request()->get('basic', false)) {

                        $query->where('make_deal.deal_amt', 'like', "%" . request()->get("basic") . "%");

                    }

                    if ($cgst = request()->get('cgst')) {

                        $query->havingRaw("cgst LIKE ?", ["%{$cgst}%"]);

                    }

                    if ($sgst = request()->get('sgst')) {

                        $query->havingRaw("sgst LIKE ?", ["%{$sgst}%"]);

                    }

                    if ($igst = request()->get('igst')) {

                        $query->havingRaw("igst LIKE ?", ["%{$igst}%"]);

                    }

                    if (request()->get('cess', false)) {

                        $query->where('make_deal.cess_tax_deal', 'like', "%" . request()->get("cess") . "%");

                    }

                    if ($after_dis_ex_showroom_price = request()->get('after_dis_ex_showroom_price')) {

                        $query->havingRaw("after_dis_ex_showroom_price LIKE ?", ["%{$after_dis_ex_showroom_price}%"]);

                    }

                    if (request()->get('tcs', false)) {

                        $query->where('make_deal.tcs_tax_deal', 'like', "%" . request()->get("tcs") . "%");

                    }

                    if (request()->get('rto', false)) {

                        $query->where('make_deal.rto_deal', 'like', "%" . request()->get("rto") . "%");

                    }

                    if (request()->get('rto_custom_handling_charges', false)) {

                        $query->where('make_deal.rto_cutom_handling_charges_deal', 'like', "%" . request()->get("rto_custom_handling_charges") . "%");

                    }

                    if (request()->get('municipal_tax', false)) {

                        $query->where('make_deal.municipal_tax_deal', 'like', "%" . request()->get("municipal_tax") . "%");

                    }

                    if (request()->get('insurance', false)) {

                        $query->where('make_deal.insurance_deal', 'like', "%" . request()->get("insurance") . "%");

                    }

                    if (request()->get('insurance_name', false)) {

                        $query->where('insurance.name', 'like', "%" . request()->get("insurance_name") . "%");

                    }

                    if ($rsa = request()->get('rsa')) {

                        $query->havingRaw("rsa LIKE ?", ["%{$rsa}%"]);

                    }

                    if ($ccs = request()->get('ccs')) {

                        $query->havingRaw("ccs LIKE ?", ["%{$ccs}%"]);

                    }

                    if (request()->get('ew', false)) {

                        $query->where('extand_warranties.amount', 'like', "%" . request()->get("ew") . "%");

                    }

                    if (request()->get('mcp', false)) {

                        $query->where('mcp.amount', 'like', "%" . request()->get("mcp") . "%");

                    }

                    if (request()->get('fastag', false)) {

                        $query->where('fasttags.amount', 'like', "%" . request()->get("fastag") . "%");

                    }

                    if ($accessory_amount = request()->get('accessory_amount')) {

                        $query->havingRaw("accessory_amount LIKE ?", ["%{$accessory_amount}%"]);

                    }

                    if ($total = request()->get('total')) {

                        $query->havingRaw("total LIKE ?", ["%{$total}%"]);

                    }

                    if ($booking_amount = request()->get('booking_amount')) {

                        $query->havingRaw("booking_amount LIKE ?", ["%{$booking_amount}%"]);

                    }

                    if ($dp_amount = request()->get('dp_amount')) {

                        $query->havingRaw("dp_amount LIKE ?", ["%{$dp_amount}%"]);

                    }

                    if (request()->get('financer_name', false)) {

                        $query->where('finance.name', 'like', "%" . request()->get("financer_name") . "%");

                    }

                    if (request()->get('finance_type', false)) {

                        $query->where('obf_finance.finance_type', 'like', "%" . request()->get("finance_type") . "%");

                    }

                    if (request()->get('finance_discount', false)) {

                        $query->where('obf_finance.finance_discount', 'like', "%" . request()->get("finance_discount") . "%");

                    }

                    if ($exchange_amount = request()->get('exchange_amount')) {

                        $query->havingRaw("exchange_amount LIKE ?", ["%{$exchange_amount}%"]);

                    }

                    if ($access_sort_amount = request()->get('access_sort_amount')) {

                        $query->havingRaw("access_sort_amount LIKE ?", ["%{$access_sort_amount}%"]);

                    }

                    if ($other_amount = request()->get('other_amount')) {

                        $query->havingRaw("other_amount LIKE ?", ["%{$other_amount}%"]);

                    }

                    if ($total_amt_received = request()->get('total_amt_received')) {

                        $query->havingRaw("total_amt_received LIKE ?", ["%{$total_amt_received}%"]);

                    }

                    if ($refund_amount = request()->get('refund_amount')) {

                        $query->havingRaw("refund_amount LIKE ?", ["%{$refund_amount}%"]);

                    }

                    if ($refund_amt_process = request()->get('refund_amt_process')) {

                        $query->havingRaw("refund_amt_process LIKE ?", ["%{$refund_amt_process}%"]);

                    }

                    if ($refund_amt_date = request()->get('refund_amt_date')) {

                        $query->havingRaw("refund_amt_date LIKE ?", ["%{$refund_amt_date}%"]);

                    }

                    if ($refund_diff = request()->get('refund_diff')) {

                        $query->havingRaw("refund_diff LIKE ?", ["%{$refund_diff}%"]);

                    }

                    if ($date = request()->get('date')) {

                        $query->havingRaw("date LIKE ?", ["%{$date}%"]);

                    }

                    if ($payment_ref_no = request()->get('payment_ref_no')) {

                        $query->havingRaw("payment_ref_no LIKE ?", ["%{$payment_ref_no}%"]);

                    }

                    if (request()->get('on_road_price', false)) {

                        $query->where('obf.on_road_price', 'like', "%" . request()->get("on_road_price") . "%");

                    }

                    if ($total = request()->get('total')) {

                        $query->havingRaw("total LIKE ?", ["%{$total}%"]);

                    }

                    if ($on_road_discount = request()->get('on_road_discount')) {

                        $query->havingRaw("on_road_discount LIKE ?", ["%{$on_road_discount}%"]);

                    }

                    if (request()->get('remarks', false)) {

                        $query->where('obf.step1_remarks', 'like', "%" . request()->get("remarks") . "%");

                    }

                    if (request()->get('kin_invoice_no', false)) {

                        $query->where('inventory.kin_invoice_no', 'like', "%" . request()->get("kin_invoice_no") . "%");

                    }

                    if (request()->get('kin_invoice_date', false)) {

                        $query->where('inventory.kin_invoice_date', 'like', "%" . request()->get("kin_invoice_date") . "%");

                    }

                    if (request()->get('purchase_price', false)) {

                        $query->where('inventory.purchase_price', 'like', "%" . request()->get("purchase_price") . "%");

                    }

                    if (request()->get('manufacturing_year', false)) {

                        $query->where('inventory.manufacturing_year', 'like', "%" . request()->get("manufacturing_year") . "%");

                    }

                    if ($booking_month_year = request()->get('booking_month_year')) {

                        $query->havingRaw("booking_month_year LIKE ?", ["%{$booking_month_year}%"]);

                    }

                    if (request()->get('fuel_type', false)) {

                        $query->where('fule_type.title', 'like', "%" . request()->get("fuel_type") . "%");

                    }
                    
                    if ($tat_days = request()->get('tat_days')) {

                        $query->havingRaw("tat_days LIKE ?", ["%{$tat_days}%"]);

                    }
                    
                    if ($tat_status = request()->get('tat_status')) {

                        $query->havingRaw("tat_status LIKE ?", ["%{$tat_status}%"]);

                    }

                })

                ->make(true);

            }    

            return view('AllReport.day_book_report');

        }

        

        public function daybookExport(Request $request)

        {

            $request->validate([

                'slug' => 'required|string'

            ]);

        

            $slug = $request->input('slug');

            $filename = 'DayBookReport_' . now()->format('YmdHis') . '.xlsx';

            

            $fromDate = null;

            $toDate = null;

        

            if ($request->filter_booking_date) {

                [$from, $to] = array_map('trim', explode('to', $request->filter_booking_date));

        

                $fromDate = \Carbon\Carbon::createFromFormat('d-m-Y', $from)->startOfDay();

                $toDate   = \Carbon\Carbon::createFromFormat('d-m-Y', $to)->endOfDay();

            }

            

            try {

                ExportDayBookReportJob::dispatch($slug, $fromDate, $toDate, auth()->id(), $filename);

        

                return back()->with('success', 'Report generation started. You can download it once ready.');

            } catch (\Exception $e) {

                \Log::error('Daybook Export Dispatch Failed: ' . $e->getMessage());

                return back()->with('error', 'Something went wrong. Please try again.');

            }

        }

        

        public function downloadExportFile($id)

        {

            $today = \Carbon\Carbon::today();



            $oldRecords = \DB::table('excel_exports')

                ->whereDate('created_at', '<', $today)

                ->get();

        

            foreach ($oldRecords as $oldRecord) {

                if ($oldRecord->file_path && \Storage::disk('public')->exists($oldRecord->file_path)) {

                    \Storage::disk('public')->delete($oldRecord->file_path);

                }

                \DB::table('excel_exports')->where('id', $oldRecord->id)->delete();

            }

    

            $record = \DB::table('excel_exports')->find($id);

        

            if (!$record || !\Storage::disk('public')->exists($record->file_path)) {

                abort(404, 'File not found.');

            }

            

            

            

            return \Storage::disk('public')->download($record->file_path, $record->file_name);

        }



        

        public function CashReceiptReport(){ 

            return view('AllReport.cash_receipt_report');

        }

        

        public function CashReceiptReportFetch(Request $request)

        {

            $cash_receipt = CashReceipt::get()->toArray();

            $obf_ids = array_column($cash_receipt, 'obf_id');

            $obf_ids = array_unique($obf_ids);



            $branch_nm = Branch::select('id','name')->get();

            $cust_nm = OBF::select('id','customer_name')->whereIn('id',$obf_ids)->orderBy('customer_name','asc')->get();

            $receipt_type = CashReceipt::select('id','receipt_type')->groupBy('receipt_type')->get();

            $payment_type = CashReceipt::select('id','payment_type')->groupBy('payment_type')->get();

            

            view()->share('branch_nm',$branch_nm);

            view()->share('cust_nm',$cust_nm);

            view()->share('receipt_type',$receipt_type);

            view()->share('payment_type',$payment_type);

            

            if($request->ajax()){

                $start_date = $request->input('start_date');

                $end_date = $request->input('end_date');

                $receipt_type = $request->input('receipt_type');

                $payment_type = $request->input('payment_type');

                $branch_name = $request->input('branch_name');

                $customer_name = $request->input('customer_name');

                

                $receipt_type_map = [

                    'Booking Receipt' => 'booking_receipt',

                    'Downpayment Receipt' => 'downpayment_receipt',

                    'Disbursement Receipt' => 'disbursement_receipt',

                    'Other Receipt' => 'other_receipt',

                ];

            

                if (isset($receipt_type_map[$receipt_type])) {

                    $receipt_type = $receipt_type_map[$receipt_type];

                }

        

                $cash_receipt = CashReceipt::select(

                    'cash_receipt.id',

                    'cash_receipt.obf_id as cash_receipt_obf_id',

                    'obf.id as obf_id',

                    'obf.customer_name as customer_name',

                    'branches.id as branch_id',

                    'branches.name as branch_name',

                    DB::raw("CONCAT(us.first_name,' ',us.last_name) AS kec_name"),

                    'obf.contact_number',

                    DB::raw("DATE_FORMAT(cash_receipt.created_at, '%d-%m-%Y') AS receipt_date"),

                    'cash_receipt.amount as receipt_amount',

                    DB::raw("CASE 

                        WHEN cash_receipt.receipt_type = 'booking_receipt' THEN 'Booking Receipt'

                        WHEN cash_receipt.receipt_type = 'downpayment_receipt' THEN 'Downpayment Receipt'

                        WHEN cash_receipt.receipt_type = 'disbursement_receipt' THEN 'Disbursement Receipt'

                        WHEN cash_receipt.receipt_type = 'other_receipt' THEN 'Other Receipt'

                        ELSE cash_receipt.receipt_type

                    END as receipt_type"),

                    DB::raw("CASE 

                        WHEN cash_receipt.payment_type = 'online_transfer' THEN 'Online Transfer'

                        WHEN cash_receipt.payment_type = 'cash' THEN 'Cash'

                        WHEN cash_receipt.payment_type = 'cheque' THEN 'Cheque'

                        WHEN cash_receipt.payment_type = 'vallet_payment' THEN 'Vallet Payment'

                        ELSE cash_receipt.payment_type

                    END as payment_type"),

                    'bank_account.name as bank_account_no',

                    'finance.name AS hyp',

                    'cash_receipt.transaction_no',

                    'products.id as product_id',

                    'car_model.name as model_name',

                    'car_varient.name as varient_name',

                    DB::raw('(SELECT vin_number FROM inventory WHERE inventory.status = "allocated" AND inventory.id = obf.inventory_id) as vin_number'),

                    DB::raw("CONCAT(exteriorcolor.name, ' | ', interiorcolor.name) as combined_color"),

                    DB::raw("CONCAT(UCASE(LEFT(cash_receipt.status, 1)), LCASE(SUBSTRING(cash_receipt.status, 2))) as status"),

                    'cash_receipt.cash_remark',

                )

                ->join('obf', 'cash_receipt.obf_id', 'obf.id')

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

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

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

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

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

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

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

                ->leftjoin('Team_master','Team_master.id','us.team_name')

                ->leftjoin('inventory', 'inventory.name', '=', 'products.id')

                ->leftjoin('bank_account', 'bank_account.id', 'cash_receipt.bank_account_id')

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

                ->leftjoin('finance', 'obf_finance.finance_name', 'finance.id')

                ->where('cash_receipt.status','accepted')

                ->when($start_date && $end_date, function ($query) use ($start_date, $end_date) {

                    return $query->whereBetween('cash_receipt.created_at', [$start_date, $end_date]);

                })

                ->when($receipt_type, function ($query) use ($receipt_type) {

                    return $query->where('cash_receipt.receipt_type', $receipt_type);

                })

                ->when($payment_type, function ($query) use ($payment_type) {

                    return $query->where('cash_receipt.payment_type', $payment_type);

                })

                ->when($branch_name, function ($query) use ($branch_name) {

                    return $query->where('branches.id', $branch_name);

                })

                ->when($customer_name, function ($query) use ($customer_name) {

                    return $query->where('obf.id', $customer_name);

                })

                ->groupBy('cash_receipt.id');

                

                return DataTables::of($cash_receipt)

                ->editColumn('receipt_no', function ($cash_receipt) {

                    $cash_receipt_id = $cash_receipt->id ?? '';

                    if(!empty($cash_receipt_id)){

                        $month = Carbon::now()->format('m');

                        $year = Carbon::now()->format('Y');

                        

                        $branch_full = $cash_receipt->branch_name ?? ''; // ensure 'branch_name' is available

                        $b_name = '';

        

                        if (str_contains($branch_full, 'Rajkot')) {

                            $b_name = 'RJT';

                        } elseif (str_contains($branch_full, 'Jamnagar')) {

                            $b_name = 'Jam';

                        } elseif (str_contains($branch_full, 'Junagadh')) {

                            $b_name = 'Juna';

                        } elseif (str_contains($branch_full, 'Morbi')) {

                            $b_name = 'Mor';

                        }

                        return $cash_receipt_id . $b_name . $month . $year;   

                    } else {

                        return '';

                    }

                })    

                        ->filter(function ($query){

                            if (request()->get('branch_name',false)) {

                                $query->where('branches.name', "like", "%".request()->get("branch_name")."%");

                            }

                            if (request()->get('kec_name',false)) {

                                $kecName = request()->get('kec_name');

                                $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%{$kecName}%"]);

                            }

                            if (request()->get('customer_name',false)) {

                                $query->where('obf.customer_name', "like", "%".request()->get("customer_name")."%");

                            }

                            if (request()->get('contact_number',false)) {

                                $query->where('obf.contact_number', "like", "%".request()->get("contact_number")."%");

                            }

                            if (request()->get('receipt_date',false)) {

                                $query->where('cash_receipt.created_at', "like", "%".request()->get("receipt_date")."%");

                            }

                            if (request()->get('receipt_no',false)) {

                                $receipt = request()->get('receipt_no');



                                $query->whereHas('cashReceipts', function ($q) use ($receipt) {

                                    $q->where('id', 'like', "%$receipt%");

                                });

                            }

                            if (request()->get('receipt_amount',false)) {

                                $query->where('cash_receipt.amount', "like", "%".request()->get("receipt_amount")."%");

                            }

                            if (request()->get('receipt_type',false)) {

                                $query->where('cash_receipt.receipt_type', "like", "%".request()->get("receipt_type")."%");

                            }

                            if (request()->get('payment_type',false)) {

                                $query->where('cash_receipt.payment_type', "like", "%".request()->get("payment_type")."%");

                            }

                            

                            if (request()->get('bank_account_no',false)) {

                                $query->where('bank_account.name', "like", "%".request()->get("bank_account_no")."%");

                            }

                            if (request()->get('hyp',false)) {

                                $query->where('finance_name', "like", "%".request()->get("hyp")."%");

                            }

                            if (request()->get('transaction_no',false)) {

                                $query->where('cash_receipt.transaction_no', "like", "%".request()->get("transaction_no")."%");

                            }

                            if (request()->get('model_name',false)) {

                                $query->where('car_model.name', "like", "%".request()->get("model_name")."%");

                            }

                            if (request()->get('varient_name',false)) {

                                $query->where('car_varient.name', "like", "%".request()->get("varient_name")."%");

                            }

                            if (request()->get('vin_number',false)) {

                                $query->where('inventory.vin_number', "like", "%".request()->get("vin_number")."%");

                            }

                            if ($combinedColor = request()->get('combined_color')) {

                                $query->whereRaw("CONCAT(exteriorcolor.name, ' | ', interiorcolor.name) LIKE ?", ["%$combinedColor%"]);

                            }

                            if (request()->get('status',false)) {

                                $query->where('cash_receipt.status', "like", "%".request()->get("status")."%");

                            }

                            if (request()->get('cash_remark',false)) {

                                $query->where('cash_receipt.cash_remark', "like", "%".request()->get("cash_remark")."%");

                            }

                        })   

                ->make(true);

            }

            return view('AllReport.cash_receipt_report');

        }

        public function cashreceiptExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }

            

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



            try {

                return Excel::download(new ExportCashReceiptReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function CancelReasonReport(){

            return view('AllReport.cancel_reason_report');

        }



        public function CancelReasonReportFetch(Request $request){

            $obfRecords = OBF::select(

                    'car_model.name AS product', 

                    'car_varient.name AS car_varient_name', 

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)), 

                    LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),

                    'inventory.vin_number',

                    'obf.on_road_price',

                    'Team_master.team_name',

                    'obf.customer_name',

                    'obf.booking_date',

                    'cancellation.name as cancel_reason',

                    'obf.cancel_remark',

                    'branches.name AS branch_name',

                    DB::raw("CONCAT(us.first_name,' ',us.last_name) AS kec_name")

                )

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

                ->leftJoin('branches', 'obf.branch_id', '=', 'branches.id')

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

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

                ->leftjoin('Team_master','Team_master.id','us.team_name')

                ->join('inventory', 'inventory.name', '=', 'products.id')

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

                ->leftJoin('cancellation', 'cancellation.id', '=', 'obf.cancel_reason')

                ->where('obf.status', 'cancel');

            

            return DataTables::of($obfRecords)

                                    ->filter(function ($query){

                            if (request()->get('customer_name',false)) {

                                $query->where('obf.customer_name', "like", "%".request()->get("customer_name")."%");

                            }

                            if (request()->get('branch_name',false)) {

                                $query->where('branches.name', "like", "%".request()->get("branch_name")."%");

                            }

                            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('vin_number',false)) {

                                $query->where('inventory.vin_number', "like", "%".request()->get("vin_number")."%");

                            }

                            if (request()->get('team_name',false)) {

                                $query->where('Team_master.team_name', "like", "%".request()->get("team_name")."%");

                            }

                            if (request()->get('kec_name',false)) {

                                $kecName = request()->get('kec_name');

                                $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%{$kecName}%"]);

                            }

                            if (request()->get('on_road_price',false)) {

                                $query->where('obf.on_road_price', "like", "%".request()->get("on_road_price")."%");

                            }

                            if (request()->get('booking_date',false)) {

                                $query->where('obf.booking_date', "like", "%".request()->get("booking_date")."%");

                            }

                            if (request()->get('status',false)) {

                                $query->where('obf.status', "like", "%".request()->get("status")."%");

                            }

                            if (request()->get('cancel_reason',false)) {

                                $query->where('cancellation.name', "like", "%".request()->get("cancel_reason")."%");

                            }

                            if (request()->get('cancel_remark',false)) {

                                $query->where('obf.cancel_remark', "like", "%".request()->get("cancel_remark")."%");

                            }                        

                        })

                        ->make(true);

        }

         

        public function CancelReasonReportExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportCancelReasonReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function MakeDealReport(){ 

            return view('AllReport.make_deal_report');

        }

        

        public function MakeDealReportFetch(Request $request)

        {

            

            $make_deal = MakeDeal::select(

                'make_deal.id',

                'make_deal.obf_id as make_deal_obf_id',

                'obf.id as obf_id',

                'obf.booking_date',

                'obf.customer_name as customer_name',

                'obf.on_road_price',

                'branches.name as branch_name',

                'products.id as product_id',

                'car_model.name as model_name',

                'car_varient.name as varient_name',

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

                'inventory.vin_number',

                'Team_master.team_name',

                DB::raw("CONCAT(us.first_name,' ',us.last_name) AS kec_name"),

                DB::raw("DATE_FORMAT(make_deal.created_at, '%d-%m-%Y') AS created_date"),

            )

            ->join('obf', 'make_deal.obf_id', 'obf.id')

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

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

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

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

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

            ->leftjoin('Team_master','Team_master.id','us.team_name')

            ->join('inventory', 'inventory.name', '=', 'products.id')

            ->groupBy(

                'obf.customer_name',

            );

            

            return DataTables::of($make_deal)

            ->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('customer_name',false)) {

                        $query->where('obf.customer_name', "like", "%".request()->get("customer_name")."%");

                    }

                    if (request()->get('branch_name',false)) {

                        $query->where('branches.name', "like", "%".request()->get("branch_name")."%");

                    }

                    if (request()->get('vin_number',false)) {

                        $query->where('inventory.vin_number', "like", "%".request()->get("vin_number")."%");

                    }

                    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('gst_tax_deal',false)) {

                        $query->where('make_deal.gst_tax_deal', "like", "%".request()->get("gst_tax_deal")."%");

                    }

                    if (request()->get('cess_tax_deal',false)) {

                        $query->where('make_deal.cess_tax_deal', "like", "%".request()->get("cess_tax_deal")."%");

                    }

                    if (request()->get('tcs_tax_deal',false)) {

                        $query->where('make_deal.tcs_tax_deal', "like", "%".request()->get("tcs_tax_deal")."%");

                    }

                    if (request()->get('municipal_tax_deal',false)) {

                        $query->where('make_deal.municipal_tax_deal', "like", "%".request()->get("municipal_tax_deal")."%");

                    }

                    if (request()->get('rto_deal',false)) {

                        $query->where('make_deal.rto_deal', "like", "%".request()->get("rto_deal")."%");

                    }

                })

                ->make(true);

        }

        

        public function BookingReportFetch(Request $request)

        {

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

                    DB::raw("DATE_FORMAT(obf.booking_date, '%b-%y') as booking_month_year"),

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

                    'obf.contact_number',

                    'pricelist_master.ex_showroom_price',

                    'car_varient.name AS car_varient_name',
                    
                    'fule_type.title as fuel_type',

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

                    'tex_master.gst as gst_master',

                    'tex_master.compensation_cess as compensation_cess_master',
                    
                    DB::raw("
                        CASE 
                            WHEN orders.invoice_date IS NULL THEN 'Pending Invoice'
                    
                            WHEN DATEDIFF(orders.invoice_date, obf.booking_date) BETWEEN 0 AND 10 
                                THEN 'Within TAT (10 Days)'
                    
                            WHEN DATEDIFF(orders.invoice_date, obf.booking_date) BETWEEN 11 AND 15 
                                THEN 'Delay (11-15 Days)'
                    
                            WHEN DATEDIFF(orders.invoice_date, obf.booking_date) > 15 
                                THEN 'Delay (Above 15 Days)'
                    
                            ELSE 'Invalid Date'
                        END as tat_status
                    "), 
                    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"),
                    'obf.way_off as kec_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('fule_type', 'fule_type.id', '=', 'obf.fuel_type')

                ->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('pricelist_master', 'pricelist_master.id', '=', 'obf.pricelist_id')

                ->leftJoinSub($cashSummary, 'cash_summary', 'cash_summary.obf_id', '=', 'obf.id')

                ->leftJoinSub($exchangeSummary, 'exchange', 'exchange.obf_id', '=', 'obf.id')

                ->leftJoin('tex_master','tex_master.id','car_varient.tex_master_id')

                ->where('obf.status','!=','delete');    

                $data->groupBy('obf.id');

                $data->orderByDesc('obf.id');

                    

                return Datatables::of($data)

                ->addIndexColumn()

    

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

                })

                ->editColumn('finance_discount',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);

                    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('offer_discount', function($data) {
                    $output = [];

                    // KIN OFFERS
                    if(!empty($data->kin_offer_titles)){
                
                        $titles  = explode(',', $data->kin_offer_titles);
                        $amounts = explode(',', $data->kin_offer_amounts);
                
                        foreach($titles as $key => $title){
                
                            $amount = $amounts[$key] ?? '';
                
                            $output[] = $title.' - '.$amount;
                        }
                    }
                
                    // IB OFFERS
                    if(!empty($data->ib_offer_titles)){
                
                        $titles  = explode(',', $data->ib_offer_titles);
                        $amounts = explode(',', $data->ib_offer_amounts);
                
                        foreach($titles as $key => $title){
                
                            $amount = $amounts[$key] ?? '';
                
                            $output[] = $title.' - '.$amount;
                        }
                    }
                
                    return implode(',<br>', $output);
                    
                })
                
                ->addColumn('approval_discount', function($data) {

                    $output = [];
                
                    if(!empty($data->kec_discount))
                        $output[] = 'KEC - '.$data->kec_discount;
                
                    if(!empty($data->tl_discount))
                        $output[] = 'TL - '.$data->tl_discount;
                
                    if(!empty($data->sm_discount))
                        $output[] = 'SM - '.$data->sm_discount;
                
                    if(!empty($data->gm_discount))
                        $output[] = 'GM - '.$data->gm_discount;
                
                    if(!empty($data->bh_discount))
                        $output[] = 'BH - '.$data->bh_discount;
                
                    if(!empty($data->ceo_discount))
                        $output[] = 'CEO - '.$data->ceo_discount;
                
                    if(!empty($data->md_discount))
                        $output[] = 'MD - '.$data->md_discount;
                
                    return implode(',<br>', $output); 
                })
                
                ->addColumn('total_discount', function($data) {

                    $total = 0;
                
                    // KIN OFFERS
                    if(!empty($data->kin_offer_amounts)){
                        $amounts = explode(',', $data->kin_offer_amounts);
                        foreach($amounts as $amount){
                            $total += (float)$amount;
                        }
                    }
                
                    // IB OFFERS
                    if(!empty($data->ib_offer_amounts)){
                        $amounts = explode(',', $data->ib_offer_amounts);
                        foreach($amounts as $amount){
                            $total += (float)$amount;
                        }
                    }
                
                    // Approval Discounts
                    $total += (float)($data->kec_discount ?? 0);
                    $total += (float)($data->tl_discount ?? 0);
                    $total += (float)($data->sm_discount ?? 0);
                    $total += (float)($data->gm_discount ?? 0);
                    $total += (float)($data->bh_discount ?? 0);
                    $total += (float)($data->ceo_discount ?? 0);
                    $total += (float)($data->md_discount ?? 0);
                
                    return $total;
                })

                ->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('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','offer_discount','approval_discount'])

                ->filter(function ($query) {

                    $filters = request()->get('filters', []);
                    $booking_status_filter = request()->get('booking_status_filter');
                
                    // ðŸ”¹ Booking Date Range
                    if (!empty($filters['booking_date'])) {
                        $dates = explode(' to ', $filters['booking_date']);
                
                        if (count($dates) === 2) {
                            try {
                                $start = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[0]))->startOfDay();
                                $end   = \Carbon\Carbon::createFromFormat('d-m-Y', trim($dates[1]))->endOfDay();
                
                                $query->whereBetween('obf.booking_date', [$start, $end]);
                            } catch (\Exception $e) {
                                \Log::error('Invalid booking_date', ['input' => $filters['booking_date']]);
                            }
                        }
                    }
                
                    // ðŸ”¹ Simple WHERE filters
                    $likeFilters = [
                        'branch_name' => 'branches.name',
                        'customer_name' => 'obf.customer_name',
                        'gst' => 'obf.gst',
                        'ship_to_customer_name' => 'obf.ship_to_customer_name',
                        'team_name' => 'Team_master.team_name',
                        'product' => 'car_model.name',
                        'car_varient_name' => 'car_varient.name',
                        'exterior_color' => 'exteriorcolor.name',
                        'vin_number' => 'inventory.vin_number',
                        'on_road_price' => 'obf.on_road_price',
                        'loan_amount' => 'obf_finance.loan_amount',
                        'net_disbusment' => 'obf_finance.net_disbusment',
                        'total_exchange_amount' => 'exchange_purchase.total_exchange_amount',
                        'status' => 'obf.status',
                        'approval_status' => 'obf.approval_status',
                        'invoice_no' => 'orders.invoice_no',
                        'invoice_date' => 'orders.invoice_date',
                    ];
                
                    foreach ($likeFilters as $key => $column) {
                        if (!empty($filters[$key])) {
                            $query->where($column, 'like', '%' . $filters[$key] . '%');
                        }
                    }
                
                    // ðŸ”¹ Sales Person (CONCAT)
                    if (!empty($filters['sales_person_name'])) {
                        $query->whereRaw(
                            "CONCAT(users.first_name, ' ', users.last_name) LIKE ?",
                            ["%" . $filters['sales_person_name'] . "%"]
                        );
                    }
                
                    // ðŸ”¹ HAVING filters (calculated fields)
                    $havingFilters = [
                        'booking_month_year' => 'booking_month_year',
                        'booking_amount' => 'booking_amount',
                        'dp_amount' => 'dp_amount',
                        'final_total' => 'final_total',
                        'net_total' => 'net_total',
                        'access_sort_amount' => 'access_sort_amount',
                        'due_amount' => 'due_amount',
                    ];
                
                    foreach ($havingFilters as $key => $column) {
                        if (!empty($filters[$key])) {
                            $query->havingRaw("$column LIKE ?", ["%" . $filters[$key] . "%"]);
                        }
                    }
                
                    // ðŸ”¹ Special CAST filter
                    if (!empty($filters['finance_discount'])) {
                        $query->havingRaw(
                            "CAST(total_finance_discount AS CHAR) LIKE ?",
                            ["%" . $filters['finance_discount'] . "%"]
                        );
                    }
                    
                    // ✅ DORMANT BOOKING
                    if ($booking_status_filter == 'dormant') {
                
                        $date = Carbon::now()->subDays(45)->format('Y-m-d');
                
                        $query->whereDate('obf.booking_date', '<=', $date)
                              ->whereNull('orders.invoice_no') 
                              ->whereNull('orders.invoice_date');
                    }
                
                    // ✅ ACTIVE (includes dormant also)
                    if ($booking_status_filter == 'active') {
                
                        $query->where(function ($q) {
                            $q->where('obf.status', '!=', 'refund_process')
                              ->orWhereNull('obf.status');
                        });
                    }
                
                    // ✅ REFUND (previous reject)
                    if ($booking_status_filter == 'refund') {
                
                        $query->where('obf.status', 'refund_process');
                    }
                
                })->make(true);

            }

            return view('AllReport.bookingreport');

        }

        

        public function bookingreportExport(Request $request){
            if(isset($request->slug) && $request->slug != null){
    
                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportBookingReport($slug), $name);

            }catch(\Exception $e){

                dd($e);

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        

        public function BookingRetailReport(Request $request){

            return view('AllReport.booking_retail_report');

        }

        public function BookingRetailReportFetch(Request $request)

        {

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



            $data = DB::table('obf')

                ->select(

                    'obf.id',

                    'obf.customer_name',

                    'obf.booking_date',

                    'branches.name AS branch_name',

                    'obf.gst',

                    'Team_master.team_name',

                    DB::raw("CONCAT(users.first_name, ' ', users.last_name) AS sales_person_name"),

                    'car_model.name AS product',

                    'car_varient.name AS car_varient_name',

                    'exteriorcolor.name AS exterior_color',

                    'inventory.vin_number',

                    'obf.on_road_price',

                    'obf.ex_showroom_price',

                    DB::raw("(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'booking_receipt') as booking_amount"),

                    DB::raw("(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'downpayment_receipt') as dp_amount"),

                    'obf_finance.loan_amount',

                    'obf_finance.net_disbusment',

                    'exchange_purchase.total_exchange_amount',

                    DB::raw("(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id) as received_amount"),

                    'obf_finance.finance_discount',

                    DB::raw("(obf.on_road_price - IFNULL((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id), 0)) as due_amount"),

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)), LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),



                    // Inventory Info

                    'car_model.name as car_name',

                    'car_varient.name as variant',

                    'inventory.inventory_type',

                    'inventory.status as inventory_status',

                    DB::raw("DATEDIFF(inventory.allocation_date, obf.booking_date) as aging_days"),

                    'inventory.purchase_price',

                    'inventory.kin_margin',

                    'inventory.manufacturing_year',

                    'fule_type.title as fuel_type'

                )

                ->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('orders', 'orders.obf_id', '=', 'obf.id')

                ->leftJoin('inventory', function ($join) {

                    $join->on('inventory.id', '=', 'obf.inventory_id')

                        ->where('inventory.status', '=', 'allocated');

                })

                ->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('exchange_purchase', 'exchange_purchase.obf_id', '=', 'obf.id')

                ->leftJoin('fule_type', 'fule_type.id', '=', 'inventory.fuel_type')

                ->whereNotNull('inventory.id') 

                ->groupBy(

                    'obf.id',

                    'obf.customer_name',

                    'obf.booking_date',

                    'branches.name',

                    'obf.gst',

                    'Team_master.team_name',

                    'users.first_name',

                    'users.last_name',

                    'car_model.name',

                    'car_varient.name',

                    'exteriorcolor.name',

                    'inventory.vin_number',

                    'obf.on_road_price',

                    'obf_finance.loan_amount',

                    'obf_finance.net_disbusment',

                    'exchange_purchase.total_exchange_amount',

                    'obf_finance.finance_discount',

                    'obf.status',

                    'inventory.inventory_type',

                    'inventory.status',

                    'inventory.created_at',

                    'obf.booking_date',

                    'inventory.purchase_price',

                    'inventory.kin_margin',

                    'inventory.manufacturing_year',

                    'fule_type.title'

                )

                ->orderBy('obf.id', 'desc');



            return DataTables::of($data)

            ->filter(function ($query) use ($request) {

                        if ($request->get('car_name', false)) {

                            $query->where('car_model.name', 'like', '%' . $request->get('car_name') . '%');

                        }

                        if ($request->get('variant', false)) {

                            $query->where('car_varient.name', 'like', '%' . $request->get('variant') . '%');

                        }

                        if ($request->get('branch_name', false)) {

                            $query->where('branches.name', 'like', '%' . $request->get('branch_name') . '%');

                        }

                        if ($request->get('ex_showroom_price', false)) {

                            $query->where('obf.ex_showroom_price', 'like', '%' . $request->get('ex_showroom_price') . '%');

                        }

                        if ($request->get('purchase_price', false)) {

                            $query->where('inventory.purchase_price', 'like', '%' . $request->get('purchase_price') . '%');

                        }

                        if ($request->get('kin_margin', false)) {

                            $query->where('inventory.kin_margin', 'like', '%' . $request->get('kin_margin') . '%');

                        }

                        if ($request->get('fuel_type', false)) {

                            $query->where('fule_type.title', 'like', '%' . $request->get('fuel_type') . '%');

                        }

                        if ($request->get('vin_number', false)) {

                            $query->where('inventory.vin_number', 'like', '%' . $request->get('vin_number') . '%');

                        }

                        if ($request->get('inventory_type', false)) {

                            $query->where('inventory.inventory_type', 'like', '%' . $request->get('inventory_type') . '%');

                        }

                        if ($request->get('inventory_status', false)) {

                            $query->where('inventory.inventory_status', 'like', '%' . $request->get('inventory_status') . '%');

                        }

                        if ($request->get('aging_days', false)) {

                            $query->havingRaw("DATEDIFF(inventory.allocation_date, obf.booking_date) LIKE ?", ['%' . $request->get('aging_days') . '%']);

                        }

                        if ($request->get('booking_date', false)) {

                            $query->where('obf.booking_date', 'like', '%' . $request->get('booking_date') . '%');

                        }

                        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('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('exterior_color', false)) {

                            $query->where('exteriorcolor.name', 'like', '%' . $request->get('exterior_color') . '%');

                        }

                        if ($request->get('on_road_price', false)) {

                            $query->where('obf.on_road_price', 'like', '%' . $request->get('on_road_price') . '%');

                        }

                        if ($request->get('booking_amount')) {

                            $query->havingRaw("(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'booking_receipt') LIKE ?", ["%" . $request->get('booking_amount') . "%"]);

                        }

                        if ($request->get('dp_amount')) {

                            $query->havingRaw("(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'downpayment_receipt') LIKE ?", ["%" . $request->get('dp_amount') . "%"]);

                        }

                        if ($request->get('loan_amount')) {

                            $query->where('obf_finance.loan_amount', 'like', '%' . $request->get('loan_amount') . '%');

                        }

                        if ($request->get('net_disbusment')) {

                            $query->where('obf_finance.net_disbusment', 'like', '%' . $request->get('net_disbusment') . '%');

                        }

                        if ($request->get('total_exchange_amount')) {

                            $query->where('exchange_purchase.total_exchange_amount', 'like', '%' . $request->get('total_exchange_amount') . '%');

                        }

                        if ($request->get('total_received_amount')) {

                            $query->havingRaw("total_received_amount LIKE ?", ["%" . $request->get('total_received_amount') . "%"]);

                        }

                        if ($request->get('finance_discount')) {

                            $query->where('obf_finance.finance_discount', 'like', '%' . $request->get('finance_discount') . '%');

                        }

                        if ($request->get('net_amount_received')) {

                            $query->havingRaw("net_amount_received LIKE ?", ["%" . $request->get('net_amount_received') . "%"]);

                        }

                        if ($request->get('due_amount')) {

                            $query->havingRaw("(obf.on_road_price - IFNULL((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id), 0)) LIKE ?", ["%" . $request->get('due_amount') . "%"]);

                        }

                        if ($request->get('status', false)) {

                            $query->where('obf.status', 'like', '%' . $request->get('status') . '%');

                        }

                    })

                    ->make(true);

        }

        // public function MakeDealExport(Request $request){

        //     if(isset($request->slug) && $request->slug != null){

        //         $slug = $request->slug;

        //     }else{

        //         $slug = 'all';

        //     }



        //     $name = 'MakeDealReport_'.Date('YmdHis').'.xlsx';



        //     try {

        //         return Excel::download(new ExportCancelReasonReport($slug), $name);

        //     }catch(\Exception $e){

        //         return redirect()->back()->with('error' ,$e->getMessage());

        //     }

        // }

        

        public function MunicipleTaxReportFetch(Request $request)

        {

            $vin = $request->input('vin');



            $obfRecords = OBF::query()

                ->select(

                    'obf.id',

                    'car_model.name as model_name',

                    'car_varient.name as variant_name',

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.status, '_', ' '), 1)), 

                     LOWER(SUBSTRING(REPLACE(obf.status, '_', ' '), 2))) AS status"),

                    'inventory.vin_number',

                    'exteriorcolor.name as exterior_color',

                    'interiorcolor.name as interior_color',

                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

                    'Team_master.team_name',

                    'obf_municiple_tax.rmc_receipt_no',

                    'obf_municiple_tax.tax_type',

                    'obf_municiple_tax.remarks',

                    'obf_municiple_tax.municiple_date',

                    'obf_municiple_tax.status as municiple_status'

                )

                ->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('inventory', 'inventory.name', '=', 'products.id')

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

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

                ->leftJoin('users', 'users.id', '=', 'obf.sales_person_id')

                ->leftJoin('Team_master', 'Team_master.id', '=', 'users.team_name')

                ->leftJoin('obf_municiple_tax', 'obf_municiple_tax.obf_id', '=', 'obf.id')

                ->where('obf_municiple_tax.status', 'municipal_taxx_comlpleted')

                ->when($vin, function ($query) use ($vin) {

                    return $query->where('inventory.vin_number', '=', $vin);

                })

                ->groupBy('obf.id');

        

            return DataTables::of($obfRecords)

                                    ->filter(function ($query){

                            if (request()->get('model_name',false)) {

                                $query->where('car_model.name', "like", "%".request()->get("model_name")."%");

                            }

                            if (request()->get('variant_name',false)) {

                                $query->where('car_varient.name', "like", "%".request()->get("variant_name")."%");

                            }

                            if (request()->get('status',false)) {

                                $query->where('obf.status', "like", "%".request()->get("status")."%");

                            }

                            if (request()->get('vin_number',false)) {

                                $query->where('inventory.vin_number', "like", "%".request()->get("vin_number")."%");

                            }

                            if (request()->get('exterior_color',false)) {

                                $query->where('exteriorcolor.name', "like", "%".request()->get("exterior_color")."%");

                            }

                            if (request()->get('interior_color',false)) {

                                $query->where('interiorcolor.name', "like", "%".request()->get("interior_color")."%");

                            }

                            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('rmc_receipt_no',false)) {

                                $query->where('obf_municiple_tax.rmc_receipt_no', "like", "%".request()->get("rmc_receipt_no")."%");

                            }

                            if (request()->get('tax_type',false)) {

                                $query->where('obf_municiple_tax.tax_type', "like", "%".request()->get("tax_type")."%");

                            }

                            if (request()->get('remarks',false)) {

                                $query->where('obf_municiple_tax.remarks', "like", "%".request()->get("remarks")."%");

                            }

                            if (request()->get('municiple_status',false)) {

                                $query->where('obf_municiple_tax.status', "like", "%".request()->get("municiple_status")."%");

                            }

                        })

                        ->make(true);

        }

        

        public function municipletaxExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportMunicipleTaxReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function ObfReport(Request $request){

            return view('AllReport.obf_report');

        }

        

        public function ObfReportFetch(Request $request)

        {

            $customer_name = OBF::select('obf.id','obf.customer_name')->get();

            $kec_name = User::select(DB::raw("CONCAT(users.first_name,' ',users.last_name) As kec_name"),'users.id')->get();

            $product = Carmodel::select('name','id')->where('status','active')->get();

            $price = OBF::select('on_road_price','id')->get();

            $varient = Carvarient::select('name','id')->where('status','active')->get();

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

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

        

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

                $data = OBF::select(

                        'obf.id',

                        'obf.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',

                        '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('ROUND(sum(cash_receipt.amount)) as received_amount'),

                        'obf.gst',

                        'exteriorcolor.name as exterior_color',

                        'obf.address',

                        'obf.registration',

                        'obf_finance.loan_amount',

                        'obf_finance.finance_discount',

                        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.way_off',

                        'obf.foc_accessories',

                        'obf.offer_ib_amount',

                        'obf.offer_kin_amount',

                        'obf.approval_status',

                        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('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.receipt_type = "access_sort_receipt" AND cash_receipt.status != "rejected") as access_sort_amount'),

                        'Team_master.team_name',

                        DB::raw('(SELECT total_exchange_amount FROM exchange_purchase WHERE exchange_purchase.obf_id = obf.id AND exchange_purchase.status = "active" LIMIT 1) as total_exchange_amount'),

                        DB::raw("(

                            COALESCE((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'), 0) +

                            COALESCE((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'), 0) +

                            COALESCE((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'), 0) +

                            COALESCE((SELECT total_exchange_amount FROM exchange_purchase WHERE exchange_purchase.obf_id = obf.id AND exchange_purchase.status = 'active' LIMIT 1), 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((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'booking_receipt' AND status != 'rejected'), 0) +

                            COALESCE((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'downpayment_receipt' AND status != 'rejected'), 0) +

                            COALESCE((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'disbusment_receipt' AND status != 'rejected'), 0) +

                            COALESCE((SELECT total_exchange_amount FROM exchange_purchase WHERE exchange_purchase.obf_id = obf.id AND status = 'active' LIMIT 1), 0) +

                            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)

                        ) + CASE

                            WHEN (

                                COALESCE((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'booking_receipt' AND status != 'rejected'), 0) +

                                COALESCE((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'downpayment_receipt' AND status != 'rejected'), 0) +

                                COALESCE((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'disbusment_receipt' AND status != 'rejected'), 0) +

                                COALESCE((SELECT total_exchange_amount FROM exchange_purchase WHERE exchange_purchase.obf_id = obf.id AND status = 'active' LIMIT 1), 0) +

                                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)

                            ) < obf.on_road_price

                            THEN -COALESCE((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'access_sort_receipt' AND status != 'rejected'), 0)

                            ELSE COALESCE((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND receipt_type = 'access_sort_receipt' AND status != 'rejected'), 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')

                    )

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

                    ->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('exchange_purchase','exchange_purchase.obf_id','=','obf.id');

        

                if(auth()->user()->roles && auth()->user()->roles[0]['id'] == 33) {

                    $data = $data->groupBy('orders.obf_id')->whereIn('orders.status', ['all_payment_done', 'invoice_create'])->whereNotNull('obf.extanded_warranty_id');

                } elseif(auth()->user()->roles && auth()->user()->roles[0]['id'] == 36){

                    $data = $data->groupBy('orders.obf_id')->whereIn('orders.status', ['all_payment_done', 'invoice_create'])->whereNotNull('obf.convinience_program');

                } elseif(auth()->user()->roles && auth()->user()->roles[0]['id'] == 37){

                    $data = $data->groupBy('orders.obf_id')->whereIn('orders.status', ['all_payment_done', 'invoice_create'])->whereNotNull('obf.rsa_master_obf');

                } elseif(auth()->user()->roles && auth()->user()->roles[0]['id'] == 32){

                    $data = $data->groupBy('orders.obf_id')->whereIn('orders.status', ['all_payment_done', 'invoice_create'])->whereNotNull('obf.accessory_id');

                } elseif(auth()->user()->roles && auth()->user()->roles[0]['id'] == 22){

                    $data = $data->groupBy('obf.id');

                } elseif(auth()->user()->roles && auth()->user()->roles[0]['id'] == 34){

                    $data = $data->groupBy('obf.id')->where('obf.trade_car_value','=','yes');

                } else {

                    $data = $data->groupBy('obf.id');

                }

        

                return datatables()->of($data)

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

            }

        }

        

        public function ObfReportExport(Request $request){

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportObfReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        

        public function MisReport(){

            return view('AllReport.miuireport');

        }

    

        public function yettodeliveryReportfetch(Request $request)

        {

            if($request->ajax()){

                $data = Order::select(

                    'obf.id',

                    'obf.customer_name',

                    'branches.name as branch',

                    'orders.vin_number',

                    'orders.engine_number',

                    'obf.on_road_price',

                    DB::raw('ROUND(SUM(cash_receipt.amount)) as total_received_amount'),

                    'orders.invoice_no',

                    DB::raw("CONCAT(LPAD(DAY(orders.invoice_date), 2, '0'), '-', ELT(MONTH(orders.invoice_date),'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'), '-', YEAR(orders.invoice_date)) as invoice_date"),

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(orders.status, '_', ' '), 1)),LOWER(SUBSTRING(REPLACE(orders.status, '_', ' '), 2))) AS invoice_status"),

                    'car_model.name AS model',

                    'car_varient.name AS car_varient_name',

                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.rto_status, '_', ' '), 1)),LOWER(SUBSTRING(REPLACE(obf.rto_status, '_', ' '), 2))) AS rto_status"),

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.insurance_status, '_', ' '), 1)),LOWER(SUBSTRING(REPLACE(obf.insurance_status, '_', ' '), 2))) AS insurance_status"),

                    DB::raw("CONCAT(UCASE(LEFT(REPLACE(obf.municipal_tax_status, '_', ' '), 1)),LOWER(SUBSTRING(REPLACE(obf.municipal_tax_status, '_', ' '), 2))) AS municipal_status"),

                    DB::raw("(

                        IFNULL(obf_finance.finance_discount, 0) +

                        IFNULL(obf.way_off, 0) +

                        IFNULL(obf.foc_accessories, 0) +

                        IFNULL(obf.offer_ib_amount, 0) +

                        IFNULL(obf.offer_kin_amount, 0)

                    ) AS total_discount"),

                    DB::raw("(obf.on_road_price 

                        - IFNULL((SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id), 0)

                        - (

                            IFNULL(obf_finance.finance_discount, 0) +

                            IFNULL(obf.way_off, 0) +

                            IFNULL(obf.foc_accessories, 0) +

                            IFNULL(obf.offer_ib_amount, 0) +

                            IFNULL(obf.offer_kin_amount, 0)

                        )

                    ) as due_amount"),

                )

                ->leftJoin('obf','obf.id','=','orders.obf_id')

                ->leftJoin('branches','branches.id','=','obf.branch_id')

                ->leftJoin('cash_receipt','cash_receipt.obf_id','=','obf.id')

                ->leftJoin('exchange_purchase', 'exchange_purchase.obf_id', '=', 'obf.id')

                ->leftJoin('inventory','inventory.id','=','orders.inventory_id')

                ->leftjoin('products', 'inventory.name', 'products.id')

                ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')

                ->leftjoin('car_model', 'car_model.id', 'products.car_model')

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

                ->leftJoin('obf_finance','obf_finance.obf_id','=','obf.id')

                ->where('orders.status', '=', 'invoice_create')

                ->whereNull('orders.dealer_id')

                ->groupBy('obf.id');

            

                return DataTables::of($data)

                    ->filter(function ($query) {

                    if (request()->get('customer_name')) {

                        $query->where('obf.customer_name', 'like', '%' . request()->get('customer_name') . '%');

                    }

        

                    if (request()->get('branch')) {

                        $query->where('branches.name', 'like', '%' . request()->get('branch') . '%');

                    }

                     

                    if (request()->get('sales_person_name')) {

                        $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%" . request()->get('sales_person_name') . "%"]);

                    }

                    

                    if (request()->get('model')) {

                        $query->where('car_model.name', 'like', '%' . request()->get('model') . '%');

                    }

                    

                    if (request()->get('car_varient_name')) {

                        $query->where('car_varient.name', 'like', '%' . request()->get('car_varient_name') . '%');

                    }

                    

                    if (request()->get('vin_number')) {

                        $query->where('orders.vin_number', 'like', '%' . request()->get('vin_number') . '%');

                    }

        

                    if (request()->get('engine_number')) {

                        $query->where('orders.engine_number', 'like', '%' . request()->get('engine_number') . '%');

                    }

        

                    if (request()->get('on_road_price')) {

                        $query->where('obf.on_road_price', 'like', '%' . request()->get('on_road_price') . '%');

                    }

                    

                    if (request()->get('total_discount')) {

                        $query->whereRaw("(

                            IFNULL(obf_finance.finance_discount, 0) +

                            IFNULL(obf.way_off, 0) +

                            IFNULL(obf.foc_accessories, 0) +

                            IFNULL(obf.offer_ib_amount, 0) +

                            IFNULL(obf.offer_kin_amount, 0)

                        ) LIKE ?", ['%' . request()->get('total_discount') . '%']);

                    }

        

                    if (request()->get('total_received_amount')) {

                        $query->havingRaw('ROUND(SUM(cash_receipt.amount)) LIKE ?', ['%' . request()->get('total_received_amount') . '%']);

                    }

                    

                    if (request()->get('due_amount')) {

                        $query->havingRaw('ROUND(obf.on_road_price - IFNULL(SUM(cash_receipt.amount), 0)) LIKE ?', ['%' . request()->get('due_amount') . '%']);

                    }

        

                    if (request()->get('invoice_no')) {

                        $query->where('orders.invoice_no', 'like', '%' . request()->get('invoice_no') . '%');

                    }

        

                    if (request()->get('invoice_date')) {

                        $query->whereDate('orders.invoice_date', '=', \Carbon\Carbon::createFromFormat('d-m-Y', request()->get('invoice_date'))->format('Y-m-d'));

                    }

        

                    if (request()->get('invoice_status')) {

                        $query->where('orders.status', 'like', '%' . request()->get('invoice_status') . '%');

                    }

                    

                    if (request()->get('insurance_status')) {

                        $query->where('obf.insurance_status', 'like', '%' . request()->get('insurance_status') . '%');

                    }

                    

                    if (request()->get('rto_status')) {

                        $query->where('obf.rto_status', 'like', '%' . request()->get('rto_status') . '%');

                    }

                    

                    if (request()->get('municipal_status')) {

                        $query->where('obf.municipal_tax_status', 'like', '%' . request()->get('municipal_status') . '%');

                    }

                })



                ->make(true);

            }

            

        }

        

        public function YettodeliveryReportExport()

        {

            if(isset($request->slug) && $request->slug != null){

                $slug = $request->slug;

            }else{

                $slug = 'all';

            }



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



            try {

                return Excel::download(new ExportYetToDeliverReport($slug), $name);

            }catch(\Exception $e){

                return redirect()->back()->with('error' ,$e->getMessage());

            }

        }

        public function customeroutstanding(Request $request){

            return view('AllReport.customeroutstandingreport');

        }

        

        public function customeroutstandingfetch(Request $request)

        {

            $permission_get = '';

            $data_v = auth()->user()->roles->pluck('data_permission');

            if (!empty($data_v)) {

                $permission_get = $data_v[0];

            }

            

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

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

                )

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

                ->leftJoinSub($cashSummary, 'cash_summary', 'cash_summary.obf_id', '=', 'obf.id')

                ->leftJoinSub($exchangeSummary, 'exchange', 'exchange.obf_id', '=', 'obf.id')

                ->where('obf.status','!=','delete')

                ->whereNotNull('orders.invoice_no')

                ->whereRaw("

                    (

                        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.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.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

                    ) != 0

                ");

                // 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()

    

                    ->editColumn('booking_date', function($data) {

                        return (!empty($data->booking_date))

                            ? \Carbon\Carbon::parse($data->booking_date)->format('d-m-Y')

                            : '--';

                    })

    

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

    

                    })

                    

                    ->editColumn('finance_discount',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);

                        

                        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('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>';

                    

                        }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('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'])

                    

                    ->filter(function ($query) {

                    if (request()->get('customer_name')) {

                        $query->where('obf.customer_name', 'like', '%' . request()->get('customer_name') . '%');

                    }

        

                    if (request()->get('branch')) {

                        $query->where('branches.name', 'like', '%' . request()->get('branch') . '%');

                    }

        

                    if (request()->get('vin_number')) {

                        $query->where('orders.vin_number', 'like', '%' . request()->get('vin_number') . '%');

                    }

        

                    if (request()->get('engine_number')) {

                        $query->where('orders.engine_number', 'like', '%' . request()->get('engine_number') . '%');

                    }

        

                    if (request()->get('on_road_price')) {

                        $query->where('obf.on_road_price', 'like', '%' . request()->get('on_road_price') . '%');

                    }

        

                    if (request()->get('total_received_amount')) {

                        $query->havingRaw('ROUND(SUM(cash_receipt.amount)) LIKE ?', ['%' . request()->get('total_received_amount') . '%']);

                    }

                    

                    if (request()->get('due_amount')) {

                        $query->havingRaw('ROUND(obf.on_road_price - IFNULL(SUM(cash_receipt.amount), 0)) LIKE ?', ['%' . request()->get('due_amount') . '%']);

                    }

        

                    if (request()->get('invoice_no')) {

                        $query->where('orders.invoice_no', 'like', '%' . request()->get('invoice_no') . '%');

                    }

        

                    if (request()->get('invoice_date')) {

                        $query->whereDate('orders.invoice_date', '=', \Carbon\Carbon::createFromFormat('d-m-Y', request()->get('invoice_date'))->format('Y-m-d'));

                    }

        

                    if (request()->get('invoice_status')) {

                        $query->where('orders.status', 'like', '%' . request()->get('invoice_status') . '%');

                    }

                })



                ->make(true);

            }

            

        }

        

        public function customeroutstandingExport(Request $request)

        {
        
            $slug = $request->slug ?? 'all';
        
            $name = 'CustomerOutstandingReport_' . date('YmdHis') . '.xlsx';
        
        
        
            try {
        
                return Excel::download(new ExportCustomerOutstandingReport($slug), $name);
        
            } catch (\Exception $e) {
        
                return back()->with('error', 'Export failed: ' . $e->getMessage());
        
            }
        
        }


        public function DemoInventoryReport(Request $request){
            $branches = Branch::where('status', 'active')->get();
            $models = Carmodel::select('id', 'name')->where('status', 'active')->get();
    
            return view('AllReport.demo_inventory_report', [
                'branches' => $branches,
                'models' => $models
            ]);
        }
        
        public function getDemoInventory(Request $request){
            $data = DB::table('inventory as i')
                ->select(
                    'i.id',
                    'i.name',
                    'b.name as branch',
                    'i.veriant',
                    'i.inventory_type',
                    'i.ex_showroom_price',
                    'i.status',
                    'i.aging_days',
                    'cv.name as varient_name',
                    'cm.name as car_name',
                    'i.fsc_code',
                    'i.vin_number',
                    DB::raw('count(obf.id) as obf_id'),DB::raw('(CASE WHEN i.status = "allocated" THEN obf.customer_name END) AS customer_name'),
                    'i.purchase_price', 
                    'i.kin_margin',
                    'i.manufacturing_year',
                    'fule_type.title as fuel_type',
                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                    'Team_master.team_name')

                ->leftjoin('branches as b', 'b.id', 'i.branch_id')
                ->leftjoin('products', 'i.name', 'products.id')
                ->leftjoin('car_model as cm', 'cm.id', 'products.car_model')
                ->leftjoin('car_varient as cv', 'cv.id', 'products.veriant')
                ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
                ->leftJoin('interiorcolor','interiorcolor.id','=','products.interior_color')
                ->leftJoin('obf','obf.product_id','=','i.name')
                ->leftjoin('fule_type','fule_type.id','=','i.fuel_type')
                ->leftjoin('users','users.id','=','obf.sales_person_id')
                ->leftjoin('Team_master','Team_master.id','users.team_name')
                ->groupBy('i.name')
                ->orderBy('i.id', 'desc')
                ->where('i.status','!=',"allocatedDealer")
                ->where('i.status','!=','deleted')
                ->where('i.inventory_type','=','Demo'); 

                return Datatables::of($data)->filter(function ($query){           
                    if (request()->get('car_name')) {
                        $query->where('cm.name', 'like', '%' . request()->get('car_name') . '%');
                    }

                    if (request()->get('varient_name')) {
                        $query->where('cv.name', 'like', '%' . request()->get('varient_name') . '%');
                    }

                    if (request()->get('status')) {
                        $query->where('i.status', 'like', '%' . request()->get('status') . '%');
                    }

                    if (request()->get('vin_number')) {
                        $query->where('i.vin_number', 'like', '%' . request()->get('vin_number') . '%');
                    }

                    if (request()->get('branch')) {
                        $query->where('b.name', 'like', '%' . request()->get('branch') . '%');
                    }

                    if (request()->get('team_name')) {
                        $query->where('Team_master.team_name', 'like', '%' . request()->get('team_name') . '%');
                    }

                    if (request()->get('sales_person_name')) {
                        $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%" . request()->get('sales_person_name') . "%"]);
                    }

                    if (request()->get('ex_showroom_price')) {
                        $query->where('i.ex_showroom_price', 'like', '%' . request()->get('ex_showroom_price') . '%');
                    }

                    if (request()->get('purchase_price')) {
                        $query->where('i.purchase_price', 'like', '%' . request()->get('purchase_price') . '%');
                    }

                    if (request()->get('kin_margin')) {
                        $query->where('i.kin_margin', 'like', '%' . request()->get('kin_margin') . '%');
                    }

                    if (request()->get('fuel_type')) {
                        $query->where('fule_type.title', 'like', '%' . request()->get('fuel_type') . '%');
                    }

                    if (request()->get('customer_name')) {
                        $query->where('obf.customer_name', 'like', '%' . request()->get('customer_name') . '%');
                    }

                    if (request()->get('aging_days')) {
                        $query->where('i.aging_days', 'like', '%' . request()->get('aging_days') . '%');
                    }

                    if (request()->get('inventory_type')) {
                        $query->where('i.inventory_type', 'like', '%' . request()->get('inventory_type') . '%');
                    }

                    if (request()->get('fsc_code')) {
                        $query->where('i.fsc_code', 'like', '%' . request()->get('fsc_code') . '%');
                    }

                })->make(true);
        }
        
        public function DemoInventoryExport(Request $request){
            if(isset($request->slug) && $request->slug != null){
                $slug = $request->slug;
            }else{
                $slug = 'all';
            }

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

            try {
                return Excel::download(new ExportDemoInventoryReport($slug), $name); 
            }catch(\Exception $e){
                return redirect()->back()->with('error' ,$e->getMessage());
            }
        }
        
        public function UsedCarReport(Request $request){
            return view('AllReport.used_car_inventory_report');
        }
        
        public function getUsedCarReport(Request $request){
            $data = DB::table('exchange_purchase')
                ->select(
                    'exchange_purchase.id',
        			'exchange_purchase.obf_id',
        			'exchange_purchase.seller_detail',
        			'exchange_purchase.company_name',
        			'exchange_purchase.variant',
        			'exchange_purchase.manufacturing_year',
        			'exchange_purchase.registration_number',
        			'exchange_purchase.chassis_number',
        			'exchange_purchase.engine_number',
        			'exchange_purchase.colour',
        			'exchange_purchase.time',
        			'exchange_purchase.date',
        			'exchange_purchase.date_of_registration',
        			'exchange_purchase.purchase_date',
        			'exchange_purchase.amount',
        			'exchange_purchase.exchange_bonus',
        			'exchange_purchase.total_exchange_amount',
        			'exchange_purchase.amount_in_words',
        			'exchange_purchase.HPA',
        			'exchange_purchase.car_status',
        			'exchange_purchase.relation_with_obf',
        			'exchange_purchase.pan_image',
        			'exchange_purchase.adhar_image',
        			'exchange_purchase.rcbook',
        			'exchange_purchase.insurance',
        			'exchange_purchase.totto',
        			'exchange_purchase.status',
        			'exchange_purchase.created_at',
        			'exchange_purchase.created_by',
        			'exchange_purchase.updated_at',
        			'exchange_purchase.updated_by',
        			'exchange_purchase.remarks',
        			'exchange_purchase.cancel_reason',
        			'obf.customer_name as seller_name',
                )
                ->leftJoin('obf','obf.id','=','exchange_purchase.obf_id')
                ->orderBy('exchange_purchase.id', 'desc')
                ->where('exchange_purchase.status','=',"active"); 
        
                return Datatables::of($data)->filter(function ($query){           
                    if (request()->get('seller_name')) {
                        $query->where('obf.customer_name', 'like', '%' . request()->get('seller_name') . '%');
                    }
        
                    if (request()->get('company_name')) {
                        $query->where('exchange_purchase.company_name', 'like', '%' . request()->get('company_name') . '%');
                    }
        
                    if (request()->get('variant')) {
                        $query->where('exchange_purchase.variant', 'like', '%' . request()->get('variant') . '%');
                    }
        
                    if (request()->get('manufacturing_year')) {
                        $query->where('exchange_purchase.manufacturing_year', 'like', '%' . request()->get('manufacturing_year') . '%');
                    }
        
                    if (request()->get('registration_number')) {
                        $query->where('exchange_purchase.registration_number', 'like', '%' . request()->get('registration_number') . '%');
                    }
        
                    if (request()->get('chassis_number')) {
                        $query->where('exchange_purchase.chassis_number', 'like', '%' . request()->get('chassis_number') . '%');
                    }
        
                    if (request()->get('engine_number')) {
                        $query->where('exchange_purchase.engine_number', 'like', '%' . request()->get('engine_number') . '%');
                    }
        
                    if (request()->get('colour')) {
                        $query->where('exchange_purchase.colour', 'like', '%' . request()->get('colour') . '%');
                    }
        
                    if (request()->get('date_of_registration')) {
                        $query->where('exchange_purchase.date_of_registration', 'like', '%' . request()->get('date_of_registration') . '%');
                    }
        
                    if (request()->get('purchase_date')) {
                        $query->where('exchange_purchase.purchase_date', 'like', '%' . request()->get('purchase_date') . '%');
                    }
        
                    if (request()->get('total_exchange_amount')) {
                        $query->where('exchange_purchase.total_exchange_amount', 'like', '%' . request()->get('total_exchange_amount') . '%');
                    }
        
                    if (request()->get('HPA')) {
                        $query->where('exchange_purchase.HPA', 'like', '%' . request()->get('HPA') . '%');
                    }
        
                    if (request()->get('remarks')) {
                        $query->where('exchange_purchase.remarks', 'like', '%' . request()->get('remarks') . '%');
                    }
        
                })->make(true);
        }
        
        public function UsedCarReportExport(Request $request){
            if(isset($request->slug) && $request->slug != null){
                $slug = $request->slug;
            }else{
                $slug = 'all';
            }
        
            $name = 'UsedCarReport_'.Date('YmdHis').'.xlsx';
        
            try {
                return Excel::download(new ExportUsedCarReport($slug), $name); 
            }catch(\Exception $e){
                return redirect()->back()->with('error' ,$e->getMessage());
            }
        }
        
        /** Refund Report */
        public function refundReport(Request $request){
            return view('AllReport.refund_report');
        }
        
        /** Refund Report Fetch*/
        public function refundReportfetch(Request $request){
            $permission_get = '';
            $data_v = auth()->user()->roles->pluck('data_permission');
            if (!empty($data_v)) {
                $permission_get = $data_v[0];
            }
            
            if($request->ajax()){
                $data = OBF::select(
                    'obf.id',
                    'obf.customer_name',
                    'branches.name as branch',
                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                    'Team_master.team_name as team_leader',
                    'car_model.name AS model',
                    'car_varient.name AS car_varient_name',
                    'obf.on_road_price',
                
                    // ✅ cash receipt aggregated
                    'cr.total_received_amount',
                    DB::raw('obf.on_road_price - COALESCE(cr.total_received_amount, 0) AS due_amount'),
                    'cr.booking_receipt_no',
                    'cr.payment_type',
                
                    'liquidation.liquidation_amount',
                    'obf.booking_date',
                
                    'obf.refund_amount as booking_refund_amount',
                    'obf.refund_remark as cancellation_reason_kec',
                
                    'lg.gm_remark as cancellation_reason_gm',
                
                    'obf.updated_at as Accepted_date_time_kec',
                
                    // ✅ logs aggregated
                    'lg.tl_date as Accepted_date_time_tl',
                    'lg.sm_date as Accepted_date_time_sm',
                    'lg.gm_date as Accepted_date_time_gm',
                    'lg.bh_date as Accepted_date_time_bh',
                    'lg.accounts_date as Accepted_date_time_account',
                
                    'liquidation_cash_receipt.liquidation_amount as cheque_amount',
                    'liquidation_cash_receipt.transaction_no as cheque_number',
                    'liquidation_cash_receipt.created_at as cheque_date',
                    'bank_account.name as bank_account_number',
                
                    
                    'lg.account_remark as account_remark',
                    'liquidation.approval_status',
                )
                
                ->leftJoin('liquidation','liquidation.obf_id','=','obf.id')
                
                ->leftJoin('branches','branches.id','=','obf.branch_id')
                ->leftJoin('users','users.id','=','obf.sales_person_id')
                ->leftJoin('users as refund_by','refund_by.id','=','obf.created_by')
                ->leftJoin('Team_master','Team_master.id','=','users.team_name')
                ->leftJoin('products' ,'obf.product_id' ,'products.id')
                ->leftJoin('car_model', 'car_model.id', '=', 'products.car_model')
                ->leftJoin('car_varient', 'car_varient.id', '=', 'products.veriant')
                
                /* =======================
                   ✅ CASH RECEIPT SUBQUERY
                ======================= */
                ->leftJoin(DB::raw("
                    (SELECT 
                        cr.obf_id,
                        SUM(cr.amount) as total_received_amount,
                
                        GROUP_CONCAT(
                            CONCAT(
                                cr.id,
                                CASE 
                                    WHEN b.name LIKE '%Rajkot%' THEN 'RJT'
                                    WHEN b.name LIKE '%Jamnagar%' THEN 'Jam'
                                    WHEN b.name LIKE '%Junagadh%' THEN 'Juna'
                                    WHEN b.name LIKE '%Morbi%' THEN 'Mor'
                                    WHEN b.name LIKE '%_K%' THEN 'IBK'
                                    WHEN b.name LIKE '%_M%' THEN 'IBM'
                                    ELSE ''
                                END,
                                DATE_FORMAT(NOW(), '%m'),
                                DATE_FORMAT(NOW(), '%Y')
                            ) SEPARATOR ',\n'
                        ) as booking_receipt_no,
                
                        GROUP_CONCAT(cr.receipt_type SEPARATOR ',\n') as payment_type
                
                    FROM cash_receipt cr
                    LEFT JOIN obf o ON o.id = cr.obf_id
                    LEFT JOIN branches b ON b.id = o.branch_id
                
                    GROUP BY cr.obf_id
                ) as cr"), 'cr.obf_id', '=', 'obf.id')
                
                /* =======================
                   ✅ LOGS SUBQUERY
                ======================= */
                ->leftJoin(DB::raw("
                    (SELECT 
                        module_id,
                
                        MAX(CASE WHEN status = 'liquidation_tl_accepted' THEN created_at END) as tl_date,
                        MAX(CASE WHEN status = 'liquidation_sm_accepted' THEN created_at END) as sm_date,
                        MAX(CASE WHEN status = 'liquidation_gm_accepted' THEN created_at END) as gm_date,
                        MAX(CASE WHEN status = 'liquidation_bh_accepted' THEN created_at END) as bh_date,
                        MAX(CASE WHEN status = 'liquidation_accountant_accepted' THEN created_at END) as accounts_date,
                
                        -- ✅ ADD THIS
                        MAX(CASE WHEN status = 'liquidation_gm_accepted' THEN remark END) as gm_remark,
                        
                        MAX(CASE WHEN status = 'liquidation_accountant_accepted' THEN remark END) as account_remark
                
                    FROM logs
                    WHERE module_nm = 'liquidation_approval'
                    GROUP BY module_id
                ) as lg"), 'lg.module_id', '=', 'obf.id')
                
                ->leftJoin('liquidation_cash_receipt','liquidation_cash_receipt.liquidation_id','=','liquidation.id')
                ->leftJoin('bank_account','bank_account.id','=','liquidation_cash_receipt.bank_account_id')
                ->whereIn('liquidation.liquidation_type',['booking_cancel','excess_amount'])
                ->whereIn('liquidation.approval_status', [
                    'liquidation_bh_accepted',
                    'liquidation_accountant_accepted',
                    'cheque_ready'
                ])
                
                ->groupBy('obf.id')
                ->orderBy('obf.id','desc');
    
                
    
                return DataTables::of($data)
                
                    ->editColumn('booking_date', function($data) {
                        return (!empty($data->booking_date)) ? \Carbon\Carbon::parse($data->booking_date)->format('d-m-Y h:i:s') : '--';
                    })

                    ->editColumn('cancellation_reason_kec',function($data){
                        return strtoupper($data->cancellation_reason_kec);
                    })
                    
                    ->editColumn('cancellation_reason_gm',function($data){
                        return strtoupper($data->cancellation_reason_gm);
                    })
                    
                    ->editColumn('Accepted_date_time_kec', function($data) {
                        return (!empty($data->Accepted_date_time_kec)) ? \Carbon\Carbon::parse($data->Accepted_date_time_kec)->format('d-m-Y h:i:s') : '--';
                    })
                    
                    ->editColumn('Accepted_date_time_tl', function($data) {
                        return (!empty($data->Accepted_date_time_tl)) ? \Carbon\Carbon::parse($data->Accepted_date_time_tl)->format('d-m-Y h:i:s') : '--';
                    })
                    
                    ->editColumn('Accepted_date_time_sm', function($data) {
                        return (!empty($data->Accepted_date_time_sm)) ? \Carbon\Carbon::parse($data->Accepted_date_time_sm)->format('d-m-Y h:i:s') : '--';
                    })
                    
                    ->editColumn('Accepted_date_time_gm', function($data) {
                        return (!empty($data->Accepted_date_time_gm)) ? \Carbon\Carbon::parse($data->Accepted_date_time_gm)->format('d-m-Y h:i:s') : '--';
                    })
                    
                    ->editColumn('Accepted_date_time_bh', function($data) {
                        return (!empty($data->Accepted_date_time_bh)) ? \Carbon\Carbon::parse($data->Accepted_date_time_bh)->format('d-m-Y h:i:s') : '--';
                    })
                    
                    ->editColumn('Accepted_date_time_account', function($data) {
                        return (!empty($data->Accepted_date_time_account)) ? \Carbon\Carbon::parse($data->Accepted_date_time_account)->format('d-m-Y h:i:s') : '--';
                    })
                    
                    ->editColumn('cheque_date', function($data) {
                        return (!empty($data->cheque_date)) ? \Carbon\Carbon::parse($data->cheque_date)->format('d-m-Y h:i:s') : '--';
                    })
                    
                    ->editColumn('account_remark',function($data){
                        return strtoupper($data->account_remark);
                    })
                    
                    ->editColumn('approval_status', function ($data) {
                        if ($data->approval_status == 'liquidation_bh_rejected') {
                            return '<span class="badge badge-pill badge-danger">Rejected By BH</span>';
                        }elseif ($data->approval_status == 'liquidation_accountant_rejected') {
                            return '<span class="badge badge-pill badge-danger">Rejected By Accountant</span>';
                        }elseif ($data->approval_status == 'liquidation_tl_accepted') {
                            return '<span class="badge badge-pill badge-success">Accepted By TL</span>';
                        }elseif ($data->approval_status == 'liquidation_bh_accepted') {
                            return '<span class="badge badge-pill badge-success">Accepted By BH</span>';
                        }elseif ($data->approval_status == 'liquidation_accountant_accepted') {
                            return '<span class="badge badge-pill badge-success">Accepted By Accountant</span>';
                        }elseif ($data->approval_status == 'cheque_ready') {
                            return '<span class="badge badge-pill" style="background-color: #17a2b8; color: white;">Cheque Ready</span>';
                        }else{
                            return '-';
                        }                            
    
                    })
                    ->rawColumns(['approval_status'])
                    ->filter(function ($query) {
    
                        if (request()->get('customer_name')) {
                            $query->where('obf.customer_name', 'like', '%' . request()->get('customer_name') . '%');
                        }
    
                        if (request()->get('branch')) {
                            $query->where('branches.name', 'like', '%' . request()->get('branch') . '%');
                        }
    
                        if (request()->get('sales_person_name')) {
                            $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%" . request()->get('sales_person_name') . "%"]);
                        }
    
                        if (request()->get('team_leader')) {
                            $query->where('Team_master.team_name', 'like', '%' . request()->get('team_leader') . '%');
                        }
    
                        if (request()->get('model')) {
                            $query->where('car_model.name', 'like', '%' . request()->get('model') . '%');
                        }
    
                        if (request()->get('car_varient_name')) {
                            $query->where('car_varient.name', 'like', '%' . request()->get('car_varient_name') . '%');
                        }
    
                        if (request()->get('on_road_price')) {
                            $query->where('obf.on_road_price', 'like', '%' . request()->get('on_road_price') . '%');
                        }
    
                        if (request()->get('total_received_amount')) {
                            $query->havingRaw('ROUND(SUM(cash_receipt.amount)) LIKE ?', ['%' . request()->get('total_received_amount') . '%']);
                        }
    
                        if (request()->get('due_amount')) {
                            $query->havingRaw('ROUND(obf.on_road_price - IFNULL(SUM(cash_receipt.amount), 0)) LIKE ?', ['%' . request()->get('due_amount') . '%']);
                        }
    
                        if (request()->get('liquidation_amount')) {
                            $query->where('liquidation.liquidation_amount', 'like', '%' . request()->get('liquidation_amount') . '%');
                        }
    
                        if (request()->get('booking_date',false)) {
                            $query->where('obf.booking_date', "like", "%".request()->get("booking_date")."%");
                        }
    
                        if (request()->get('booking_receipt_no',false)) {
                            $query->where('cash_receipt.receipt_no', "like", "%".request()->get("booking_receipt_no")."%");
                        }
    
                        if (request()->get('payment_type',false)) {
                            $query->where('cash_receipt.receipt_type', "like", "%".request()->get("payment_type")."%");
                        }
    
                        if (request()->get('booking_refund_amount',false)) {
                            $query->where('obf.refund_amount', "like", "%".request()->get("booking_refund_amount")."%");
                        }
    
                        if (request()->get('cancellation_reason_kec',false)) {
                            $query->where('obf.refund_remark', "like", "%".request()->get("cancellation_reason_kec")."%");
                        }
    
                        if (request()->get('cancellation_reason_gm', false)) {
                            $query->having('cancellation_reason_gm', 'LIKE', '%' . request()->get('cancellation_reason_gm') . '%');
                        }
    
                        if (request()->get('Accepted_date_time_kec',false)) {
                            $query->having('Accepted_date_time_kec', 'LIKE', '%' . request()->get('Accepted_date_time_kec') . '%');
                        }
    
                        if (request()->get('Accepted_date_time_tl',false)) {
                            $query->having('Accepted_date_time_tl', 'LIKE', '%' . request()->get('Accepted_date_time_tl') . '%');
                        }
    
                        if (request()->get('Accepted_date_time_sm',false)) {
                            $query->having('Accepted_date_time_sm', 'LIKE', '%' . request()->get('Accepted_date_time_sm') . '%');
                        }
    
                        if (request()->get('Accepted_date_time_gm',false)) {
                            $query->having('Accepted_date_time_gm', 'LIKE', '%' . request()->get('Accepted_date_time_gm') . '%');
                        }
    
                        if (request()->get('Accepted_date_time_bh',false)) {
                            $query->having('Accepted_date_time_bh', 'LIKE', '%' . request()->get('Accepted_date_time_bh') . '%');
                        }
    
                        if (request()->get('Accepted_date_time_account',false)) {
                            $query->having('Accepted_date_time_account', 'LIKE', '%' . request()->get('Accepted_date_time_account') . '%');
                        }
    
                        if (request()->get('cheque_amount',false)) {
                            $query->where('liquidation_cash_receipt.liquidation_amount', "like", "%".request()->get("cheque_amount")."%");
                        }
    
                        if (request()->get('cheque_number',false)) {
                            $query->where('liquidation_cash_receipt.transaction_no', "like", "%".request()->get("cheque_number")."%");
                        }
    
                        if (request()->get('cheque_date',false)) {
                            $query->where('liquidation_cash_receipt.created_at', "like", "%".request()->get("cheque_date")."%");
                        }
    
                        if (request()->get('bank_account_number',false)) {
                            $query->where('bank_account.name', "like", "%".request()->get("bank_account_number")."%");
                        }
    
                        if (request()->get('account_remark',false)) {
                            $query->having('account_remark', 'LIKE', '%' . request()->get('account_remark') . '%');
                        }
                        
                        if (request()->get('approval_status',false)) {
                            $query->where('liquidation.approval_status', "like", "%".request()->get("approval_status")."%");
                        }
    
                    })
                ->make(true);
            }
        }
        
        public function refundReportExport(Request $request){
            if(isset($request->slug) && $request->slug != null){
                $slug = $request->slug;
            }else{
                $slug = 'all';
            }
        
            $name = 'RefundReport_'.Date('YmdHis').'.xlsx';
        
            try {
                return Excel::download(new ExportRefundReport($slug), $name); 
            }catch(\Exception $e){
                return redirect()->back()->with('error' ,$e->getMessage());
            }
        }
        
        public function deliveryReport(Request $request){
            return view('AllReport.deliveryreport');
        }

        public function deliveryReportfetch(Request $request){
            if($request->ajax()){
        
                $data = Order::select(
                    'orders.id',
                    DB::raw("
                        CASE 
                            WHEN orders.obf_id IS NOT NULL THEN obf.customer_name
                            WHEN orders.dealer_id IS NOT NULL THEN dealer_management.dealer_name
                            ELSE NULL
                        END as customer_name
                    "),
                    'branches.name as branch',
                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                    DB::raw("CASE WHEN orders.inventory_id IS NOT NULL THEN car_model.name ELSE NULL END as model"),
                    DB::raw("CASE WHEN orders.inventory_id IS NOT NULL THEN car_varient.name ELSE NULL END as car_varient_name"),
                    'orders.vin_number',
                    'orders.engine_number',
                    DB::raw("CASE WHEN orders.obf_id IS NOT NULL THEN obf.on_road_price ELSE NULL END as on_road_price"),
                    DB::raw("
                        CASE 
                            WHEN orders.obf_id IS NOT NULL THEN (
                                IFNULL(obf_finance.finance_discount, 0) +
                                IFNULL(obf.way_off, 0) +
                                IFNULL(obf.foc_accessories, 0) +
                                IFNULL(obf.offer_ib_amount, 0) +
                                IFNULL(obf.offer_kin_amount, 0)
                            )
                            ELSE NULL
                        END as total_discount
                    "),
                    DB::raw("
                        CASE 
                            WHEN orders.obf_id IS NOT NULL THEN (
                                SELECT ROUND(SUM(cr.amount)) 
                                FROM cash_receipt cr 
                                WHERE cr.obf_id = obf.id
                            )
                            ELSE NULL
                        END as total_received_amount
                    "),
                    DB::raw("
                        CASE 
                            WHEN orders.obf_id IS NOT NULL THEN (
                                obf.on_road_price 
                                - IFNULL((SELECT SUM(cr.amount) FROM cash_receipt cr WHERE cr.obf_id = obf.id), 0)
                                - (
                                    IFNULL(obf_finance.finance_discount, 0) +
                                    IFNULL(obf.way_off, 0) +
                                    IFNULL(obf.foc_accessories, 0) +
                                    IFNULL(obf.offer_ib_amount, 0) +
                                    IFNULL(obf.offer_kin_amount, 0)
                                )
                            )
                            ELSE NULL
                        END as due_amount
                    "),
                    'orders.invoice_no',
                    DB::raw("DATE_FORMAT(orders.invoice_date, '%d-%b-%Y') as invoice_date"),
                    DB::raw("
                        CONCAT(
                            UCASE(LEFT(REPLACE(orders.status, '_', ' '), 1)),
                            LOWER(SUBSTRING(REPLACE(orders.status, '_', ' '), 2))
                        ) AS invoice_status
                    "),
                    DB::raw("
                        CASE 
                            WHEN orders.obf_id IS NOT NULL THEN 
                                CONCAT(UCASE(LEFT(REPLACE(obf.insurance_status, '_', ' '), 1)),
                                LOWER(SUBSTRING(REPLACE(obf.insurance_status, '_', ' '), 2)))
                            ELSE NULL
                        END as insurance_status
                    "),
                    DB::raw("
                        CASE 
                            WHEN orders.obf_id IS NOT NULL THEN 
                                CONCAT(UCASE(LEFT(REPLACE(obf.rto_status, '_', ' '), 1)),
                                LOWER(SUBSTRING(REPLACE(obf.rto_status, '_', ' '), 2)))
                            ELSE NULL
                        END as rto_status
                    "),
                    DB::raw("
                        CASE 
                            WHEN orders.obf_id IS NOT NULL THEN 
                                CONCAT(UCASE(LEFT(REPLACE(obf.municipal_tax_status, '_', ' '), 1)),
                                LOWER(SUBSTRING(REPLACE(obf.municipal_tax_status, '_', ' '), 2)))
                            ELSE NULL
                        END as municipal_status
                    ")
                )
                ->leftJoin('obf','obf.id','=','orders.obf_id')
                ->leftJoin('branches','branches.id','=','orders.branch_id')
                ->leftJoin('inventory','inventory.id','=','orders.inventory_id')
                ->leftJoin('products', 'inventory.name', '=', 'products.id')
                ->leftJoin('car_varient', 'car_varient.id', '=', 'products.veriant')
                ->leftJoin('car_model', 'car_model.id', '=', 'products.car_model')
                ->leftJoin('users', function($join){
                    $join->on('users.id','=','obf.sales_person_id');
                })
                ->leftJoin('obf_finance','obf_finance.obf_id','=','obf.id')
                ->leftJoin('dealer_management','dealer_management.id','=','orders.dealer_id')
        
                // ✅ Ensure both OBF + Dealer included
                ->where(function($q){
                    $q->whereNotNull('orders.obf_id')
                      ->orWhereNotNull('orders.dealer_id');
                })
        
                ->where('orders.status', 'delivered')
                ->whereDate('orders.invoice_date', '>=', '2026-01-01');
        
                return DataTables::of($data)
        
                ->filter(function ($query) {
        
                    if (request()->get('customer_name')) {
                        $query->whereRaw("
                            (obf.customer_name LIKE ? OR dealer_management.dealer_name LIKE ?)
                        ", [
                            '%' . request()->get('customer_name') . '%',
                            '%' . request()->get('customer_name') . '%'
                        ]);
                    }
        
                    if (request()->get('branch')) {
                        $query->where('branches.name', 'like', '%' . request()->get('branch') . '%');
                    }
        
                    if (request()->get('sales_person_name')) {
                        $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%" . request()->get('sales_person_name') . "%"]);
                    }
        
                    if (request()->get('model')) {
                        $query->where('car_model.name', 'like', '%' . request()->get('model') . '%');
                    }
        
                    if (request()->get('car_varient_name')) {
                        $query->where('car_varient.name', 'like', '%' . request()->get('car_varient_name') . '%');
                    }
        
                    if (request()->get('vin_number')) {
                        $query->where('orders.vin_number', 'like', '%' . request()->get('vin_number') . '%');
                    }
        
                    if (request()->get('engine_number')) {
                        $query->where('orders.engine_number', 'like', '%' . request()->get('engine_number') . '%');
                    }
        
                    if (request()->get('on_road_price')) {
                        $query->whereNotNull('orders.obf_id')
                              ->where('obf.on_road_price', 'like', '%' . request()->get('on_road_price') . '%');
                    }
        
                    if (request()->get('total_discount')) {
                        $query->whereNotNull('orders.obf_id')
                              ->whereRaw("(
                                    IFNULL(obf_finance.finance_discount, 0) +
                                    IFNULL(obf.way_off, 0) +
                                    IFNULL(obf.foc_accessories, 0) +
                                    IFNULL(obf.offer_ib_amount, 0) +
                                    IFNULL(obf.offer_kin_amount, 0)
                              ) LIKE ?", ['%' . request()->get('total_discount') . '%']);
                    }
        
                    if (request()->get('total_received_amount')) {
                        $query->whereNotNull('orders.obf_id')
                              ->whereRaw("(
                                    SELECT ROUND(SUM(cr.amount)) 
                                    FROM cash_receipt cr 
                                    WHERE cr.obf_id = obf.id
                              ) LIKE ?", ['%' . request()->get('total_received_amount') . '%']);
                    }
        
                    if (request()->get('due_amount')) {
                        $query->whereNotNull('orders.obf_id')
                              ->whereRaw("(
                                    obf.on_road_price 
                                    - IFNULL((SELECT SUM(cr.amount) FROM cash_receipt cr WHERE cr.obf_id = obf.id), 0)
                                    - (
                                        IFNULL(obf_finance.finance_discount, 0) +
                                        IFNULL(obf.way_off, 0) +
                                        IFNULL(obf.foc_accessories, 0) +
                                        IFNULL(obf.offer_ib_amount, 0) +
                                        IFNULL(obf.offer_kin_amount, 0)
                                    )
                              ) LIKE ?", ['%' . request()->get('due_amount') . '%']);
                    }
        
                    if (request()->get('invoice_no')) {
                        $query->where('orders.invoice_no', 'like', '%' . request()->get('invoice_no') . '%');
                    }
        
                    if (request()->get('invoice_date')) {
                        $query->whereDate(
                            'orders.invoice_date',
                            '=',
                            \Carbon\Carbon::createFromFormat('d-m-Y', request()->get('invoice_date'))->format('Y-m-d')
                        );
                    }
        
                    if (request()->get('invoice_status')) {
                        $query->where('orders.status', 'like', '%' . request()->get('invoice_status') . '%');
                    }
        
                    if (request()->get('insurance_status')) {
                        $query->whereNotNull('orders.obf_id')
                              ->where('obf.insurance_status', 'like', '%' . request()->get('insurance_status') . '%');
                    }
        
                    if (request()->get('rto_status')) {
                        $query->whereNotNull('orders.obf_id')
                              ->where('obf.rto_status', 'like', '%' . request()->get('rto_status') . '%');
                    }
        
                    if (request()->get('municipal_status')) {
                        $query->whereNotNull('orders.obf_id')
                              ->where('obf.municipal_tax_status', 'like', '%' . request()->get('municipal_status') . '%');
                    }
        
                })
        
                ->make(true);
            }
        }

        public function deliveryReportExport(){
            if(isset($request->slug) && $request->slug != null){
                $slug = $request->slug;
            }else{
                $slug = 'all';
            }

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

            try {
                return Excel::download(new ExportDeliverReport($slug), $name);
            }catch(\Exception $e){
                return redirect()->back()->with('error' ,$e->getMessage());
            }
        }
        
        public function PPCReport(){
            return view('AllReport.ppc_report');
        }
        
        public function PPCReportFetch(Request $request)

        {

            if($request->ajax()){

                $day_book = OBF::from('obf as obf')

                    ->leftJoin('branches', 'branches.id', '=', 'obf.branch_id')

                    ->leftJoin('users as us', 'us.id', '=', 'obf.sales_person_id')

                    ->leftJoin('Team_master', 'Team_master.id', '=', 'us.team_name')

                    ->leftJoin('district', 'district.id', '=', 'obf.district_id')

                    ->leftJoin('common_state', 'common_state.id', '=', 'obf.state_id')

                    ->leftJoin('orders', 'orders.obf_id', '=', 'obf.id')

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

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

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

                    ->leftJoin('inventory', 'inventory.id', '=', 'obf.inventory_id')

                    ->leftjoin('pricelist_master','pricelist_master.id','=', 'obf.pricelist_id')

                    ->leftJoin('make_deal', 'make_deal.obf_id', '=', 'obf.id')

                    ->leftJoin('obf_insurance', 'obf.id', '=', 'obf_insurance.obf_id')

                    ->leftJoin('insurance','obf_insurance.company_name', '=', 'insurance.id')

                    ->leftjoin('rsa','rsa.id','=','obf.rsa_master_obf')

                    ->leftjoin('rsa as ccs','ccs.id','=','obf.ccs_master_obf')

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

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

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

                    ->leftJoin('obf_finance', 'obf.id', '=', 'obf_finance.obf_id')

                    ->leftJoin('finance', 'obf_finance.finance_name', '=', 'finance.id')

                    ->leftJoin('obf_rto', 'obf_rto.obf_id', '=', 'obf.id')

                    ->leftJoin('customer_type_master', 'customer_type_master.id', '=', 'obf.customer_type_new')

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

                    ->leftJoin('exchange_purchase', function ($join) {

                        $join->on('exchange_purchase.obf_id', '=', 'obf.id')

                             ->whereIn('exchange_purchase.status', ['active','sell']);

                    })

                    ->leftJoin(DB::raw('(SELECT obf_id, 

                                SUM(CASE WHEN receipt_type = "booking_receipt" AND status != "rejected" THEN amount ELSE 0 END) as booking_amount,

                                SUM(CASE WHEN receipt_type = "downpayment_receipt" AND status != "rejected" THEN amount ELSE 0 END) as dp_amount,

                                SUM(CASE WHEN receipt_type = "disbusment_receipt" AND status != "rejected" THEN amount ELSE 0 END) as finance_discount,

                                SUM(CASE WHEN receipt_type = "access_sort_receipt" AND status != "rejected" THEN amount ELSE 0 END) as access_sort_amount,

                                SUM(CASE WHEN receipt_type = "other_receipt" AND status != "rejected" THEN amount ELSE 0 END) as other_amount

                            FROM cash_receipt

                            GROUP BY obf_id) as cr'), 'cr.obf_id', '=', 'obf.id')

                    ->select(

                        'obf.id',

                        DB::raw('DATE(obf.booking_date) as booking_date'),

                        DB::raw("DATE_FORMAT(orders.invoice_date, '%b-%y') as booking_month_year"),    

                        'obf.customer_name',

                        'obf.company_name',

                        'obf.registration',

                        'obf.einvoicing_applicable',

                        'obf.gst',

                        'obf.ship_to_customer_name',

                        'obf.ship_to_address',

                        'obf.contact_number',

                        'obf.pan_number',

                        'obf.adhar_number',

                        'obf.aadhar_pan_link',

                        'obf.on_road_price',

                        'branches.name AS location',

                        DB::raw("CONCAT(us.first_name,' ',us.last_name) AS kec_name"),

                        'Team_master.team_name as tl_name',

                        'district.name as district_name',

                        'common_state.name as state_name',

                        'obf.customer_type as rto_type',

                        'customer_type_master.name as customer_type_master', 

                        'orders.invoice_date as ibs_invoice_date',

                        'orders.invoice_no as ibs_invoice_no',

                        'car_model.name AS model', 

                        'car_varient.name AS varient', 

                        'fule_type.title as fuel_type',

                        'inventory.vin_number',

                        'inventory.engine_number',

                        DB::raw("CASE WHEN pricelist_master.is_csd = 'No' THEN pricelist_master.ex_showroom_price WHEN pricelist_master.is_csd = 'Yes' THEN (pricelist_master.basic + pricelist_master.gst_amount) END AS ex_showroom_price"),

                        'make_deal.deal_amt as basic',

                        DB::raw('make_deal.gst_tax_deal / 2 as cgst'),

                        DB::raw('make_deal.gst_tax_deal / 2 as sgst'),

                        DB::raw("0 as igst"),

                        'make_deal.gst_tax_deal',

                        'make_deal.cess_tax_deal as cess',

                        'make_deal.tcs_tax_deal as tcs',

                        'make_deal.rto_deal as rto',

                        'make_deal.rto_cutom_handling_charges_deal as rto_custom_handling_charges',

                        'make_deal.municipal_tax_deal as municipal_tax',

                        'make_deal.insurance_deal as insurance',

                        'insurance.name AS insurance_name',

                        'insurance.type AS insurance_type',

                        DB::raw("CASE WHEN rsa.rsa_ccs = 'RSA' THEN rsa.amount ELSE 0 END as rsa"),

                        DB::raw("CASE WHEN ccs.rsa_ccs = 'CCS' THEN ccs.amount ELSE 0 END as ccs"),

                        'extand_warranties.amount as ew',

                        'mcp.amount as mcp',

                        'fasttags.amount as fastag',

                        DB::raw("(IFNULL((SELECT SUM(accessories.price) FROM accessories WHERE FIND_IN_SET(accessories.id, obf.accessory_id)), 0) + IFNULL(obf.other_accesssories_prise, 0)) as accessory_amount"),

                        DB::raw('cr.booking_amount as booking_amount'),

                        DB::raw('cr.dp_amount as dp_amount'),

                        'finance.name AS financer_name',

                        'obf_finance.finance_type',

                        'obf_rto.vehicle_number',

                        DB::raw('cr.finance_discount as finance_discount'),

                        DB::raw('exchange_purchase.total_exchange_amount as exchange_amount'),

                        DB::raw('cr.access_sort_amount as access_sort_amount'),

                        DB::raw('cr.other_amount as other_amount'),

                        DB::raw("0 as refund_amt_process"),

                        DB::raw("0 as refund_amt_date"),

                        DB::raw("0 as refund_diff"),

                        DB::raw("0 as date"),

                        DB::raw("0 as payment_ref_no"),

                        'obf.step1_remarks as remarks',

                        'inventory.kin_invoice_no',

                        'inventory.kin_invoice_date',

                        'inventory.purchase_price',

                        'inventory.manufacturing_year',

                        'pricelist_master.price_list_name',

                        DB::raw("CONCAT(exchange_purchase.company_name, ' - ', exchange_purchase.variant) AS exchange_name"),

                        'exchange_purchase.registration_number',
                        
                        DB::raw("DATEDIFF(orders.invoice_date, obf.booking_date) as tat_days"),

                        DB::raw("
                            CASE 
                                WHEN orders.invoice_date IS NULL THEN 'Pending Invoice'
                        
                                WHEN DATEDIFF(orders.invoice_date, obf.booking_date) BETWEEN 0 AND 10 
                                    THEN 'Within TAT (10 Days)'
                        
                                WHEN DATEDIFF(orders.invoice_date, obf.booking_date) BETWEEN 11 AND 15 
                                    THEN 'Delay (11-15 Days)'
                        
                                WHEN DATEDIFF(orders.invoice_date, obf.booking_date) > 15 
                                    THEN 'Delay (Above 15 Days)'
                        
                                ELSE 'Invalid Date'
                            END as tat_status
                        "), 
                        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"),
                        'obf.way_off as kec_discount',         
                        'obf.tl_discount',
                        'obf.sm_discount',
                        'obf.gm_discount',
                        'obf.bh_discount',
                        'obf.ceo_discount',
                        'obf.md_discount',
                    )

                ->whereNotNull('orders.invoice_no') 

                ->groupBy('obf.id')

                ->orderBy('obf.id', 'DESC');



                

                return Datatables::of($day_book)

                ->order(function ($query) {

                    $query->orderBy('obf.id', 'desc');

                })

                ->addIndexColumn()

                ->editColumn('discount_with_gst', function($data) {

                    $ex_showroom_price = ($data->ex_showroom_price ?? 0);

                    $after_dis_ex_showroom_price = ($data->basic ?? 0) + ($data->gst_tax_deal ?? 0) + ($data->cess ?? 0);

                    $discount_with_gst = $ex_showroom_price - $after_dis_ex_showroom_price;

                    return $discount_with_gst;

                })

                ->editColumn('after_dis_ex_showroom_price', function($data) {

                    $after_dis_ex_showroom_price = ($data->basic ?? 0) + ($data->gst_tax_deal ?? 0) + ($data->cess ?? 0);

                    return $after_dis_ex_showroom_price;

                })

                ->editColumn('total', function($data) {

                    $total = ($data->basic ?? 0) + ($data->gst_tax_deal ?? 0) + ($data->cess ?? 0) + ($data->tcs ?? 0) + ($data->rto ?? 0) + ($data->rto_custom_handling_charges ?? 0) + ($data->municipal_tax ?? 0) + ($data->insurance ?? 0) + ($data->rsa ?? 0) + ($data->css ?? 0) + ($data->ew ?? 0) + ($data->mcp ?? 0) + ($data->fastag ?? 0) + ($data->accessory_amount ?? 0);

                    return $total;

                })

                ->editColumn('total_amt_received', function($data) {

                    $total_amt_received = ($data->booking_amount ?? 0) + ($data->dp_amount ?? 0) + ($data->finance_discount ?? 0) + ($data->exchange_amount ?? 0) + ($data->access_sort_amount ?? 0) + ($data->other_amount ?? 0);

                    return $total_amt_received;

                })

                ->editColumn('refund_amount', function($data) {

                    $total = ($data->basic ?? 0) + ($data->gst_tax_deal ?? 0) + ($data->cess ?? 0) + ($data->tcs ?? 0) + ($data->rto ?? 0) + ($data->rto_custom_handling_charges ?? 0) + ($data->municipal_tax ?? 0) + ($data->insurance ?? 0) + ($data->rsa ?? 0) + ($data->ccs ?? 0) + ($data->ew ?? 0) + ($data->mcp ?? 0) + ($data->fastag ?? 0) + ($data->accessory_amount ?? 0);

                    $total_amt_received = ($data->booking_amount ?? 0) + ($data->dp_amount ?? 0) + ($data->finance_discount ?? 0) + ($data->exchange_amount ?? 0) + ($data->access_sort_amount ?? 0) + ($data->other_amount ?? 0);

                    $refund_amount = ($total ?? 0) - ($total_amt_received ?? 0);

                    return $refund_amount;

                })
                
                ->editColumn('offer_discount', function($data) {
                    $output = [];

                    // KIN OFFERS
                    if(!empty($data->kin_offer_titles)){
                
                        $titles  = explode(',', $data->kin_offer_titles);
                        $amounts = explode(',', $data->kin_offer_amounts);
                
                        foreach($titles as $key => $title){
                
                            $amount = $amounts[$key] ?? '';
                
                            $output[] = $title.' - '.$amount;
                        }
                    }
                
                    // IB OFFERS
                    if(!empty($data->ib_offer_titles)){
                
                        $titles  = explode(',', $data->ib_offer_titles);
                        $amounts = explode(',', $data->ib_offer_amounts);
                
                        foreach($titles as $key => $title){
                
                            $amount = $amounts[$key] ?? '';
                
                            $output[] = $title.' - '.$amount;
                        }
                    }
                
                    return implode(',<br>', $output);
                    
                })
                
                ->addColumn('approval_discount', function($data) {

                    $output = [];
                
                    if(!empty($data->kec_discount))
                        $output[] = 'KEC - '.$data->kec_discount;
                
                    if(!empty($data->tl_discount))
                        $output[] = 'TL - '.$data->tl_discount;
                
                    if(!empty($data->sm_discount))
                        $output[] = 'SM - '.$data->sm_discount;
                
                    if(!empty($data->gm_discount))
                        $output[] = 'GM - '.$data->gm_discount;
                
                    if(!empty($data->bh_discount))
                        $output[] = 'BH - '.$data->bh_discount;
                
                    if(!empty($data->ceo_discount))
                        $output[] = 'CEO - '.$data->ceo_discount;
                
                    if(!empty($data->md_discount))
                        $output[] = 'MD - '.$data->md_discount;
                
                    return implode(',<br>', $output); 
                })
                
                ->addColumn('total_discount', function($data) {

                    $total = 0;
                
                    // KIN OFFERS
                    if(!empty($data->kin_offer_amounts)){
                        $amounts = explode(',', $data->kin_offer_amounts);
                        foreach($amounts as $amount){
                            $total += (float)$amount;
                        }
                    }
                
                    // IB OFFERS
                    if(!empty($data->ib_offer_amounts)){
                        $amounts = explode(',', $data->ib_offer_amounts);
                        foreach($amounts as $amount){
                            $total += (float)$amount;
                        }
                    }
                
                    // Approval Discounts
                    $total += (float)($data->kec_discount ?? 0);
                    $total += (float)($data->tl_discount ?? 0);
                    $total += (float)($data->sm_discount ?? 0);
                    $total += (float)($data->gm_discount ?? 0);
                    $total += (float)($data->bh_discount ?? 0);
                    $total += (float)($data->ceo_discount ?? 0);
                    $total += (float)($data->md_discount ?? 0);
                
                    return $total;
                })
                
                ->editColumn('on_road_discount', function($data) {

                    $total = ($data->basic ?? 0) + ($data->gst_tax_deal ?? 0) + ($data->cess ?? 0) + ($data->tcs ?? 0) + ($data->rto ?? 0) + ($data->rto_custom_handling_charges ?? 0) + ($data->municipal_tax ?? 0) + ($data->insurance ?? 0) + ($data->rsa ?? 0) + ($data->ccs ?? 0) + ($data->ew ?? 0) + ($data->mcp ?? 0) + ($data->fastag ?? 0) + ($data->accessory_amount ?? 0);

                    $on_road_discount = ($data->on_road_price ?? 0) - ($total ?? 0);

                    return $on_road_discount;

                })

                ->editColumn('booking_date', function ($data) {

                     return !empty($data->booking_date) ? \Carbon\Carbon::parse($data->booking_date)->format('d-m-Y') : ''; 

                })

                ->editColumn('ibs_invoice_date', function ($data) {

                     return !empty($data->ibs_invoice_date) ? \Carbon\Carbon::parse($data->ibs_invoice_date)->format('d-m-Y') : ''; 

                })

                ->editColumn('rto_type', function ($data) {

                     return ucwords(str_replace('_',' ',$data->rto_type)); 

                })

                ->editColumn('remarks', function ($data) {

                    $full = htmlspecialchars($data->remarks ?? '', ENT_QUOTES, 'UTF-8');

                    $short = mb_strimwidth($full, 0, 20, '...');

                    return '<span title="'.$full.'">'.$short.'</span>';

                })

                ->rawColumns(['remarks','offer_discount','approval_discount'])

                ->filter(function ($query) {

                    if (request()->get('location', false)) {

                        $query->where('branches.name', 'like', "%" . request()->get("location") . "%");

                    }

                    if (request()->get('kec_name', false)) {

                        $salesPersonName = request()->get('kec_name');

                        $query->whereRaw("CONCAT(us.first_name, ' ', us.last_name) LIKE ?", ["%{$salesPersonName}%"]);

                    }

                    if (request()->get('tl_name', false)) {

                        $query->where('Team_master.team_name', 'like', "%" . request()->get("tl_name") . "%");

                    }

                    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('orders.invoice_date', [$start, $end]);
                                // $query->whereBetween('obf.booking_date', [$start, $end]);

                            } catch (\Exception $e) {

                                \Log::error('Invalid date range format for Booking Date filter', [

                                    'input' => $dateRange,

                                    'error' => $e->getMessage()

                                ]);

                            }

                        }

                    }

                    if (request()->get('price_list_name', false)) {

                        $query->where('pricelist_master.price_list_name', 'like', "%" . request()->get("price_list_name") . "%");

                    }

                    if (request()->get('customer_name', false)) {

                        $query->where('obf.customer_name', 'like', "%" . request()->get("customer_name") . "%");

                    }

                    if (request()->get('company_name', false)) {

                        $query->where('obf.company_name', 'like', "%" . request()->get("company_name") . "%");

                    }

                    if (request()->get('registration', false)) {

                        $query->where('obf.registration', 'like', "%" . request()->get("registration") . "%");

                    }

                    if (request()->get('district_name', false)) {

                        $query->where('district.name', 'like', "%" . request()->get("district_name") . "%");

                    }

                    if (request()->get('state_name', false)) {

                        $query->where('common_state.name', 'like', "%" . request()->get("state_name") . "%");

                    }

                    if (request()->get('einvoicing_applicable', false)) {

                        $query->where('obf.einvoicing_applicable', 'like', "%" . request()->get("einvoicing_applicable") . "%");

                    }

                    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('ship_to_address', false)) {

                        $query->where('obf.ship_to_address', 'like', "%" . request()->get("ship_to_address") . "%");

                    }

                    if (request()->get('rto_type',false)) {

                        $query->where('obf_rto.rto_type', "like", "%".request()->get("rto_type")."%");

                    }

                    if (request()->get('customer_type_master',false)) {

                        $query->where('customer_type_master.name', "like", "%".request()->get("customer_type_master")."%");

                    }

                    if (request()->get('contact_number', false)) {

                        $query->where('obf.contact_number', 'like', "%" . request()->get("contact_number") . "%");

                    }

                    if (request()->get('pan_number', false)) {

                        $query->where('obf.pan_number', 'like', "%" . request()->get("pan_number") . "%");

                    }

                    if (request()->get('adhar_number', false)) {

                        $query->where('obf.adhar_number', 'like', "%" . request()->get("adhar_number") . "%");

                    }

                    if (request()->get('aadhar_pan_link', false)) {

                        $query->where('obf.aadhar_pan_link', 'like', "%" . request()->get("aadhar_pan_link") . "%");

                    }

                    if ($dateRange = request()->get('ibs_invoice_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('orders.invoice_date', [$start, $end]);

                            } catch (\Exception $e) {

                                \Log::error('Invalid date range format for IBS invoice_date filter', [

                                    'input' => $dateRange,

                                    'error' => $e->getMessage()

                                ]);

                            }

                        }

                    }

                    if (request()->get('ibs_invoice_no', false)) {

                        $query->where('orders.invoice_no', 'like', "%" . request()->get("ibs_invoice_no") . "%");

                    }

                    if (request()->get('model', false)) {

                        $query->where('car_model.name', 'like', "%" . request()->get("model") . "%");

                    }

                    if (request()->get('varient', false)) {

                        $query->where('car_varient.name', 'like', "%" . request()->get("varient") . "%");

                    }

                    if (request()->get('vin_number', false)) {

                        $query->where('inventory.vin_number', 'like', "%" . request()->get("vin_number") . "%");

                    }

                    if (request()->get('engine_number', false)) {

                        $query->where('inventory.engine_number', 'like', "%" . request()->get("engine_number") . "%");

                    }

                    if (request()->get('ex_showroom_price', false)) {

                        $query->where('pricelist_master.ex_showroom_price', 'like', "%" . request()->get("ex_showroom_price") . "%");

                    }

                    if ($discount_with_gst = request()->get('discount_with_gst')) {

                        $query->havingRaw("discount_with_gst LIKE ?", ["%{$discount_with_gst}%"]);

                    }

                    if ($after_dis_ex_showroom_price = request()->get('after_dis_ex_showroom_price')) {

                        $query->havingRaw("after_dis_ex_showroom_price LIKE ?", ["%{$after_dis_ex_showroom_price}%"]);

                    }

                    if (request()->get('basic', false)) {

                        $query->where('make_deal.deal_amt', 'like', "%" . request()->get("basic") . "%");

                    }

                    if ($cgst = request()->get('cgst')) {

                        $query->havingRaw("cgst LIKE ?", ["%{$cgst}%"]);

                    }

                    if ($sgst = request()->get('sgst')) {

                        $query->havingRaw("sgst LIKE ?", ["%{$sgst}%"]);

                    }

                    if ($igst = request()->get('igst')) {

                        $query->havingRaw("igst LIKE ?", ["%{$igst}%"]);

                    }

                    if (request()->get('cess', false)) {

                        $query->where('make_deal.cess_tax_deal', 'like', "%" . request()->get("cess") . "%");

                    }

                    if ($after_dis_ex_showroom_price = request()->get('after_dis_ex_showroom_price')) {

                        $query->havingRaw("after_dis_ex_showroom_price LIKE ?", ["%{$after_dis_ex_showroom_price}%"]);

                    }

                    if (request()->get('tcs', false)) {

                        $query->where('make_deal.tcs_tax_deal', 'like', "%" . request()->get("tcs") . "%");

                    }

                    if (request()->get('rto', false)) {

                        $query->where('make_deal.rto_deal', 'like', "%" . request()->get("rto") . "%");

                    }

                    if (request()->get('rto_custom_handling_charges', false)) {

                        $query->where('make_deal.rto_cutom_handling_charges_deal', 'like', "%" . request()->get("rto_custom_handling_charges") . "%");

                    }

                    if (request()->get('municipal_tax', false)) {

                        $query->where('make_deal.municipal_tax_deal', 'like', "%" . request()->get("municipal_tax") . "%");

                    }

                    if (request()->get('insurance', false)) {

                        $query->where('make_deal.insurance_deal', 'like', "%" . request()->get("insurance") . "%");

                    }

                    if (request()->get('insurance_name', false)) {

                        $query->where('insurance.name', 'like', "%" . request()->get("insurance_name") . "%");

                    }

                    if ($rsa = request()->get('rsa')) {

                        $query->havingRaw("rsa LIKE ?", ["%{$rsa}%"]);

                    }

                    if ($ccs = request()->get('ccs')) {

                        $query->havingRaw("ccs LIKE ?", ["%{$ccs}%"]);

                    }

                    if (request()->get('ew', false)) {

                        $query->where('extand_warranties.amount', 'like', "%" . request()->get("ew") . "%");

                    }

                    if (request()->get('mcp', false)) {

                        $query->where('mcp.amount', 'like', "%" . request()->get("mcp") . "%");

                    }

                    if (request()->get('fastag', false)) {

                        $query->where('fasttags.amount', 'like', "%" . request()->get("fastag") . "%");

                    }

                    if ($accessory_amount = request()->get('accessory_amount')) {

                        $query->havingRaw("accessory_amount LIKE ?", ["%{$accessory_amount}%"]);

                    }

                    if ($total = request()->get('total')) {

                        $query->havingRaw("total LIKE ?", ["%{$total}%"]);

                    }

                    if ($booking_amount = request()->get('booking_amount')) {

                        $query->havingRaw("booking_amount LIKE ?", ["%{$booking_amount}%"]);

                    }

                    if ($dp_amount = request()->get('dp_amount')) {

                        $query->havingRaw("dp_amount LIKE ?", ["%{$dp_amount}%"]);

                    }

                    if (request()->get('financer_name', false)) {

                        $query->where('finance.name', 'like', "%" . request()->get("financer_name") . "%");

                    }

                    if (request()->get('finance_type', false)) {

                        $query->where('obf_finance.finance_type', 'like', "%" . request()->get("finance_type") . "%");

                    }

                    if (request()->get('finance_discount', false)) {

                        $query->where('obf_finance.finance_discount', 'like', "%" . request()->get("finance_discount") . "%");

                    }

                    if ($exchange_amount = request()->get('exchange_amount')) {

                        $query->havingRaw("exchange_amount LIKE ?", ["%{$exchange_amount}%"]);

                    }

                    if ($access_sort_amount = request()->get('access_sort_amount')) {

                        $query->havingRaw("access_sort_amount LIKE ?", ["%{$access_sort_amount}%"]);

                    }

                    if ($other_amount = request()->get('other_amount')) {

                        $query->havingRaw("other_amount LIKE ?", ["%{$other_amount}%"]);

                    }

                    if ($total_amt_received = request()->get('total_amt_received')) {

                        $query->havingRaw("total_amt_received LIKE ?", ["%{$total_amt_received}%"]);

                    }

                    if ($refund_amount = request()->get('refund_amount')) {

                        $query->havingRaw("refund_amount LIKE ?", ["%{$refund_amount}%"]);

                    }

                    if ($refund_amt_process = request()->get('refund_amt_process')) {

                        $query->havingRaw("refund_amt_process LIKE ?", ["%{$refund_amt_process}%"]);

                    }

                    if ($refund_amt_date = request()->get('refund_amt_date')) {

                        $query->havingRaw("refund_amt_date LIKE ?", ["%{$refund_amt_date}%"]);

                    }

                    if ($refund_diff = request()->get('refund_diff')) {

                        $query->havingRaw("refund_diff LIKE ?", ["%{$refund_diff}%"]);

                    }

                    if ($date = request()->get('date')) {

                        $query->havingRaw("date LIKE ?", ["%{$date}%"]);

                    }

                    if ($payment_ref_no = request()->get('payment_ref_no')) {

                        $query->havingRaw("payment_ref_no LIKE ?", ["%{$payment_ref_no}%"]);

                    }

                    if (request()->get('on_road_price', false)) {

                        $query->where('obf.on_road_price', 'like', "%" . request()->get("on_road_price") . "%");

                    }

                    if ($total = request()->get('total')) {

                        $query->havingRaw("total LIKE ?", ["%{$total}%"]);

                    }

                    if ($on_road_discount = request()->get('on_road_discount')) {

                        $query->havingRaw("on_road_discount LIKE ?", ["%{$on_road_discount}%"]);

                    }

                    if (request()->get('remarks', false)) {

                        $query->where('obf.step1_remarks', 'like', "%" . request()->get("remarks") . "%");

                    }

                    if (request()->get('kin_invoice_no', false)) {

                        $query->where('inventory.kin_invoice_no', 'like', "%" . request()->get("kin_invoice_no") . "%");

                    }

                    if (request()->get('kin_invoice_date', false)) {

                        $query->where('inventory.kin_invoice_date', 'like', "%" . request()->get("kin_invoice_date") . "%");

                    }

                    if (request()->get('purchase_price', false)) {

                        $query->where('inventory.purchase_price', 'like', "%" . request()->get("purchase_price") . "%");

                    }

                    if (request()->get('manufacturing_year', false)) {

                        $query->where('inventory.manufacturing_year', 'like', "%" . request()->get("manufacturing_year") . "%");

                    }

                    if ($booking_month_year = request()->get('booking_month_year')) {

                        $query->havingRaw("booking_month_year LIKE ?", ["%{$booking_month_year}%"]);

                    }

                    if (request()->get('fuel_type', false)) {

                        $query->where('fule_type.title', 'like', "%" . request()->get("fuel_type") . "%");

                    }
                    
                    if ($tat_days = request()->get('tat_days')) {

                        $query->havingRaw("tat_days LIKE ?", ["%{$tat_days}%"]);

                    }
                    
                    if ($tat_status = request()->get('tat_status')) {

                        $query->havingRaw("tat_status LIKE ?", ["%{$tat_status}%"]);

                    }

                })

                ->make(true);

            }    

            return view('AllReport.ppc_report');

        }
        
}