<?php

namespace App\Http\Controllers;

use App\Models\Accessory;
use App\Models\Allocation;
use App\Models\Approval;
use App\Models\Branch;
use App\Models\CarExchange;
use App\Models\Carmodel;
use App\Models\Carvarient;
use App\Models\CashReceipt;
use App\Models\ExtandWarranty;
use App\Models\Fasttag;
use App\Models\Finance;
use App\Models\Insurance;
use App\Models\Lead;
use App\Models\RSA;
use App\Models\OBF;
use App\Models\Order;
use App\Models\BankAccount;
use App\Models\Product;
use App\Models\Setting;
use App\Models\Tax;
use App\Models\User;
use Carbon\Carbon;
use DataTables, DB;
use Illuminate\Http\Request;
use PDF;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

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

    /** index */
        public function index(Request $request)
        {
           // dd(auth()->user()->branch);
            $permission_get = '';
            $data_v = auth()->user()->roles->pluck('data_permission');
            if(!empty($data_v)){
                $permission_get = $data_v[0];
            }


            $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();
            $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();
            $receipt_type = CashReceipt::select('receipt_type')->distinct()->get()->map(function ($item) {
                return [
                    'key' => $item->receipt_type,
                    'value' => $item->receipt_type,
                ];
            })->toArray();


            $cust_name = $request->client;
            $kec = $request->kec;
            $variants = $request->varient;
            $locations = $request->location;
            $startdates = $request->start_date;
            $enddates = $request->end_date;

            if ($request->ajax()) {
                $a_id = auth()->id();

                // $data = OBF::select(
                //     'obf.id',
                //     'obf.customer_name',
                //     'obf.ship_to_customer_name',
                //     'cash_receipt.id AS cash_receipt_id',
                //     'obf.booking_date',
                //     'obf.status',
                //     'car_model.name AS product',
                //     DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                //     'obf.on_road_price',
                //     'car_varient.name AS car_varient_name',
                //     'branches.name as branch_name',
                //     'obf.gst',
                //     'exteriorcolor.name as exterior_color',
                //     'obf.address',
                //     'obf.registration',
                //     'obf_finance.loan_amount',
                //     // 'obf_finance.net_disbusment', 
                //     // DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.receipt_type = "disbusment_receipt" AND cash_receipt.status != "rejected") as net_disbusment'),
                //     'obf_finance.finance_discount as finance_discount',
                //     'Team_master.team_name',
                //     'obf.way_off',
                //     'obf.offer_ib_amount',
                //     'obf.offer_kin_amount',
                //     'obf.foc_accessories',
                //     'cash_receipt.receipt_type',
                //     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'),
                //     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 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) + 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 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) + 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 cash_receipt.receipt_type = 'access_sort_receipt' AND cash_receipt.status != 'rejected'), 0) ELSE COALESCE((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'), 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'),
                //     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('(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('ROUND(obf.on_road_price - sum(cash_receipt.amount)) as due_amount'),
                //     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 = "allocated" AND inventory.id = obf.inventory_id) as vin_number'),
                //     DB::raw('ROUND(sum(cash_receipt.amount)) as received_amount'),
                //     DB::raw('COUNT(DISTINCT IF(cash_receipt.status = "rejected",cash_receipt.id,null)) as no_of_receipt_rejected'),
                //     DB::raw('(SELECT COUNT(*) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id) as no_of_receipt'))
                //  ->leftjoin('products' ,'obf.product_id' ,'products.id')
                //  ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                //  ->leftjoin('users','users.id','=','obf.sales_person_id')
                //  ->leftjoin('cash_receipt','cash_receipt.obf_id','=','obf.id')
                //  ->leftjoin('orders','orders.obf_id','=','obf.id')
                //  ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                //  ->leftjoin('branches','branches.id','=','obf.branch_id')
                //  ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_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('inventory','inventory.name','=','obf.inventory_id') 
                // ->whereIn('obf.approval_status', [
                //     'obf_tl_accepted', 
                //     'obf_sm_accepted', 
                //     'obf_gm_accepted',  
                //     'obf_accountant_accepted'
                // ])->groupBy('obf.id');
            
                // if(!empty(auth()->user()->branch)){
                //     $data =$data->whereRaw('FIND_IN_SET(obf.branch_id ,"'.auth()->user()->branch.'")');
                // }
                
                // $data =$data->orderBy('obf.id' ,'desc');
                
                // Aggregate subquery for cash_receipt
                /*$cashReceiptAggregates = DB::table('cash_receipt')
                    ->selectRaw('
                        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 net_disbusment,
                        SUM(amount) AS received_amount,
                        COUNT(DISTINCT IF(status = "rejected", id, NULL)) AS no_of_receipt_rejected,
                        COUNT(*) AS no_of_receipt
                    ')
                    ->groupBy('obf_id');*/
                $cashReceiptAggregates = DB::table('cash_receipt')
                ->selectRaw('
                    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 net_disbusment,
                    SUM(CASE WHEN receipt_type = "access_sort_receipt" AND status != "rejected" THEN amount ELSE 0 END) AS access_sort_amount,
                    SUM(amount) AS received_amount,
                    COUNT(DISTINCT IF(status = "rejected", id, NULL)) AS no_of_receipt_rejected,
                    COUNT(*) AS no_of_receipt,
                    MAX(id) AS cash_receipt_id,
                    MAX(receipt_type) AS receipt_type
                ')
                ->groupBy('obf_id');
    
                
                // Aggregate subquery for exchange_purchase
                /*$exchangePurchaseSubquery = DB::table('exchange_purchase')
                    ->selectRaw('
                        obf_id,
                        MAX(total_exchange_amount) AS total_exchange_amount
                    ')
                    ->whereIn('status',['active','sell'])
                    ->groupBy('obf_id');*/
                $exchangePurchaseSubquery = DB::table('exchange_purchase')
                ->selectRaw('
                    obf_id,
                    MAX(total_exchange_amount) AS total_exchange_amount
                ')
                ->whereIn('status',['active','sell'])
                ->groupBy('obf_id');    
                
                /*$data = OBF::select(
                        'obf.id',
                        'obf.customer_name',
                        'obf.ship_to_customer_name',
                        'cash_receipt.id AS cash_receipt_id',
                        'obf.booking_date',
                        'obf.status',
                        'car_model.name AS product',
                        DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                        'obf.on_road_price',
                        'car_varient.name AS car_varient_name',
                        'branches.name as branch_name',
                        'obf.gst',
                        'exteriorcolor.name as exterior_color',
                        'obf.address',
                        'obf.registration',
                        'obf_finance.loan_amount',
                        'obf_finance.finance_discount as finance_discount',
                        'Team_master.team_name',
                        'obf.way_off',
                        'obf.offer_ib_amount',
                        'obf.offer_kin_amount',
                        'obf.foc_accessories',
                        'cash_receipt.receipt_type',
                        'cash_agg.net_disbusment',
                        DB::raw('(cash_agg.booking_amount + cash_agg.dp_amount + cash_agg.net_disbusment + COALESCE(exchange_agg.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 - (cash_agg.booking_amount + cash_agg.dp_amount + cash_agg.net_disbusment + COALESCE(exchange_agg.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 ((cash_agg.booking_amount + cash_agg.dp_amount + cash_agg.net_disbusment + COALESCE(exchange_agg.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((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'), 0) ELSE COALESCE((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'), 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'),
                        'exchange_agg.total_exchange_amount',
                        'cash_agg.booking_amount',
                        'cash_agg.dp_amount',
                        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 = "allocated" AND inventory.id = obf.inventory_id) as vin_number'),
                        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'),
                        'cash_agg.received_amount',
                        'cash_agg.no_of_receipt_rejected',
                        'cash_agg.no_of_receipt'
                    )
                    ->leftjoin('products' ,'obf.product_id' ,'products.id')
                    ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                    ->leftjoin('users','users.id','=','obf.sales_person_id')
                    ->leftjoin('cash_receipt','cash_receipt.obf_id','=','obf.id')
                    ->leftjoinSub($cashReceiptAggregates, 'cash_agg', function($join){
                        $join->on('cash_agg.obf_id','=','obf.id');
                    })
                    ->leftjoinSub($exchangePurchaseSubquery, 'exchange_agg', function($join){
                        $join->on('exchange_agg.obf_id','=','obf.id');
                    })
                    ->leftjoin('orders','orders.obf_id','=','obf.id')
                    ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                    ->leftjoin('branches','branches.id','=','obf.branch_id')
                    ->leftJoin('exteriorcolor','exteriorcolor.id','=','products.exterior_color')
                    ->leftJoin('obf_finance','obf_finance.obf_id','=','obf.id')
                    ->leftjoin('Team_master','Team_master.id','users.team_name')
                    // ->leftJoin('inventory','inventory.name','=','obf.inventory_id') 
                    ->leftJoin('inventory','inventory.name','=','products.id')
                    ->whereIn('obf.approval_status', [
                        'obf_tl_accepted', 
                        'obf_sm_accepted', 
                        'obf_gm_accepted',  
                        'obf_accountant_accepted'
                    ])
                    ->groupBy('obf.id');*/
                    
                $data = OBF::select(
                    'obf.id',
                    'obf.customer_name',
                    'obf.ship_to_customer_name',
                    'cash_agg.cash_receipt_id AS cash_receipt_id',
                    'obf.booking_date',
                    'obf.status',
                    'car_model.name AS product',
                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                    'obf.on_road_price',
                    'car_varient.name AS car_varient_name',
                    'branches.name as branch_name',
                    'obf.gst',
                    'exteriorcolor.name as exterior_color',
                    'obf.address',
                    'obf.registration',
                    'obf.tl_discount',
                    'obf.sm_discount',
                    'obf.gm_discount',
                    'obf.bh_discount',
                    'obf.ceo_discount',
                    'obf.md_discount',
                    'obf_finance.loan_amount',
                    'obf_finance.finance_discount as finance_discount',
                    'Team_master.team_name',
                    'obf.way_off',
                    'obf.offer_ib_amount',
                    'obf.offer_kin_amount',
                    'obf.foc_accessories',
                    'cash_agg.receipt_type',
            
                    'cash_agg.net_disbusment',
            
                    DB::raw('(cash_agg.booking_amount + cash_agg.dp_amount + cash_agg.net_disbusment + COALESCE(exchange_agg.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.tl_discount, 0) + 
                        COALESCE(obf.sm_discount, 0) + 
                        COALESCE(obf.gm_discount, 0) + 
                        COALESCE(obf.bh_discount, 0) + 
                        COALESCE(obf.ceo_discount, 0) + 
                        COALESCE(obf.md_discount, 0) + 
                        COALESCE(obf.foc_accessories,0) +
                        COALESCE(obf.offer_ib_amount,0) +
                        COALESCE(obf.offer_kin_amount,0)
                    )) as net_total"),
            
                    DB::raw("( obf.on_road_price - (
                        cash_agg.booking_amount +
                        cash_agg.dp_amount +
                        cash_agg.net_disbusment +
                        COALESCE(exchange_agg.total_exchange_amount,0) +
                        COALESCE(obf_finance.finance_discount,0) +
                        COALESCE(obf.way_off,0) +
                        COALESCE(obf.tl_discount, 0) + 
                        COALESCE(obf.sm_discount, 0) + 
                        COALESCE(obf.gm_discount, 0) + 
                        COALESCE(obf.bh_discount, 0) + 
                        COALESCE(obf.ceo_discount, 0) + 
                        COALESCE(obf.md_discount, 0) + 
                        COALESCE(obf.foc_accessories,0) +
                        COALESCE(obf.offer_ib_amount,0) +
                        COALESCE(obf.offer_kin_amount,0)
                    )
                    + CASE
                        WHEN (
                            cash_agg.booking_amount +
                            cash_agg.dp_amount +
                            cash_agg.net_disbusment +
                            COALESCE(exchange_agg.total_exchange_amount,0) +
                            COALESCE(obf_finance.finance_discount,0) +
                            COALESCE(obf.way_off,0) +
                            COALESCE(obf.tl_discount, 0) + 
                            COALESCE(obf.sm_discount, 0) + 
                            COALESCE(obf.gm_discount, 0) + 
                            COALESCE(obf.bh_discount, 0) + 
                            COALESCE(obf.ceo_discount, 0) + 
                            COALESCE(obf.md_discount, 0) + 
                            COALESCE(obf.foc_accessories,0) +
                            COALESCE(obf.offer_ib_amount,0) +
                            COALESCE(obf.offer_kin_amount,0)
                        ) < obf.on_road_price
                        THEN -COALESCE(cash_agg.access_sort_amount,0)
                        ELSE COALESCE(cash_agg.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'),
            
                    'exchange_agg.total_exchange_amount',
                    'cash_agg.booking_amount',
                    'cash_agg.dp_amount',
            
                    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 NOT IN ("inactive","deleted","sold") AND inventory.id = obf.inventory_id) as vin_number'),
            
                    'cash_agg.received_amount',
                    'cash_agg.no_of_receipt_rejected',
                    'cash_agg.no_of_receipt'
                )
            
                ->leftJoinSub($cashReceiptAggregates,'cash_agg',function($join){
                    $join->on('cash_agg.obf_id','=','obf.id');
                })
            
                ->leftJoinSub($exchangePurchaseSubquery,'exchange_agg',function($join){
                    $join->on('exchange_agg.obf_id','=','obf.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('users','users.id','obf.sales_person_id')
                ->leftJoin('branches','branches.id','obf.branch_id')
                ->leftJoin('exteriorcolor','exteriorcolor.id','products.exterior_color')
                ->leftJoin('obf_finance','obf_finance.obf_id','obf.id')
                ->leftJoin('Team_master','Team_master.id','users.team_name')
                ->leftJoin('orders','orders.obf_id','obf.id')
            
                ->whereIn('obf.approval_status',[
                    'obf_tl_accepted',
                    'obf_sm_accepted',
                    'obf_gm_accepted',
                    'obf_accountant_accepted'
                ])
                ->groupBy('obf.id');    
                
                /*if(!empty(auth()->user()->branch)){
                    $data =$data->whereRaw('FIND_IN_SET(obf.branch_id ,"'.auth()->user()->branch.'")');
                }
                
                $data =$data->orderBy('obf.id' ,'desc');*/
                
                if(!empty(auth()->user()->branch)){
                    $data->whereRaw('FIND_IN_SET(obf.branch_id,"'.auth()->user()->branch.'")');
                }
                
                $data->orderBy('obf.id','desc');

                
                return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('receipt_no', function ($data) {
                        $cash_receipt_id = $data->cash_receipt_id ?? '';
                    
                        if (!empty($cash_receipt_id)) {
                            $month = \Carbon\Carbon::now()->format('m');
                            $year = \Carbon\Carbon::now()->format('Y');
                    
                            $branch_full = $data->branch_name ?? '';
                            $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';
                            } elseif (str_contains($branch_full, '_K')) {
                                $b_name = 'IBK';
                            } elseif (str_contains($branch_full, '_M')) {
                                $b_name = 'IBM';
                            }
                    
                            return $cash_receipt_id . $b_name . $month . $year;
                        }
                    
                        return ''; 
                    })
                    ->addColumn('action', function ($data) {
                        $return = '<div class="btn-group">';

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

                        if (auth()->user()->can('cash_receipt-delete')) {
                            // $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                            //                             <i class="fa fa-bars"></i>
                            //                         </a> &nbsp;
                            //                         <ul class="dropdown-menu">
                            //                             <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="account_accepted" data-id="' . base64_encode($data->id) . '">Account Accepted</a></li>
                            //                             <li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="account_rejected" data-id="' . base64_encode($data->id) . '">Account Rejected</a></li>
                            //                             <li><a class="dropdown-item" href="' . route('cash_receipt.obf_summary', ['id' => base64_encode($data->id)]) . '" target="_blank">OBF Summary</a></li>
                            //                         </ul>';
                            
                            $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                            <i class="fa fa-bars"></i>
                                        </a> &nbsp;
                                        <ul class="dropdown-menu">
                                            <li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="account_rejected" data-id="' . base64_encode($data->id) . '">Reject OBF</a></li>
                                            <li><a class="dropdown-item" href="' . route('cash_receipt.obf_summary', ['id' => base64_encode($data->id)]) . '" target="_blank">OBF Summary</a></li>
                                        </ul>';
                        }
                        if (auth()->user()->can('cash_receipt-generate_gate_pass')) {
                            $return .= '<a title="Add Cash" href="' . route('cash_receipt.create', ['id' => base64_encode($data->id),'page' => 'cash_receipt']) . '" class="btn btn-default btn-xs">
                                    <i class="fas fa-file-medical"></i>
                                    </a> &nbsp;';
                        }
                        if (auth()->user()->can('cash_receipt-generate_gate_pass')) {
                            $return .= '<a title="Generate Cash Receipt" href="' . route('cash_receipt.generate_cash_receipt', ['id' => base64_encode($data->id),'page' => 'cash_receipt']) . '" class="btn btn-default btn-xs">
                                    <i class="fas fa-receipt"></i> 
                                    </a> &nbsp;';
                        }

                        $return .= '</div>';

                        return $return;
                    })

                    ->editColumn('booking_date', function($data) {
                        return (!empty($data->booking_date)) ? \Carbon\Carbon::parse($data->booking_date)->format('d-m-Y') : '--';
                    })  
                    ->editColumn('name', function($data) {
                        return $data->customer_name;
                    })
                    ->editColumn('receipt_type', function($data){
                        return ucwords(str_replace('_',' ',$data->receipt_type)) ?? '';
                    })
                    ->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->tl_discount ?? 0) + ($data->gm_discount ?? 0) + ($data->sm_discount ?? 0) + ($data->bh_discount ?? 0) + ($data->ceo_discount ?? 0) + ($data->md_discount ?? 0) + ($data->foc_accessories ?? 0) + ($data->offer_ib_amount ?? 0) + ($data->offer_kin_amount ?? 0);
                        $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->tl_discount ?? 0) + ($data->gm_discount ?? 0) + ($data->sm_discount ?? 0) + ($data->bh_discount ?? 0) + ($data->ceo_discount ?? 0) + ($data->md_discount ?? 0) + ($data->foc_accessories ?? 0) + ($data->offer_ib_amount ?? 0) + ($data->offer_kin_amount ?? 0);
                        return $finance_dis;
                    })
                    ->editColumn('due_amount',function($data){
                        $finance_dis = ($data->finance_discount ?? 0) + ($data->way_off ?? 0) + ($data->tl_discount ?? 0) + ($data->gm_discount ?? 0) + ($data->sm_discount ?? 0) + ($data->bh_discount ?? 0) + ($data->ceo_discount ?? 0) + ($data->md_discount ?? 0) + ($data->foc_accessories ?? 0) + ($data->offer_ib_amount ?? 0) + ($data->offer_kin_amount ?? 0);
                        $book_amt = $data->booking_amount + $data->dp_amount + $data->net_disbusment + $data->total_exchange_amount;
                        $due_amount = $data->on_road_price - $book_amt - $finance_dis;
                        return $due_amount;
                    })
                    ->editColumn('status', function ($data) {
                        if ($data->status == 'accepted') {
                            return '<span class="badge badge-pill badge-success">Active</span>';
                        } else if ($data->status == 'pending') {
                            return '<span class="badge badge-pill badge-warning">Pending</span>';
                        } else if ($data->status == 'deleted') {
                            return '<span class="badge badge-pill badge-danger">Deleted</span>';
                        } else if ($data->status == 'account_rejected') {
                            return '<span class="badge badge-pill badge-danger">Rejected By Cashier</span>';
                        } else if ($data->status == 'obf_rejected') {
                            return '<span class="badge badge-pill badge-danger">OBF Rejected</span>';
                        } else if ($data->status == 'rejected') {
                            return '<span class="badge badge-pill badge-danger">Rejected</span>';
                        } else if ($data->status == 'obf_accepted') {
                            return '<span class="badge badge-pill badge-success">Obf Accepted</span>';
                        } else if ($data->status == 'account_accepted') {
                            // return '<span class="badge badge-pill badge-success">Account Accepted</span>';
                            return '<span class="badge badge-pill badge-success">Receipt Created</span>';
                        }
                    })

                    ->rawColumns(['name', 'action', 'status', 'model'])
                    
                        ->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('receipt_type',false)) {
                                $query->where('cash_receipt.receipt_type', "like", "%".request()->get("receipt_type")."%");
                            }
                            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('branch_name',false)) {
                                $query->where('branches.name', "like", "%".request()->get("branch_name")."%");
                            }
                            if (request()->get('customer_name',false)) {
                                $query->where('obf.customer_name', "like", "%".request()->get("customer_name")."%");
                            }
                            if (request()->get('gst',false)) {
                                $query->where('obf.gst', "like", "%".request()->get("gst")."%");
                            }
                            if (request()->get('ship_to_customer_name',false)) {
                                $query->where('obf.ship_to_customer_name', "like", "%".request()->get("ship_to_customer_name")."%");
                            }
                            if (request()->get('team_name',false)) {
                                $query->where('Team_master.team_name', "like", "%".request()->get("team_name")."%");
                            }
                            if (request()->get('sales_person_name',false)) {
                                $salesPersonName = request()->get('sales_person_name');
                                $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%{$salesPersonName}%"]);
                            }
                            if (request()->get('product',false)) {
                                $query->where('car_model.name', "like", "%".request()->get("product")."%");
                            }
                            if (request()->get('car_varient_name',false)) {
                                $query->where('car_varient.name', "like", "%".request()->get("car_varient_name")."%");
                            }
                            if (request()->get('exterior_color',false)) {
                                $query->where('exteriorcolor.name', "like", "%".request()->get("exterior_color")."%");
                            }
                            if (request()->get('vin_number',false)) {
                                $query->where('inventory.vin_number', "like", "%".request()->get("vin_number")."%");
                            }
                            if (request()->get('on_road_price',false)) {
                                $query->where('obf.on_road_price', "like", "%".request()->get("on_road_price")."%");
                            }
                            if (request()->get('booking_amount', false)) {
                                $bookingAmount = request()->get('booking_amount');
                                $query->having('booking_amount', 'LIKE', "%{$bookingAmount}%");
                            }

                            if (request()->get('dp_amount', false)) {
                                $dpAmount = request()->get("dp_amount");
                                $query->having('dp_amount', 'LIKE', "%{$dpAmount}%");
                            }
                            if (request()->get('loan_amount',false)) {
                                $query->where('obf_finance.loan_amount', "like", "%".request()->get("loan_amount")."%");
                            }
                            if ($netDisbursement = request()->get('net_disbusment')) {
                                $query->havingRaw('CAST(net_disbusment AS CHAR) LIKE ?', ["%{$netDisbursement}%"]);
                            }
                            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 ($dueAmount = request()->get('due_amount')) {
                                $query->havingRaw("due_amount LIKE ?", ["%{$dueAmount}%"]);
                            }
                            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")."%");
                            }
                            if (request()->get('no_of_receipt', false)) {
                                $query->havingRaw("COUNT(cash_receipt.id) LIKE ?",
                                    ['%' . request()->get('no_of_receipt') . '%']);
                            }
                            if (request()->get('no_of_receipt_rejected', false)) {
                                $query->havingRaw("COUNT(DISTINCT IF(cash_receipt.status = 'rejected', cash_receipt.id, NULL)) LIKE ?",
                                    ['%' . request()->get('no_of_receipt_rejected') . '%']
                                );
                            }
                            if (request()->get('status',false)) {
                                $query->where('obf.status', "like", "%".request()->get("status")."%");
                            }
                            
                        })  
                    
                    ->make(true);
            }
            return view('cash_receipt.index')->with(['customer_name'=>$customer_name,'kec_name'=>$kec_name,'varient'=>$varient,'branch'=>$branch,'date'=>$date,'receipt_type'=>$receipt_type]);
        }
    /** index */

    /** Create */
        public function create(Request $request)
        {
            $id = base64_decode($request->id);
            $page = $request->page;
            
            $data = OBF::select('obf.id','obf.customer_name','obf.ship_to_customer_name')
                ->where(['id' => $id])
                ->first();
                
            $bill_to_cust_nm = !empty($data->customer_name) ? 'Bill To: ' .  $data->customer_name : null;
            $ship_to_cust_nm = !empty($data->ship_to_customer_name) ? 'Ship To: ' . $data->ship_to_customer_name : null;
            
            $customer_options = array_filter([
                $bill_to_cust_nm,
                $ship_to_cust_nm,
            ]);
            
            $cash_receipt_data = [];
            if(isset($request->cash_receipt_id) && !empty($request->cash_receipt_id)){
                $cash_receipt_id = base64_decode($request->cash_receipt_id);
                $cash_receipt_data = CashReceipt::where(['id' => $cash_receipt_id])->first();   
            }
            
            $receipt_type = CashReceipt::select('receipt_type')
                ->distinct()
                ->get()
                ->map(function ($item) {
                    return [
                        'key' => $item->receipt_type,
                        'value' => $item->receipt_type,
                    ];
                })
                ->toArray();
            
            
            $bank_account = DB::table('bank_account')->select('id','name')->where('status', 'active')->groupBy('bank_account.id')->get(); 
            
           
            if ($data) {
                return view('cash_receipt.create')->with([
                    'data' => $data,
                    'cash_receipt_data' => $cash_receipt_data,
                    'page' => $page,
                    'bank_account' => $bank_account, // 🔽 PASS TO VIEW
                    'customer_options' => $customer_options,
                ]);
            } else {
                return view('cash_receipt.create')->with('error', 'No record found!');
            }
        }
    /** Create */

    /** Insert */
        public function insert(Request $request)
        {
            
            $request->validate([
                'receipt_type' => 'required|string|in:booking_receipt,downpayment_receipt,disbusment_receipt,other_receipt,access_sort_receipt', 
                'amount' => 'nullable|numeric|min:0',
            ]);

            if (in_array($request->receipt_type, ['booking_receipt','downpayment_receipt','disbusment_receipt','access_sort_receipt','other_receipt']) && ($request->amount == 0 || $request->amount == null)) {
                return redirect()->back()->with('error', 'Amount must be greater than 0.')->withInput();
            }
            $obf_data = OBF::where('id',$request->id)->first();

            if (!empty($obf_data)) {

                // var_dump($obf_data->id);
                $obf_status = '';
                $spcial_case = '';
                $status = ''; 

                $Setting_data = Setting::where('key','MINIMUM_CASH_RECEIPT_BALANCE')->first();

                $MINIMUM_CASH_RECEIPT_BALANCE = 0;
                if(!empty($Setting_data)){
                    if($Setting_data->value != NULL)
                    {
                        $MINIMUM_CASH_RECEIPT_BALANCE = (int) $Setting_data->value;
                    }    
                }
                $Setting_data = Setting::where('key','MAXIMUM_CASH_RECEIPT_BALANCE')->first();

                $MAXIMUM_CASH_RECEIPT_BALANCE = 0;
                if(!empty($Setting_data)){
                    if($Setting_data->value != NULL)
                    {
                        $MAXIMUM_CASH_RECEIPT_BALANCE = (int) $Setting_data->value;
                    }    
                }

                $CashReceipt_sum = (int) CashReceipt::where('obf_id',$request->id)->where('payment_type','cash')->sum('amount');

                if(empty($request->amount) && $request->amount == ''){
                    $request->amount = 0;
                }

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

                $total_sum = $CashReceipt_sum + (int) $request->amount;

                if($request->payment_type == 'cash'){
                    if($total_sum > $MAXIMUM_CASH_RECEIPT_BALANCE){
                        return redirect()->back()->with('error', 'cash receipt Maximum balance is '.$MAXIMUM_CASH_RECEIPT_BALANCE)->withInput();
                    }    
                }

                // die('s');
                /*var_dump($CashReceipt_sum);
                var_dump($MINIMUM_CASH_RECEIPT_BALANCE);
                var_dump($MAXIMUM_CASH_RECEIPT_BALANCE);
                die('ss');*/
                

                if ($total_sum < $MINIMUM_CASH_RECEIPT_BALANCE) {
                    $obf_status = 'account_rejected';
                    $spcial_case = 'yes';
                    $status = 'pending';
                }else{
                    $obf_status = 'account_accepted';
                    $spcial_case = 'no';
                    $status = 'accepted';
                }

                if($obf_status == 'account_accepted'){
                    //notification insert
                    $notification_template_master_data = DB::table('notification_template_master')->select('*')->where(['template_name' => 'cashier_recipt_approved','status' => 'active'])->first();
                    if(!empty($notification_template_master_data)){
                        $customer_name = $obf_data->customer_name ?? null;
                        
                        $car_name_get = '';
                        $product_id = 0;
                        if($obf_data->product_id != null && $obf_data->product_id != ''){
                            $product_id = $obf_data->product_id;
                        }

                        if($product_id != null){
                            $Cardata_get = Product::select('car_model.name as car_name','products.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
                         ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                          ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                          ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
                          ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
                          ->where('products.status', '=', 'active')
                          ->where('products.id', '=', $product_id)  
                          ->first();
                            
                            if(!empty($Cardata_get)){
                                if(!empty($Cardata_get->car_name) && $Cardata_get->car_name != '' && $Cardata_get->car_name != NULL){
                                    $car_name_get .= '('.$Cardata_get->car_name;    
                                    $car_name_get .= ' , '.$Cardata_get->varient_name.')';   
                                }
                            }    
                        }

                        $customer_name_with_car_detail = '';     

                        if($customer_name != null){
                            $customer_name_with_car_detail = $customer_name;
                        }   

                        if($customer_name != null){
                            $customer_name_with_car_detail .= ' '.$car_name_get;
                        }                  
                        
                        $data_new = str_replace("[customer_name_with_car_detail]",$customer_name_with_car_detail,$notification_template_master_data->template_data);

                        $notification_data = [
                            'user_id' => auth()->user()->id,
                            'notification_text' => $data_new,
                            'notification_link' => route('obf_approval.view', ['id' => base64_encode($request->id)]),
                            'created_by' => auth()->user()->id,
                        ];
                        DB::table('notifications')->insert($notification_data);
                    }
                    //notification insert
                }


                if($request->cash_receipt_data_id != ''){
                    //update
                    $data = CashReceipt::select('cash_receipt.*', 'bank_account.name')
                    ->leftJoin('bank_account', 'cash_receipt.bank_account_id', '=', 'bank_account.id')
                    ->where('cash_receipt.id', $request->cash_receipt_data_id)
                    ->first();

                    $data->obf_id = $obf_data->id;
                    $data->receipt_type = $request->receipt_type;
                    $data->amount = $request->amount;
                    $data->payment_type = $request->payment_type;
                    $data->customer_nm = $request->customer_nm;
                    if($request->payment_type == 'cheque')
                    {
                        $data->transaction_no = $request->chq_number;
                        $data->bank_account_id = $request->bank_account_id;
                    }
                    if($request->payment_type == 'vallet_payment')
                    {
                        $data->transaction_no = $request->vallet_number;
                        $data->bank_account_id = $request->bank_account_id;
                    }
                    if($request->payment_type == 'online_transfer')
                    {
                        $data->transaction_no = $request->trans_number;
                        $data->bank_account_id = $request->bank_account_no;
                    }
                    $data->spcial_case = $spcial_case;
                    $data->cash_remark = $request->cash_remark;
                    $data->status = $status;
                    $data->created_at = date('Y-m-d H:i:s');
                    $data->updated_at = date('Y-m-d H:i:s');
                    $data->updated_by = auth()->user()->id;
                    $data->created_by = auth()->user()->id;
                    $data->save();
                    
                    $crud = [
                        'module_nm' => 'cash_receipt',
                        'module_id' => $request->cash_receipt_data_id,
                        'status' => 'cash_receipt_update',
                        'remark' => $request->cash_remark,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => auth()->user()->id,
                    ];
                    \DB::table('logs')->insert($crud);
                }else{
                    //insert
                    $data = new CashReceipt();
                    $data->obf_id = $obf_data->id;
                    $data->receipt_type = $request->receipt_type;
                    $data->amount = $request->amount;
                    $data->payment_type = $request->payment_type;
                    $data->customer_nm = $request->customer_nm;
                    if($request->payment_type == 'cheque')
                    {
                        $data->transaction_no = $request->chq_number;
                        $data->bank_account_id = $request->bank_account_id;
                    }
                    if($request->payment_type == 'vallet_payment')
                    {
                        $data->transaction_no = $request->vallet_number;
                        $data->bank_account_id = $request->bank_account_id;
                    }
                    if($request->payment_type == 'online_transfer')
                    {
                        $data->transaction_no = $request->trans_number;
                        $data->bank_account_id = $request->bank_account_no;
                    }
                    $data->spcial_case = $spcial_case;
                    $data->cash_remark = $request->cash_remark;
                    $data->status = $status;
                    $data->created_at = date('Y-m-d H:i:s');
                    $data->updated_at = date('Y-m-d H:i:s');
                    $data->updated_by = auth()->user()->id;
                    $data->created_by = auth()->user()->id;
                    
                    $data->save();

                    $cash_receipt_id_get = $data->id;
                    
                    $crud = [
                        'module_nm' => 'cash_receipt',
                        'module_id' => $cash_receipt_id_get,
                        'status' => 'cash_receipt_create',
                        'remark' => $request->cash_remark,
                        'created_at' => date('Y-m-d H:i:s'),
                        'created_by' => auth()->user()->id,
                    ];
                    \DB::table('logs')->insert($crud);

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

                    // var_dump($notification_template_master_data);


                    if(!empty($notification_template_master_data)){

                        // echo "11";

                        $obf_data_get = DB::table('obf')->select('*')->where(['obf.id' => $obf_data->id])->first();
                        $customer_name = '';
                        $product_id = 0;
                        if(!empty($obf_data_get)){
                            $customer_name = $obf_data_get->customer_name ?? null;    
                            $product_id = $obf_data_get->product_id ?? null;    
                        }

                        $recipt_date = date('d/m/Y');


                         
                        // die('stp[');

                            // die('ss');
                        

                        $car_name_get = '';

                        /*$product_id = 0;
                        if($request->product_id != null && $request->product_id != ''){
                            $product_id = $request->product_id;
                        }*/

                          if($product_id != null){
                           // DB::enableQueryLog();


                        $Cardata_get = Product::select('car_model.name as car_name','products.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
                     ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                      ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                      ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
                      ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
                      ->where('products.status', '=', 'active')
                      ->where('products.id', '=', $product_id)  
                      ->first();
                          // dd(DB::getQueryLog());

                        /*echo "<pre>";
                        print_r($Cardata_get);
                        die('s');*/

                        
                        if(!empty($Cardata_get)){
                            if(!empty($Cardata_get->car_name) && $Cardata_get->car_name != '' && $Cardata_get->car_name != NULL){
                                $car_name_get .= '('.$Cardata_get->car_name;    
                                $car_name_get .= ' , '.$Cardata_get->varient_name.')';    
                                // $car_name_get .= ' | '$Cardata_get->varient_name;    
                            }
                        }    
                    }
                        // die('stp[--');
                        


                        $customer_name_with_car_detail = '';      

                        if($customer_name != null){
                            $customer_name_with_car_detail = $customer_name;
                        }   

                        if($customer_name != null){
                            $customer_name_with_car_detail .= ' '.$car_name_get;
                        }                  
                        
                        $data_new = str_replace("[customer_name_with_car_detail]",$customer_name_with_car_detail,$notification_template_master_data->template_data);
                        $data_new = str_replace("[Recipt_no]",$cash_receipt_id_get,$data_new);
                        $data_new = str_replace("[Recipt_date]",$recipt_date,$data_new);

                        $notification_data = [
                            'user_id' => auth()->user()->id,
                            'notification_text' => $data_new,
                            //'notification_link' => route('obf.view', ['id' => base64_encode($data->obf_id)]),
                            'notification_link' => route('cash_receipt.generate_cash_receipt', ['id' => base64_encode($data->obf_id),'page' => 'cash_receipt']),
                            'created_by' => auth()->user()->id,
                        ];

                        // var_dump($notification_data);
                         // DB::enableQueryLog();
                        DB::table('notifications')->insert($notification_data);
                         // dd(DB::getQueryLog());

                    }

                    // die('stp[');

                }




                

                $last_id = $data->id;
                // var_dump($last_id);
                if ($last_id) {
                    $crud_data = [
                        'status' => $obf_status,
                        'updated_at' => date('Y-m-d H:i:s'), 
                        'updated_by' => auth()->user()->id
                    ];
                    $obf_update = OBF::where(['id' => $obf_data->id])->update($crud_data);
                    
                    // die(json_encode(array('status'=>true)));
                    //die('ss');
                    $msg = '';
                    if($request->cash_receipt_data_id != ''){
                         $msg = 'Record Updated successfully';
                    }else{
                         $msg = 'Record inserted successfully';
                    }

                    if($request->page == 'cash_receipt'){
                        return redirect()->route('cash_receipt')->with('success', $msg);
                    }else{
                        return redirect()->route('order')->with('success', $msg);
                    }

                    
                    ///  return view('cash_receipt.index')->with('success', 'Record inserted successfully');
                    
                } else {                   
                     return redirect()->back()->with('error', 'Failed to update record2')->withInput();
                }


            }else {
                 return view('cash_receipt.index')->with('error', 'No Record Found!');
            }
            //die('---ss');

        }




        public function insert_old(Request $request)
        {
            $id = $request->id;
            $data = OBF::select('obf.id')
            ->where(['id' => $id])
            ->first();
            if ($data) {
                if ($request->amount < 25000) {
                    $crud = [
                        'obf_id' => $id,
                        'amount' => $request->amount,
                        'spcial_case' => 'yes',
                        'status' => 'pending',
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                        'updated_by' => auth()->user()->id,
                        'created_by' => auth()->user()->id
                    ];
                    $obf_status = 'account_rejected';
                } else {
                    $crud = [
                        'obf_id' => $id,
                        'amount' => $request->amount,
                        'spcial_case' => 'no',
                        'status' => 'accepted',
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                        'updated_by' => auth()->user()->id,
                        'created_by' => auth()->user()->id
                    ];
                    $obf_status = 'account_accepted';
                }
                // DB::beginTransaction();
                // try {
                    DB::enableQueryLog();
                        $cash_receipt = CashReceipt::where(['obf_id' => $id])->first();
                        if(!empty($cash_receipt)){
                            $last_id = CashReceipt::where(['id' => $cash_receipt->id])->update($crud);
                        }else{
                            $last_id = CashReceipt::insertGetId($crud);
                        }
                        // dd($last_id);
                    if ($last_id) {
                        $crud_data = [
                            'status' => $obf_status,
                            'updated_at' => date('Y-m-d H:i:s'), 
                            'updated_by' => auth()->user()->id
                        ];
                        $obf_update = OBF::where(['id' => $id])->update($crud_data);
                        if ($obf_update) {
                            // dd($obf_update);
                            DB::commit();
                            return redirect()->route('cash_receipt')->with('success', 'Record inserted successfully');
                        } else {
                            dd('ho');
                            DB::rollback();
                            return redirect()->back()->with('error', 'Failed to update record1')->withInput();
                        }
                    } else {
                        dd('by');
                        DB::rollback();
                        return redirect()->back()->with('error', 'Failed to update record2')->withInput();
                    }
                // } catch (\Throwable $th) {
                    dd('exit');
                    DB::rollback();
                    return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();
                // }
            } else {
                return view('cash_receipt.index')->with('error', 'No Record Found!');
            }
        }
    /** Insert */

    /** view */
        public function view(Request $request)
        {
            if ($request->ajax()) {
                return true ;
            }
                $id = base64_decode($request->id);
                $path = URL('/uploads/kyc').'/';
                $sales = User::role('sales')->select('id', DB::raw("CONCAT(first_name,' ',last_name) AS sales_person_name"))->where(['status' => 'active'])->get();
                $product = Product::select('id', 'name', 'veriant')->where(['status' => 'active'])->get();
                $tax_1 = Tax::select('id', 'name', 'percentage')->where(['status' => 'active', 'name' => 'registration_tax'])->first();
                $tax_2 = Tax::select('id', 'name', 'percentage')->where(['status' => 'active', 'name' => 'municipal_tax'])->first();
                $tax_3 = Tax::select('id', 'name', 'percentage')->where(['status' => 'active', 'name' => 'tcs_tax'])->first();
                $accessory = Accessory::select('id', 'name', 'price')->where(['status' => 'active'])->get();
                $extanded_warranty = ExtandWarranty::select('id', 'years', 'amount')->where(['status' => 'active'])->get();
                $fasttag = Fasttag::select('id', 'brand_name', 'amount')->where(['status' => 'active'])->get();
                $branch = Branch::select('id', 'name', 'city')->where(['status' => 'active'])->get();
                $insurance = Insurance::select('id', 'name')->where(['status' => 'active'])->get();
                $finance = Finance::select('finance.id', 'finance.name', 'branches.name AS branch_name', 'branches.id AS branch_id')->leftjoin('branches', 'finance.branch_id', 'branches.id')->where(['finance.status' => 'active'])->get();
                $lead = Lead::select('id', 'name')->where(['status' => 'active'])->get();
                $pricelist_master = DB::table('pricelist_master')->select('id','car_model')->get();
                $car_exchange = CarExchange::select('car_exchange.id', 'car_exchange.price', 'cep.name AS product_name')->leftjoin('car_exchange_product AS cep', 'car_exchange.product_id', 'cep.id')->get();
                $rsa = RSA::where(['status' => 'active','deleted_at' => 0])->get();
                // $bank_account = BankAccount::select('id','name')->where(['status'=>'active'])->get();
                $data = OBF::select(
                    'obf.id',
                    'obf.sales_person_id',
                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                    'obf.temporary_id',
                    'obf.booking_date',
                    'obf.customer_name',
                    'obf.customer_type',
                    'branches.name AS branch_name',
                    'branches.id AS branch_id',
                    'obf.company_name',
                    'obf.gst',
                    'obf.address',
                    'obf.registration',
                    'obf.email',
                    'obf.einvoicing_applicable',
                    'obf.pan_number as pan_number',
                    'obf.adhar_number',
                    'obf.licance_number',
                    'obf.contact_number',
                    'obf.dob',
                    'obf.nominee_name',
                    'obf.nominee_reletion',
                    'obf.nominee_age',
                    'obf.occupation',
                    'obf.nominee_dob',
                    'obf.step1_remarks',
                    'obf.other_details_1',
                    'obf.other_details_2',
                    'obf.priclist_detail',
                    'products.name AS product_name',
                    'obf.product_id',
                    'products.veriant',
                    'products.is_applicable_for_mcp',
                    /*'obf.exterior_color',
                    'obf.interior_color',*/
                    'obf.ex_showroom_price',
                    'registration_tax.percentage AS registration_tax',
                    'insurance.name AS insurance',
                    'obf.insurance_id',
                    'municipal_tax.percentage AS municipal_tax',
                    'tcs_tax.percentage AS tcs_tax',
                    'accessories.name AS accessory_name',
                    'obf.accessory_id',
                    'obf.extanded_warranty_id',
                    'extand_warranties.years AS extand_warranties_years',
                    'extand_warranties.amount AS extand_warranties_amount',
                    'fasttags.brand_name AS fasttag_brand_name',
                    'fasttags.amount AS fasttag_amount',
                    'fasttags.id AS fasttag_id',
                    'obf.trad_in_value',
                    'obf.on_road_price',
                    'obf.deal_price',
                    'obf.way_off',
                    'obf.final_on_road_price_after_way_off',
                    'obf.offer_amount',
                    'obf.offer_kin',
                    'obf.offer_kin_amount',
                    'obf.offer_ib',
                    'obf.offer_ib_amount',
                    'obf.step3_remarks',
                    'obf.trade_car_value',
                    'obf.other_accesssories_prise',
                    'obf.on_road_price_word',
                    'obf.on_road_price_word',
                    'obf.finance_id',
                    'finance.name AS finance_name',
                    'finance_branch.name AS finance_branch_name',
                    'lead.name AS lead_name',
                    'obf.lead_id',
                    'obf.booking_amount',
                    'obf.mode_of_payment',
                    'obf.status',
                    'obf.created_by',
                    'obf.updated_by',
                    'obf.created_at',
                    'obf.updated_at',
                    'obf.other_documents',
                    'obf.tcs_tax_id',
                    'tcs_tax.percentage AS tcs_tax',
                    'obf.pan_image','obf.adhar_image','obf.licance_image','obf.sub_lead_id',
                    'customer_type_master.name as customer_type_name',
                    'pricelist_master.price_list_name as price_list_name',
                    'accessories.name AS accessory_name'
                    /*DB::Raw("CASE
                                WHEN " . 'pan_image' . " != '' THEN CONCAT(" . "'" . $path . "'" . ", " . 'pan_image' . ")
                                ELSE CONCAT(" . "'" . $path . "'" . ", 'default.jpg')
                            END as pan_image"),
                    DB::Raw("CASE
                                WHEN " . 'adhar_image' . " != '' THEN CONCAT(" . "'" . $path . "'" . ", " . 'adhar_image' . ")
                                ELSE CONCAT(" . "'" . $path . "'" . ", 'default.jpg')
                            END as adhar_image"),
                    DB::Raw("CASE
                                WHEN " . 'licance_image' . " != '' THEN CONCAT(" . "'" . $path . "'" . ", " . 'licance_image' . ")
                                ELSE CONCAT(" . "'" . $path . "'" . ", 'default.jpg')
                            END as licance_image"),*/
                )
                    ->leftjoin('users', 'obf.sales_person_id', 'users.id')
                    ->leftjoin('branches', 'obf.branch_id', 'branches.id')
                    ->leftjoin('products', 'obf.product_id', 'products.id')
                    ->leftjoin('taxes AS registration_tax', 'obf.registration_tax_id', 'registration_tax.id')
                    ->leftjoin('taxes AS municipal_tax', 'obf.municipal_tax_id', 'municipal_tax.id')
                    ->leftjoin('taxes AS tcs_tax', 'obf.tcs_tax_id', 'tcs_tax.id')
                    ->leftjoin('insurance', 'obf.insurance_id', 'insurance.id')
                    ->leftjoin('accessories', 'obf.accessory_id', 'accessories.id')
                    ->leftjoin('extand_warranties', 'obf.extanded_warranty_id', 'extand_warranties.id')
                    ->leftjoin('fasttags', 'obf.fasttag_brand_name', 'fasttags.id')
                    ->leftjoin('finance', 'obf.finance_id', 'finance.id')
                    ->leftjoin('branches AS finance_branch', 'obf.finance_branch_id', 'finance_branch.id')
                    ->leftjoin('lead', 'obf.lead_id', 'lead.id')
                    ->leftjoin('customer_type_master','obf.customer_type_new','customer_type_master.id')
                    ->leftjoin('pricelist_master','obf.pricelist_id','pricelist_master.id')
                    ->leftjoin('other_one' ,'obf.other_details_1' ,'other_one.id')
                    ->leftjoin('other_two' ,'obf.other_details_2' ,'other_two.id')
                    ->leftjoin('mcp' ,'mcp.id' ,'obf.convinience_program')
                    ->where(['obf.id' => $id])
                    ->first();

                  $carmodel = Product::select('car_model.name as car_name','products.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
                    ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                    ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                    ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
                    ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
                    ->where('products.status', '=', 'active')
                    ->get();
                    
                $Cardata = Obf::select('obf.id as o_id','obf.product_id as o_product','car_model.name as car_name','car_model.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
                                    ->leftJoin('car_model','car_model.id','=','obf.product_id')
                                    ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
                                    ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')
                                    ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')
                                    ->where('obf.id', '=', $id)  
                                    ->first();

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


                if ($data)
                    return view('cash_receipt.view')->with(['data' => $data,'carmodel' => $carmodel,'Cardata' => $Cardata,'lead' => $lead,'pricelist_master'=>$pricelist_master,'extanded_warranty' => $extanded_warranty,'accessory'=>$accessory,
                    'fasttag'=>$fasttag,'insurance'=>$insurance,'rsa'=>$rsa,'finance'=>$finance]);
                else
                    return view('cash_receipt')->with('error', 'No record found!');
            
        }
    /** view */

    /** change-status */
        public function change_status(Request $request)
        {
            if ($request->ajax()) {
                if (isset($request->id) && $request->id != null) {
                    $id = base64_decode($request->id);
                } else {
                    return response()->json(['status' => 201, 'message' => 'Id not found!']);
                }


                DB::beginTransaction();
                try {
                    $data = OBF::where(['id' => $id])->first();

                    if (!empty($data)) {

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

                                DB::commit();
                                return response()->json(['code' => 200]);
                            } else {
                                DB::rollback();
                                return response()->json(['code' => 201]);
                            }
                        } else if ($request->status == 'account_accepted') {

                            if($request->status == 'account_accepted'){
                                //notification insert
                                $notification_template_master_data = DB::table('notification_template_master')->select('*')->where(['template_name' => 'cashier_recipt_approved','status' => 'active'])->first();
                                if(!empty($notification_template_master_data)){
                                    $customer_name = $data->customer_name ?? null;
                                    
                                    $car_name_get = '';
                                    $product_id = 0;
                                    if($data->product_id != null && $data->product_id != ''){
                                        $product_id = $data->product_id;
                                    }

                                    if($product_id != null){
                                        $Cardata_get = Product::select('car_model.name as car_name','products.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
                                     ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                                      ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                                      ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
                                      ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
                                      ->where('products.status', '=', 'active')
                                      ->where('products.id', '=', $product_id)  
                                      ->first();
                                        
                                        if(!empty($Cardata_get)){
                                            if(!empty($Cardata_get->car_name) && $Cardata_get->car_name != '' && $Cardata_get->car_name != NULL){
                                                $car_name_get .= '('.$Cardata_get->car_name;    
                                                $car_name_get .= ' , '.$Cardata_get->varient_name.')';   
                                            }
                                        }    
                                    }

                                    $customer_name_with_car_detail = '';     

                                    if($customer_name != null){
                                        $customer_name_with_car_detail = $customer_name;
                                    }   

                                    if($customer_name != null){
                                        $customer_name_with_car_detail .= ' '.$car_name_get;
                                    }                  
                                    
                                    $data_new = str_replace("[customer_name_with_car_detail]",$customer_name_with_car_detail,$notification_template_master_data->template_data);

                                    $notification_data = [
                                        'user_id' => auth()->user()->id,
                                        'notification_text' => $data_new,
                                        'notification_link' => route('obf_approval.view', ['id' => base64_encode($id)]),
                                        'created_by' => auth()->user()->id,
                                    ];
                                    DB::table('notifications')->insert($notification_data);
                                }
                                //notification insert
                            }


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

                            if ($update) {
                                DB::commit();
                                return response()->json(['code' => 200]);
                            } else {
                                DB::rollback();
                                return response()->json(['code' => 201]);
                            }
                        } else {
                            $update = OBF::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
                            if ($update) {

                                DB::commit();
                                return response()->json(['code' => 200]);
                            } else {
                                DB::rollback();
                                return response()->json(['code' => 201]);
                            }
                        }
                    } else {
                        DB::rollback();
                        return response()->json(['code' => 201]);
                    }
                } catch (\Throwable $th) {
                    DB::rollback();
                    return response()->json(['code' => 201]);
                }
            }
        }
    /** change-status */

    /** change_status_delete */
        public function change_status_delete(Request $request){
            if (!$request->ajax()) { exit('No direct script access allowed'); }
            $id = base64_decode($request->id);
           
            $data = CashReceipt::where(['id' => $id])->first();

            if (!empty($data)) {
                $update = CashReceipt::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
                if ($update) {
                    return response()->json(['code' => 200]);
                } else {
                    return response()->json(['code' => 201]);
                }
            } else {
                return response()->json(['code' => 201]);
            }
            
        }
    /** change_status_delete */
    
    public function obf_summary(Request $request){

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

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



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

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

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

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

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

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

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



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

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

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

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

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

                

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

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

       

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

        'obf_fasttag.fasttag_number','obf_fasttag.fasttag_brand','obf_fasttag.date_of_issue','obf_fasttag.fasttag_amount','obf_fasttag.opening_stock','obf_fasttag.status as fasttag_status','obf.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'           

        )

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

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

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

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

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

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

        ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        ->first();


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



        //   $accessory_name = OBF::select('accessories.id' , 'accessories.name as accessory_name')->leftjoin('accessories' ,'accessories.id','obf.accessory_id')->where('obf.id' , $id)->get();

            //dd($accessory_name);

           /* $fast_tags = Fasttag::select('fasttags.id', 'fasttags.brand_name' ,'fasttags.amount')->where(['fasttags.status' => 'active','obf.id' => $id])->get();*/



          $leads = OBF::select('lead.id' ,'lead.name')->leftjoin('lead' ,'lead.id','obf.lead_id')->where('obf.id' , $id)->get();

         /* $leads = OBF::select('lead.id' ,'lead.name')->leftjoin('lead' ,'lead.id','obf.lead_id')->where('obf.id' , $id)->get();*/



             $carmodel = Product::select('car_model.name as car_name','products.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')

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

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

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

                    ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')

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

                    ->get();



                    // dd($carmodel);





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

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

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

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

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

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

                            ->first();



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

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

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

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

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

        ->first();
       
        $price_list_name = DB::table('pricelist_master')
    ->select('price_list_name')
    ->where('id',  $data->pricelist_id)
    ->get();
         $Inventory_data = [];

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

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

         }



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



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



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

         $user_role = $user->getRoleNames();



         



        return view('cash_receipt.summary')->with(['price_list_name'=>$price_list_name,'data' =>$data,'sales' => $sales ,'product' => $product ,'taxOne' => $tax_1,'taxTwo' => $tax_2 ,'taxThree' => $tax_3,'accessory' => $accessory ,'extanded_warranty' => $extanded_warranty ,'fasttag' => $fasttag ,'branch' => $branch ,'insurance' => $insurance ,'car_exchange' => $car_exchange ,'carmodel' => $carmodel ,'Cardata' => $Cardata, 'finance' => $finance ,'lead' => $lead,'Inventory_data' => $Inventory_data,'fule' => $fule,'user_role'=> $user_role[0],'leads'=>$leads]);



    }

    /** Generate Cash-receipt */
        public function generate_cash_receipt(Request $request)
        {
            ini_set('memory_limit', '1024M');   
            
            $id = base64_decode($request->id);
            $page = $request->page;


            $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',
                'branches.name AS branch_name',
                'branches.id AS branch_id',
                'obf.company_name',
                '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',
                'products.name AS product_name',
                'obf.product_id',
                'products.veriant',
                'products.is_applicable_for_mcp',
                'products.is_applicable_for_mcp',
                /*'obf.exterior_color',
                'obf.interior_color',*/
                'obf.ex_showroom_price',
                'registration_tax.percentage AS registration_tax',
                'insurance.name AS insurance',
                'obf.insurance_id',
                'municipal_tax.percentage AS municipal_tax',
                'tcs_tax.percentage AS tcs_tax',
                'accessories.name AS accessory_name',
                'obf.accessory_id',
                'obf.extanded_warranty_id',
                'extand_warranties.years AS extand_warranties_years',
                'extand_warranties.amount AS extand_warranties_amount',
                'fasttags.brand_name AS fasttag_brand_name',
                'fasttags.amount AS fasttag_amount',
                'fasttags.id AS fasttag_id',
                'obf.trad_in_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',
                'cash_receipt.bank_account_id',
                'cash_receipt.amount',
                'cash_receipt.id AS cash_receipt_id',
                'cash_receipt.cash_remark AS cash_remark',
                'cash_receipt.payment_type AS cash_receipt_payment_type',
                'car_model.name AS car_model_name',
                'car_varient.name AS car_varient_name',
                'interiorcolor.name AS interiorcolor_name',
                'exteriorcolor.name AS exteriorcolor_name',
                DB::raw("
                    CASE 
                        WHEN cash_receipt.customer_nm IS NOT NULL AND cash_receipt.customer_nm != '' 
                        THEN cash_receipt.customer_nm 
                        ELSE obf.customer_name 
                    END as customer_nm
                ")

            )
                ->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('accessories', 'obf.accessory_id', 'accessories.id')
                ->leftjoin('extand_warranties', 'obf.extanded_warranty_id', 'extand_warranties.id')
                ->leftjoin('fasttags', 'obf.fasttag_brand_name', 'fasttags.brand_name')
                ->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('cash_receipt', 'cash_receipt.obf_id', 'obf.id')
                ->where(['obf.id' => $id])
                ->where('cash_receipt.status','!=','rejected')
                ->orderBy('obf.id' ,'desc')
                ->get();
                //->first();
         
                foreach ($data as $item) {
                    if (!empty($item->cash_receipt_id)) {
                        $branch_full = $item->branch_name ?? '';
                        $month = \Carbon\Carbon::now()->format('m');
                        $year = \Carbon\Carbon::now()->format('Y');
                
                        $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';
                        // }
                        
                        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';
                        } elseif (str_contains($branch_full, '_K')) {
                            $b_name = 'IBK';
                        } elseif (str_contains($branch_full, '_M')) {
                            $b_name = 'IBM';
                        }
                
                        $item->receipt_no = $item->cash_receipt_id . $b_name . $month . $year;
                    } else {
                        $item->receipt_no = null;
                    }
                }
            if ($data) {
                //$obf = OBF::where(['id' => $data->id])->first();
                $obf = OBF::where(['id' => $id])->first();
                if ($obf) {
                    $crud = [
                        'order_id' => 'Order_ID' . Date('YmdHis'),
                        //'obf_id' => $data->id,
                        'obf_id' => $id,
                        //'branch_id' => $data->branch_id,
                        'branch_id' => $obf->branch_id,
                        'created_by' => auth()->user()->id,
                        'created_at' => date('Y-m-d H:i:s'),
                    ];
                    $curd_update = [
                        'updated_by' => auth()->user()->id,
                        'updated_at' => date('Y-m-d H:i:s')
                    ];
                    $get_order = Order::where(['obf_id' => $id])->first();
                    if(!empty($get_order)){
                        $order = Order::where(['id' => $get_order->id])->update($curd_update);
                    }else{
                        $order = Order::insertGetId($crud);
                    }
                    if ($order) {
                        return view('cash_receipt.cash_receipt')->with(['data' => $data,'page' => $page]);
                    } else {
                        return view('cash_receipt')->with('error', 'Faild to enter in order!');
                    }
                } else {
                    return view('cash_receipt.cash_receipt')->with(['data' => $data,'page' => $page]);
                }
            } else {
                return view('cash_receipt')->with('error', 'No Data Found!');
            }
        }
    /** Generate Cash-receipt */

    public function recipt_pdf(Request $request)
    {
        
        $obf_id = base64_decode($request->id);
        $page = $request->page;
        $cash_receipt_id = base64_decode($request->cash_receipt_id);
        
       /*$img = DB::table('global_configuration')->select('*')->where('status','active')->first();
        //dd($img);
        $img1 = $img->cash_receipt_logo1;
        $img2 = $img->cash_receipt_logo2;*/
        $img = DB::table('global_configuration')->select('*')->where('status','active')->first();
        $img1 = $img->invoice_logo1 ?? '';
        $img2 = $img->invoice_logo2 ?? '';
       /*if($img == null){
           $img1 = "http://erp.ibgroup.in/public/assets/img/111.jpg";
           $img2 = "http://erp.ibgroup.in/public/assets/img/222.jpg";
       }
       else{
           $img1 = $img->cash_receipt_logo1;
           $img2 = $img->cash_receipt_logo2;
       }
*/
       $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',
                'branches.name AS branch_name',
                'branches.id AS branch_id',
                'obf.company_name',
                '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',
                'products.name AS product_name',
                'obf.product_id',
                'products.veriant',
                'products.is_applicable_for_mcp',
                'products.is_applicable_for_mcp',
                /*'obf.exterior_color',
                'obf.interior_color',*/
                'obf.ex_showroom_price',
                'registration_tax.percentage AS registration_tax',
                'insurance.name AS insurance',
                'obf.insurance_id',
                'municipal_tax.percentage AS municipal_tax',
                'tcs_tax.percentage AS tcs_tax',
                'accessories.name AS accessory_name',
                'obf.accessory_id',
                'obf.extanded_warranty_id',
                'extand_warranties.years AS extand_warranties_years',
                'extand_warranties.amount AS extand_warranties_amount',
                'fasttags.brand_name AS fasttag_brand_name',
                'fasttags.amount AS fasttag_amount',
                'fasttags.id AS fasttag_id',
                'obf.trad_in_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',
                'cash_receipt.amount as cash_receipt_amount',
                'cash_receipt.id AS cash_receipt_id',
                DB::raw("
                    CASE 
                        WHEN cash_receipt.customer_nm IS NOT NULL AND cash_receipt.customer_nm != '' 
                        THEN cash_receipt.customer_nm 
                        ELSE obf.customer_name 
                    END as customer_nm
                "),
                'cash_receipt.payment_type AS cash_receipt_payment_type',
                'cash_receipt.transaction_no',
                'cash_receipt.receipt_type',
                'cash_receipt.cash_remark',
                'cash_receipt.created_at AS cash_receipt_created_at',
                'car_model.name AS car_model_name',
                'car_varient.name AS car_varient_name',
                'interiorcolor.name AS interiorcolor_name',
                'exteriorcolor.name AS exteriorcolor_name',
            )
                ->leftjoin('users', 'obf.sales_person_id', 'users.id')
                ->leftjoin('branches', 'obf.branch_id', 'branches.id')
                ->leftjoin('products', 'obf.product_id', 'products.id')
                ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
                ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
                ->leftjoin('taxes AS registration_tax', 'obf.registration_tax_id', 'registration_tax.id')
                ->leftjoin('taxes AS municipal_tax', 'obf.municipal_tax_id', 'municipal_tax.id')
                ->leftjoin('taxes AS tcs_tax', 'obf.tcs_tax_id', 'tcs_tax.id')
                ->leftjoin('insurance', 'obf.insurance_id', 'insurance.id')
                ->leftjoin('accessories', 'obf.accessory_id', 'accessories.id')
                ->leftjoin('extand_warranties', 'obf.extanded_warranty_id', 'extand_warranties.id')
                ->leftjoin('fasttags', 'obf.fasttag_brand_name', 'fasttags.brand_name')
                ->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('cash_receipt', 'cash_receipt.obf_id', 'obf.id')
                ->where(['obf.id' => $obf_id, 'cash_receipt.id' => $cash_receipt_id])
                ->where('cash_receipt.status','!=','rejected')
                ->orderBy('obf.id' ,'desc')
                ->first();


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

            PDF::SetAuthor('Nicola Asuni');
            PDF::SetTitle('RECEIPT');
            PDF::SetSubject('RECEIPT');
            PDF::setImageScale(PDF_IMAGE_SCALE_RATIO);
            PDF::AddPage('L', 'A4');
            PDF::Image(public_path('uploads/global_configuration/invoice_logo_two/'.$img2), 15, 8, 45, 20, 'PNG');
            PDF::Image(public_path('uploads/global_configuration/invoice_logo_one/'.$img1), 235, 11, 45, 12, 'PNG');
            $data->customer_name = isset($data->customer_name) ? $data->customer_name : "N/A";
            $data->contact_number = isset($data->contact_number) ? $data->contact_number : "N/A";
            $data->address = isset($data->address) ? $data->address : "N/A";
            $data->cash_receipt_id = isset($data->cash_receipt_id) ? $data->cash_receipt_id : "N/A";
            $data->cash_receipt_payment_type = isset($data->cash_receipt_payment_type) ? $data->cash_receipt_payment_type : "N/A";
            $data->cash_receipt_created_at = isset($data->cash_receipt_created_at) ? date("d/m/Y",strtotime($data->cash_receipt_created_at)) : "N/A";
            $data->finance_name = isset($data->finance_name) ? $data->finance_name : "N/A";
            $data->cash_receipt_amount = isset($data->cash_receipt_amount) ? $data->cash_receipt_amount : "N/A";
            $data->car_model_name = isset($data->car_model_name) ? $data->car_model_name : "N/A";
            $data->car_varient_name = isset($data->car_varient_name) ? $data->car_varient_name : "N/A";
            $data->interiorcolor_name = isset($data->interiorcolor_name) ? $data->interiorcolor_name : "N/A";
            $data->exteriorcolor_name = isset($data->exteriorcolor_name) ? $data->exteriorcolor_name : "N/A";

            $data->receipt_type = isset($data->receipt_type) ? $data->receipt_type : "N/A";
            $data->cash_remark = isset($data->cash_remark) ? $data->cash_remark : "N/A";

            


            $data->sales_person_name = isset($data->sales_person_name) ? $data->sales_person_name : "N/A";
            $amount_word = $this->prisetoword($data->cash_receipt_amount);

            $receipt_title = '';
            $payment_type = '';
            $payment_method = '';
            /*$cheque_no
            $cheque_date 
            $bank_name */

            /*var_dump($data->cash_receipt_payment_type);
            die('stp[');*/
            
            if($data->cash_receipt_payment_type == 'online_transfer'){
                $receipt_title = 'PAYMENT RECEIPT';
                $payment_type = 'bank';
            }else{
                $receipt_title = 'PAYMENT RECEIPT';
                $payment_type = 'cash';
            }
            $payment_method = str_replace('_', ' ', $data->cash_receipt_payment_type);
            
            $receipt_type = ucwords(str_replace('_', ' ', $data->receipt_type));
            
            
           // $img1 = 'http://erp.ibgroup.in/public/assets/img/111.jpg';
          //  $img2 = 'http://erp.ibgroup.in/public/assets/img/222.jpg';
            
            //receipt no
            
            $month = \Carbon\Carbon::now()->format('m');
            $year = \Carbon\Carbon::now()->format('Y');
    
            $branch_full = $data->branch_name ?? '';
            $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';
            // }
            
            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';
            } elseif (str_contains($branch_full, '_K')) {
                $b_name = 'IBK';
            } elseif (str_contains($branch_full, '_M')) {
                $b_name = 'IBM';
            }
            
                        
            $tbl = '<div style="border:1px solid black;">   
                        <table cellspacing="0" cellpadding="1" border="0">
                            <tr>
                                <td rowspan="2" style="width:20%;"><span><img src="'.$img1.'" style="height:80px;"></span></td>
                                <td align="center" style="width:60%;font-size:42px;"><b>SHIVAM KIA</b></td>
                                <td rowspan="2" style="width:20%;"><span><img src="'.$img2.'" style="max-height:80px; max-width:100px; height:auto;"></span></td>
                            </tr>
                        </table><br>
                        <table cellspacing="0" cellpadding="1" border="0">
                            
                            <tr>
                                <th align="center" style="border:1px 0px 1px solid black;font-size:22px;"><b>NEW CAR SALES PAYMENT RECEIPT</b></th>
                            </tr>
                           
                            
                        </table>
                        <table cellspacing="0" cellpadding="5" border="0">
                            <tr>
                                <td rowspan="2" style="width:70%;border-right:1px solid black;"><b>Received With Thanks From: </b>'.str_replace(['Bill To: ', 'Ship To: '], '', $data->customer_nm).' <br><b>Mobile No. : </b>'.$data->contact_number.' <br> '.$data->address.'.</td>
                                <td style="width:30%;"><br><b>Branch </b>: '.strtoupper($data->branch_name).'<br><b>Receipt No. : </b>'.$cash_receipt_id.$b_name.$month.$year.'<br><b>Receipt Type. : </b>'.$receipt_type.'<br><b>Receipt Date :</b>'.$data->cash_receipt_created_at.'</td>
                            </tr>
                        </table>
                        <table cellspacing="0" cellpadding="5" border="0">
                            <tr>
                                <td style="width:70%;border-right:1px solid black;border-top:1px solid black;border-bottom:1px solid black;"><b>Model: </b>'.$data->car_model_name.' | '.$data->car_varient_name.'<br><b>Color : </b>'.$data->exteriorcolor_name.' | '.$data->interiorcolor_name.'<br><b>KEC / Executive : </b>'.$data->sales_person_name.'<br><b>Receipt Remark : </b>'.$data->cash_remark.'</td>
                                <td style="width:30%;border-top:1px solid black;border-bottom:1px solid black;">
                                    <b>Payment Detail</b><br>
                                    Payment Type : '.$payment_method.'<br>
                                    <b>Hyp/H : </b>'.$data->finance_name.' <br>
                                    Transaction No : '.$data->transaction_no.'
                                </td>
                            </tr>
                            <tr>
                                <td style="width:70%;border-right:1px solid black;border-top:1px solid black;border-bottom:1px solid black;"><b>Rupees in words :</b> '.$amount_word.'ONLY</td>
                                <td style="width:30%;border-right:1px solid black;border-top:1px solid black;border-bottom:1px solid black;"><b>Rs. </b>'.$data->cash_receipt_amount.'/- </td>
                            </tr>
                            <tr>
                                <td style="width:70%;"><b>GST No. :</b> 24ABACS4515J1ZH</td>
                                <td style="width:30%;text-align:right;"><b>'.$data->branch_name.'</b></td>
                            </tr>
                            <tr>
                                <td style="width:70%;">Price Prevailling at the time of delivery will be applicable<br>Rs. 500/- will be charged from customer as Cheque return charges.<br>Rs. 500/- will be charged from the customer against booking cancellation.<br>Consumer/Corporate offer are subject to change without prior notice and will be given/applicable as per the norms.<br>IF Payment by cheque, Then payment is subject to realization.
                                </td>
                                <td style="width:30%;text-align:right; font-size:10px;"><br><br><br><br><br><br>Authorized Signatory</td>
                                
                            </tr>
                            <tr>
                                <td style="width:70%;"><br><br><b>Customer Signature</b></td>
                                <td></td>
                            </tr>
                        </table>
                    </div>';

                    //<br><b>Booking No. :</b>B/NXA/22-23/00038
                    //<br>Created by : abc xyz

            PDF::writeHTML($tbl, true, false, false, false, '');

            PDF::SetFont('dejavusans', '', 10);
            //$content = "Office Copy";
            PDF::SetXY(270, 42);
            //PDF::Cell(0, 0, $content);
            PDF::Output('receipt.pdf', 'I');
    }



  public function recipt_pdf_share(Request $request)
    {
        
        // $obf_id = base64_decode($request->id);
        // $page = $request->page;
        $cash_receipt_id = base64_decode($request->cash_receipt_id);
        
       $img = DB::table('global_configuration')->select('*')->where('status','active')->first();
        //dd($img);
        $img1 = $img->cash_receipt_logo1;
        $img2 = $img->cash_receipt_logo2;
       /*if($img == null){
           $img1 = "http://erp.ibgroup.in/public/assets/img/111.jpg";
           $img2 = "http://erp.ibgroup.in/public/assets/img/222.jpg";
       }
       else{
           $img1 = $img->cash_receipt_logo1;
           $img2 = $img->cash_receipt_logo2;
       }
*/
       $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',
                'branches.name AS branch_name',
                'branches.id AS branch_id',
                'obf.company_name',
                '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',
                'products.name AS product_name',
                'obf.product_id',
                'products.veriant',
                'products.is_applicable_for_mcp',
                'products.is_applicable_for_mcp',
                /*'obf.exterior_color',
                'obf.interior_color',*/
                'obf.ex_showroom_price',
                'registration_tax.percentage AS registration_tax',
                'insurance.name AS insurance',
                'obf.insurance_id',
                'municipal_tax.percentage AS municipal_tax',
                'tcs_tax.percentage AS tcs_tax',
                'accessories.name AS accessory_name',
                'obf.accessory_id',
                'obf.extanded_warranty_id',
                'extand_warranties.years AS extand_warranties_years',
                'extand_warranties.amount AS extand_warranties_amount',
                'fasttags.brand_name AS fasttag_brand_name',
                'fasttags.amount AS fasttag_amount',
                'fasttags.id AS fasttag_id',
                'obf.trad_in_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',
                'cash_receipt.amount as cash_receipt_amount',
                'cash_receipt.id AS cash_receipt_id',
                'cash_receipt.payment_type AS cash_receipt_payment_type',
                'cash_receipt.transaction_no',
                'cash_receipt.receipt_type',
                'cash_receipt.cash_remark',
                'cash_receipt.created_at AS cash_receipt_created_at',
                'car_model.name AS car_model_name',
                'car_varient.name AS car_varient_name',
                'interiorcolor.name AS interiorcolor_name',
                'exteriorcolor.name AS exteriorcolor_name'
            )
                ->leftjoin('users', 'obf.sales_person_id', 'users.id')
                ->leftjoin('branches', 'obf.branch_id', 'branches.id')
                ->leftjoin('products', 'obf.product_id', 'products.id')
                ->leftjoin('car_model', 'car_model.id', 'products.car_model')
                ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
                ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
                ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
                ->leftjoin('taxes AS registration_tax', 'obf.registration_tax_id', 'registration_tax.id')
                ->leftjoin('taxes AS municipal_tax', 'obf.municipal_tax_id', 'municipal_tax.id')
                ->leftjoin('taxes AS tcs_tax', 'obf.tcs_tax_id', 'tcs_tax.id')
                ->leftjoin('insurance', 'obf.insurance_id', 'insurance.id')
                ->leftjoin('accessories', 'obf.accessory_id', 'accessories.id')
                ->leftjoin('extand_warranties', 'obf.extanded_warranty_id', 'extand_warranties.id')
                ->leftjoin('fasttags', 'obf.fasttag_brand_name', 'fasttags.brand_name')
                ->leftjoin('finance', 'obf.finance_id', 'finance.id')
                ->leftjoin('branches AS finance_branch', 'obf.finance_branch_id', 'finance_branch.id')
                ->leftjoin('lead', 'obf.lead_id', 'lead.id')
                ->leftjoin('cash_receipt', 'cash_receipt.obf_id', 'obf.id')
                ->where(['cash_receipt.id' => $cash_receipt_id])
                ->where('cash_receipt.status','!=','rejected')
                ->orderBy('obf.id' ,'desc')
                ->first();


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

            PDF::SetAuthor('Nicola Asuni');
            PDF::SetTitle('RECEIPT');
            PDF::SetSubject('RECEIPT');
            PDF::setImageScale(PDF_IMAGE_SCALE_RATIO);
            PDF::AddPage('L', 'A4');
            /*PDF::Image('assets/img/atul-logo.jpg', 15, 18, 23, 24, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);*/

            PDF::Image(public_path('uploads/global_configuration/cash_receipt_logo_one/'.$img1), 15, 11, 46, 19, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);


            PDF::Image(public_path('uploads/global_configuration/cash_receipt_logo_two/'.$img2), 180, 14, 100, 16, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);

            /*PDF::Image(public_path('assets/img/ib_logo.jpeg'), 15, 14, 60, 12, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);*/
            
            $data->customer_name = isset($data->customer_name) ? $data->customer_name : "N/A";
            $data->contact_number = isset($data->contact_number) ? $data->contact_number : "N/A";
            $data->address = isset($data->address) ? $data->address : "N/A";
            $data->cash_receipt_id = isset($data->cash_receipt_id) ? $data->cash_receipt_id : "N/A";
            $data->cash_receipt_payment_type = isset($data->cash_receipt_payment_type) ? $data->cash_receipt_payment_type : "N/A";
            $data->cash_receipt_created_at = isset($data->cash_receipt_created_at) ? date("d/m/Y",strtotime($data->cash_receipt_created_at)) : "N/A";
            $data->finance_name = isset($data->finance_name) ? $data->finance_name : "N/A";
            $data->cash_receipt_amount = isset($data->cash_receipt_amount) ? $data->cash_receipt_amount : "N/A";
            $data->car_model_name = isset($data->car_model_name) ? $data->car_model_name : "N/A";
            $data->car_varient_name = isset($data->car_varient_name) ? $data->car_varient_name : "N/A";
            $data->interiorcolor_name = isset($data->interiorcolor_name) ? $data->interiorcolor_name : "N/A";
            $data->exteriorcolor_name = isset($data->exteriorcolor_name) ? $data->exteriorcolor_name : "N/A";

            $data->receipt_type = isset($data->receipt_type) ? $data->receipt_type : "N/A";
            $data->cash_remark = isset($data->cash_remark) ? $data->cash_remark : "N/A";

            


            $data->sales_person_name = isset($data->sales_person_name) ? $data->sales_person_name : "N/A";
            $amount_word = $this->prisetoword($data->cash_receipt_amount);

            $receipt_title = '';
            $payment_type = '';
            $payment_method = '';
            /*$cheque_no
            $cheque_date 
            $bank_name */

            /*var_dump($data->cash_receipt_payment_type);
            die('stp[');*/
            
            if($data->cash_receipt_payment_type == 'online_transfer'){
                $receipt_title = 'PAYMENT RECEIPT';
                $payment_type = 'bank';
            }else{
                $receipt_title = 'PAYMENT RECEIPT';
                $payment_type = 'cash';
            }
            $payment_method = str_replace('_', ' ', $data->cash_receipt_payment_type);
            
            $receipt_type = ucwords(str_replace('_', ' ', $data->receipt_type));
            
            
           // $img1 = 'http://erp.ibgroup.in/public/assets/img/111.jpg';
          //  $img2 = 'http://erp.ibgroup.in/public/assets/img/222.jpg';
            
            //receipt no
            // $month = Carbon::now()->month;
            // $year = Carbon::now()->year;
            // $branch = $data->branch_name;
            // if($branch == 'Rajkot'){
            //     $b_name = 'RJT';
            // }
            // elseif($branch == 'Jamnagar'){
            //     $b_name = 'Jam';
            // }
            // elseif($branch == 'Junagadh'){
            //     $b_name = 'Juna';
            // }elseif($branch == 'Morbi'){
            //     $b_name = 'Mor';
            // }else{
            //     $b_name = '';
            // }
            $cash_receipt_id = $data->cash_receipt_id ?? '';
            if (!empty($cash_receipt_id)) {
                $month = \Carbon\Carbon::now()->format('m');
                $year = \Carbon\Carbon::now()->format('Y');
        
                $branch_full = $data->branch_name ?? '';
                $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';
                // }
                
                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';
                } elseif (str_contains($branch_full, '_K')) {
                    $b_name = 'IBK';
                } elseif (str_contains($branch_full, '_M')) {
                    $b_name = 'IBM';
                }
        
                return $cash_receipt_id . $b_name . $month . $year;
            }
        //receipt no
        
             /*<h1 align="center" style="font-size:26px;">ATUL MOTORS JAM LLP</h1>
                        <p align="center">Near Royal Enfield, Jamnagar-Rajkot Highway, Hapa, Jamnagar - 361120, GUJARAT, INDIA.</p>*/
            $tbl = '<div style="border:1px solid black;">   
                        <table cellspacing="0" cellpadding="1" border="0">
                            <tr>
                               <td rowspan="2" style="width:68%;"><span><img src="'.$img1.'" style="height:80px;"></span></td>
                               <td><span><img src="'.$img2.'" style="height:80px;"></span></td>
                            </tr>
                        </table><br>
                        <table cellspacing="0" cellpadding="1" border="0">
                            
                            <tr>
                                <th align="center" style="border-top:1px solid black;font-size:22px;"><b>NEW CAR SALES RECEIPT</b></th>
                            </tr>
                            <tr>
                                <th align="center" style="border-top:1px solid black;border-bottom:1px solid black;font-size:22px;"><b>'.$receipt_title.'</b></th>
                            </tr>
                            
                        </table>
                        <table cellspacing="0" cellpadding="5" border="0">
                            <tr>
                                <td rowspan="2" style="width:70%;border-right:1px solid black;"><b>Received With Thanks From: </b>'.$data->customer_name.' <br><b>Mobile No. : </b>'.$data->contact_number.' <br> '.$data->address.'.</td>
                                <td ><br><b>Branch </b>: '.strtoupper($data->branch_name).'<br><b>Receipt No. : </b>'.$cash_receipt_id.$b_name.$month.$year.'<br><b>Receipt Type. : </b>'.$receipt_type.'<br><b>Receipt Date :</b>'.$data->cash_receipt_created_at.'</td>
                            </tr>
                        </table>
                        <table cellspacing="0" cellpadding="5" border="0">
                            <tr>
                                <td style="width:70%;border-right:1px solid black;border-top:1px solid black;border-bottom:1px solid black;"><b>Model: </b>'.$data->car_model_name.' | '.$data->car_varient_name.'<br><b>Color : </b>'.$data->exteriorcolor_name.' | '.$data->interiorcolor_name.'<br><b>KEC / Executive : </b>'.$data->sales_person_name.'<br><b>Cash Remark : </b>'.$data->cash_remark.'</td>
                                <td style="width:30%;border-top:1px solid black;border-bottom:1px solid black;">
                                    <b>Payment Detail</b><br>
                                    Payment Type : '.$payment_type.'<br>
                                    Payment Method : '.$payment_method.' <br>
                                    <b>Hyp/H : </b>'.$data->finance_name.' <br>
                                    Transaction No : '.$data->transaction_no.'
                                </td>
                            </tr>
                            <tr>
                                <td style="width:70%;border-right:1px solid black;border-top:1px solid black;border-bottom:1px solid black;"><b>Rupees in words :</b> '.$amount_word.'ONLY</td>
                                <td style="width:30%;border-right:1px solid black;border-top:1px solid black;border-bottom:1px solid black;"><b>Rs. </b>'.$data->cash_receipt_amount.'/- </td>
                            </tr>
                            <tr>
                                <td style="width:70%;"><b>GST No. :</b> 24ABACS4515J1ZH</td>
                                <td style="width:30%;text-align:right;"><b>Savan IB Automotive Pvt. Ltd.</b></td>
                            </tr>
                            <tr>
                                <td style="width:70%;">Price Prevailling at the time of delivery will be applicable<br>Rs. 500/- will be charged from customer as Cheque return charges.<br>Rs. 500/- will be charged from the customer against booking cancellation.<br>Consumer/Corporate offer are subject to change without prior notice and will be given/applicable as per the norms.
                                </td>
                                <td style="width:30%;text-align:right; font-size:10px;"><br><br><br><br><br><br>Authorized Signatory</td>
                                
                            </tr>
                            <tr>
                                <td style="width:70%;"><br><br><b>Customer Signature</b></td>
                                <td></td>
                            </tr>
                        </table>
                    </div>';

                    //<br><b>Booking No. :</b>B/NXA/22-23/00038
                    //<br>Created by : abc xyz

            PDF::writeHTML($tbl, true, false, false, false, '');

            PDF::SetFont('dejavusans', '', 10);
            //$content = "Office Copy";
            PDF::SetXY(260, 42);
            //PDF::Cell(0, 0, $content);
            PDF::Output('receipt.pdf', 'I');
    }


    public function prisetoword($number){
        // $number = 230558;
        $no = floor($number);
        $point = round($number - $no, 2) * 100;
        $hundred = null;
        $digits_1 = strlen($no);
        $i = 0;
        $str = array();
        $words = array('0' => '', '1' => 'ONE', '2' => 'TWO',
        '3' => 'THREE', '4' => 'FOUR', '5' => 'FIVE', '6' => 'SIX',
        '7' => 'SEVEN', '8' => 'EIGHT', '9' => 'NINE',
        '10' => 'TEN', '11' => 'ELEVEN', '12' => 'TWELVE',
        '13' => 'THIRTEEN', '14' => 'FOURTEEN',
        '15' => 'FIFTEEN', '16' => 'SIXTEEN', '17' => 'SEVENTEEN',
        '18' => 'EIGHTEEN', '19' =>'NINETEEN', '20' => 'TWENTY',
        '30' => 'THIRTY', '40' => 'FORTY', '50' => 'FIFTY',
        '60' => 'SIXTY', '70' => 'SEVENTY',
        '80' => 'EIGHTY', '90' => 'NINETY');
        $digits = array('', 'HUNDRED', 'THOUSAND', 'LAKH', 'CRORE');
        while ($i < $digits_1) {
            $divider = ($i == 2) ? 10 : 100;
            $number = floor($no % $divider);
            $no = floor($no / $divider);
            $i += ($divider == 10) ? 1 : 2;
            if ($number) {
                $plural = (($counter = count($str)) && $number > 9) ? 'S' : null;
                $hundred = ($counter == 1 && $str[0]) ? ' ' : null;
                $str [] = ($number < 21) ? $words[$number] .
                    " " . $digits[$counter] . $plural . " " . $hundred
                    :
                    $words[floor($number / 10) * 10]
                    . " " . $words[$number % 10] . " "
                    . $digits[$counter] . $plural . " " . $hundred;
            } else $str[] = null;
        }
        $str = array_reverse($str);
        $word_price = implode('', $str);
       /* $points = ($point) ?
        "." . $words[$point / 10] . " " . 
          $words[$point = $point % 10] : '';*/
        $word_price . "ONLY";

        return $word_price;
    }
    
}
