<?php

namespace App\Http\Controllers;

use App\Models\Liquidation;
use App\Models\LiquidationCashReceipt;
use App\Models\CashReceipt;
use App\Models\OBF;
use App\Models\Inventory;
use App\Models\Carmodel;
use App\Models\Product;
use App\Models\Lead;
use App\Models\Role; 
use App\Models\User;
use NumberFormatter; 
use App\Models\Setting;
use Illuminate\Http\Request;
use App\Http\Requests\LiquidationRequest;
use Auth, DB, Mail, Validator, File, DataTables;

class ObfLiquidationController extends Controller
{

    public function __construct(){
        $this->middleware('permission:refundliquidation_create', ['only' => ['create']]);
        $this->middleware('permission:refundliquidation_edit', ['only' => ['edit']]);
        $this->middleware('permission:refundliquidation_view', ['only' => ['view']]);
        $this->middleware('permission:refundliquidation_delete', ['only' => ['delete']]);
    }
    
    public function index(Request $request){
        $permission_get = '';
        $data_v = auth()->user()->roles->pluck( 'data_permission' );

        if(!empty($data_v)){
            $permission_get = $data_v[0];
        }
        
        if($request->ajax()){
            $data = OBF::select(
                'obf.id',
                'obf.customer_name',
                'branches.name as branch_name',
                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                'Team_master.team_name',
                'car_model.name AS product',
                'car_varient.name AS car_varient_name',
                'obf.on_road_price',
                'obf_finance.finance_discount',
                'obf.way_off',
                'obf.foc_accessories',
                'obf.offer_ib_amount',
                'obf.offer_kin_amount',
                'obf_finance.net_disbusment', 
                'obf.refund_amount',
                'liquidation.approval_status',
                'liquidation.id as liquidation_id',
                'liquidation_cash_receipt.id as liquidation_cash_receipt_id',
                DB::raw("CONCAT(refund_by.first_name,' ',refund_by.last_name) AS refund_by_name"),
                DB::raw('SUM(cash_receipt.amount) AS total_received_amount'),
                DB::raw('obf.on_road_price - COALESCE(SUM(cash_receipt.amount), 0) AS due_amount'),
                DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.receipt_type = "access_sort_receipt" AND cash_receipt.status != "rejected" AND cash_receipt.refund_status = "cancel") as access_sort_amount'),
                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')
            )
            ->join('liquidation','liquidation.obf_id','=','obf.id')
            ->leftjoin('branches','branches.id','=','obf.branch_id')
            ->leftjoin('users','users.id','=','obf.sales_person_id')
            ->leftjoin('users as refund_by','refund_by.id','=','obf.created_by')
            ->leftjoin('Team_master','Team_master.id','users.team_name')
            ->leftjoin('products' ,'obf.product_id' ,'products.id')
            ->leftjoin('car_model', 'car_model.id', 'products.car_model')
            ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
            ->leftjoin('cash_receipt','cash_receipt.obf_id','=','obf.id')
            ->leftJoin('obf_finance','obf_finance.obf_id','=','obf.id')
            ->leftjoin('exchange_purchase','exchange_purchase.obf_id','=','obf.id')
            ->leftjoin('liquidation_cash_receipt','liquidation_cash_receipt.liquidation_id','=','liquidation.id')
            ->where('obf.status', '=','refund_process');
            
            if($permission_get != '' && $permission_get == 'ONLY_MY_DATA'){
                $data = $data->whereRaw('FIND_IN_SET(obf.created_by ,"'.auth()->id().'")');
            }                    

            if(!empty(auth()->user()->branch)){
                $data =$data->whereRaw('FIND_IN_SET(obf.branch_id ,"'.auth()->user()->branch.'")');
            }

            if($permission_get != '' && $permission_get == 'MY_TEAM_DATA'){
                if(auth()->user()->team_name != NULL){
                    $team_name_ids = User::select('id')->where('team_name',auth()->user()->team_name)->get()->toArray();
                    $data = $data->whereIn('obf.created_by',$team_name_ids);
                }
            }
            $data->groupBy('obf.id');
            $data->orderBy('id', 'desc');


            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($data)  {
                    $return = '<div class="btn-group">';
                
                    if (auth()->user()->can('refundliquidation_view')) {
                        $return .= '<a href="' . route('obf.obf_summary', ['id' => base64_encode($data->id)]) . '" class="btn btn-default btn-xs">
                            <i class="fa fa-eye"></i>
                        </a> &nbsp;';
                    }
                    if (auth()->user()->can('Liquidation Process')) {
                        $user = auth()->user();
                        $assignFlag = $user->flag ?? null;
                        
                        $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                            <i class="fa fa-bars"></i>
                        </a> &nbsp;
                        <ul class="dropdown-menu">';
                            if ($assignFlag === "1" && !in_array($data->approval_status, ['liquidation_sm_accepted', 'liquidation_sm_rejected','liquidation_gm_accepted', 'liquidation_gm_rejected','liquidation_accountant_accepted','liquidation_accountant_rejected'])) {  
                                $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="liquidation_tl_accepted" data-id="' . base64_encode($data->id) . '">Refund Accept</a></li>';
                                $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="liquidation_tl_rejected" data-id="' . base64_encode($data->id) . '">Refund Reject</a></li>';
                            } else if($assignFlag === "2" && !in_array($data->approval_status, ['liquidation_gm_accepted', 'liquidation_gm_rejected','liquidation_accountant_accepted','liquidation_accountant_rejected'])){
                                // if($data->approval_status === 'liquidation_tl_accepted'){
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="liquidation_sm_accepted" data-id="' . base64_encode($data->id) . '">Refund Accept</a></li>';
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="liquidation_sm_rejected" data-id="' . base64_encode($data->id) . '">Refund Reject</a></li>';
                                // }
                            } else if($assignFlag === "3" && !in_array($data->approval_status, ['liquidation_accountant_accepted','liquidation_accountant_rejected'])){
                                // if($data->approval_status === 'liquidation_sm_accepted'){
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="liquidation_gm_accepted" data-id="' . base64_encode($data->id) . '">Refund Accept</a></li>';
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="liquidation_gm_rejected" data-id="' . base64_encode($data->id) . '">Refund Reject</a></li>';
                                // }
                            } else if($assignFlag === "5"){
                                // if($data->approval_status === 'liquidation_gm_accepted'){
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="liquidation_bh_accepted" data-id="' . base64_encode($data->id) . '">Refund Accept</a></li>';
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="liquidation_bh_rejected" data-id="' . base64_encode($data->id) . '">Refund Reject</a></li>';
                                // }
                            } else if($assignFlag === "4"){
                                // if($data->approval_status === 'liquidation_bh_accepted'){
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="liquidation_accountant_accepted" data-id="' . base64_encode($data->id) . '">Refund Accept</a></li>';
                                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="liquidation_accountant_rejected" data-id="' . base64_encode($data->id) . '">Refund Reject</a></li>';
                                // }        
                            } 
                            if($data->approval_status == 'liquidation_accountant_accepted'){
                                $return .= '<li><a class="dropdown-item" href="' . route('liquidation.process', ['id' => base64_encode($data->id)]) . '" target="_blank">Process Liquidation</a></li>';
                            }    
                            if($data->approval_status == 'liquidation_accountant_accepted'){
                            // if (isset($data->liquidation_cash_receipt_id) && !empty($data->liquidation_cash_receipt_id)) {
                                $return .= '<li><a class="dropdown-item refund-request" href="javascript:void(0);" data-id="' . base64_encode($data->id) . '" onclick="openRefundPopup(this)">Refund Request Form</a></li>';
                            }
                              
                            if($data->approval_status == 'liquidation_accountant_accepted'){    
                                $return .= '<li><a class="dropdown-item" href="javascript:void(0);" onclick="change_status_cheque(this);" data-liquidation_id="' . base64_encode($data->liquidation_id) . '"  data-bs-toggle="modal" data-bs-target="#chequeStatusModal">Cheque Status</a></li>';
                                
                            }
                            $return .= '<li><a class="dropdown-item" href="' . route('liquidation.viewlogs', ['id' => $data->id]) . '">View Logs</a></li>';
                        $return .= '</ul>';
                    }
                
                    $return .= '</div>';
                    return $return;
                })    
                ->editColumn('approval_status', function ($data) {
                    if ($data->approval_status == 'pending') {
                        return '<span class="badge badge-pill badge-warning">Pending From TL</span>';
                    }elseif ($data->approval_status == 'liquidation_tl_rejected') {
                        return '<span class="badge badge-pill badge-danger">Rejected By TL</span>';
                    }elseif ($data->approval_status == 'liquidation_sm_rejected') {
                        return '<span class="badge badge-pill badge-danger">Rejected By SM</span>';
                    }elseif ($data->approval_status == 'liquidation_gm_rejected') {
                        return '<span class="badge badge-pill badge-danger">Rejected By GM</span>';
                    }elseif ($data->approval_status == 'liquidation_bh_rejected') {
                        return '<span class="badge badge-pill badge-danger">Rejected By BH</span>';
                    }elseif ($data->approval_status == 'liquidation_accountant_rejected') {
                        return '<span class="badge badge-pill badge-danger">Rejected By Accountant</span>';
                    }elseif ($data->approval_status == 'liquidation_tl_accepted') {
                        return '<span class="badge badge-pill badge-success">Accepted By TL</span>';
                    }elseif ($data->approval_status == 'liquidation_sm_accepted') {
                        return '<span class="badge badge-pill badge-success">Accepted By SM</span>';
                    }elseif ($data->approval_status == 'liquidation_gm_accepted') {
                        return '<span class="badge badge-pill badge-success">Accepted By GM</span>';
                    }elseif ($data->approval_status == 'liquidation_bh_accepted') {
                        return '<span class="badge badge-pill badge-success">Accepted By BH</span>';
                    }elseif ($data->approval_status == 'liquidation_accountant_accepted') {
                        return '<span class="badge badge-pill badge-success">Accepted By Accountant</span>';
                    }elseif ($data->approval_status == 'delete') {
                        return '<span class="badge badge-pill badge-danger">Deleted</span>';
                    }elseif ($data->approval_status == 'cheque_ready') {
                        return '<span class="badge badge-pill" style="background-color: #17a2b8; color: white;">Cheque Ready</span>';
                    }else{
                        return '-';
                    }                            

                })
                ->rawColumns(['name', 'action' ,'approval_status'])
                ->filter(function ($query){
                        if (request()->get('customer_name',false)) {
                            $query->where('obf.customer_name', "like", "%".request()->get("customer_name")."%");
                        }
                        if (request()->get('branch_name',false)) {
                            $query->where('branches.name', "like", "%".request()->get("branch_name")."%");
                        }
                        if (request()->get('sales_person_name',false)) {
                            $salesPersonName = request()->get('sales_person_name');
                            $query->whereRaw("CONCAT(users.first_name, ' ', users.last_name) LIKE ?", ["%{$salesPersonName}%"]);
                        }
                        if (request()->get('team_name',false)) {
                            $query->where('Team_master.team_name', "like", "%".request()->get("team_name")."%");
                        }
                        if (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('on_road_price',false)) {
                            $query->where('obf.on_road_price', "like", "%".request()->get("on_road_price")."%");
                        }
                        if ($receivedAmount = request()->get('total_received_amount')) {
                            $query->havingRaw("total_received_amount LIKE ?", ["%{$receivedAmount}%"]);
                        }
                        if ($dueAmount = request()->get('due_amount')) {
                            $query->havingRaw("due_amount LIKE ?", ["%{$dueAmount}%"]);
                        }
                        if (request()->get('refund_amount',false)) {
                            $query->where('obf.refund_amount', "like", "%".request()->get("refund_amount")."%");
                        }
                        if (request()->get('approval_status',false)) {
                            $query->where('liquidation.approval_status', "like", "%".request()->get("approval_status")."%");
                        }
                        if ($refundByName = request()->get('refund_by_name')) {
                            $query->havingRaw("refund_by_name LIKE ?", ["%{$refundByName}%"]);
                        }
                    })
                ->make(true);
        }

        return view('liqudation.index');
    }
    
    public function change_status(LiquidationRequest $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!']);
            }
            
            $data = Liquidation::where(['obf_id' => $id])->first();

            if(!empty($data)){
                DB::enableQueryLog();
                
                $update = Liquidation::where(['obf_id' => $id])->update(['approval_status' => $request->status, 'approval_remark' => $request->reason, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
                    
                $crud = [
                    'module_nm' => 'liquidation_approval',
                    'module_id' => $id, 
                    'status' => $request->status,
                    'remark' => $request->reason,
                    'created_at' => date('Y-m-d H:i:s'),
                    'created_by' => auth()->user()->id,
                ];
                \DB::table('logs')->insert($crud);
                    
                if($update){
                    return response()->json(['code' => 200 ,'message' => 'Record status change successfully']);
                }else{
                    return response()->json(['code' => 201, 'message' => 'Faild to update status']);
                }
            }else{
                return response()->json(['code' => 201, 'message' => 'Somthing went wrong !']);
            }
        }
    }
    
    public function process(Request $request){
        if(isset($request->id) && $request->id != null){
            $id = base64_decode($request->id);
        }else{
            return view('liqudation.index')->with('error', 'No data found');
        }
        $data = Liquidation::where('obf_id',$id)->first();
        
        $obf_data = OBF::select('refund_amount')->where('id',$data->obf_id)->first();
        
        $cash_receipt_data = CashReceipt::where('obf_id',$data->obf_id)->where('status','accepted')->where('receipt_type', '!=', 'access_sort_receipt')->get();
        
        $liquidation_cash_receipt_data = LiquidationCashReceipt::where('liquidation_id', $data->id)->first(); 
        
        $bank_account = DB::table('bank_account')->select('id','name')->where('status', 'active')->groupBy('bank_account.id')->get(); 
        
        if($data){
            return view('liqudation.process',compact('data','cash_receipt_data','liquidation_cash_receipt_data','bank_account','obf_data'));
        } else {
            return redirect()->back()->with('error', 'No data found')->withInput();   
        }
    }
    
    public function process_insert(Request $request){
        $request->validate([
            'paying_amount' => 'nullable|numeric|min:0',
        ]);

        if (($request->paying_amount == 0 || $request->paying_amount == null)) {
            return redirect()->back()->with('error', 'Customer Refund Amount must be greater than 0.')->withInput();
        }
        $liquidation_id =  Liquidation::where('id',$request->id)->first();
        $obf_data = OBF::where('id',$liquidation_id->obf_id)->first();

        if (!empty($obf_data)) {

            $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;
            }

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

            if($request->liquidation_cash_receipt_data_id != ''){
                //update
                $data = LiquidationCashReceipt::select('liquidation_cash_receipt.*', 'bank_account.name','finance_liquidation_bank.name as finance_liquidation_bank_name')
                ->leftJoin('bank_account', 'liquidation_cash_receipt.bank_account_id', '=', 'bank_account.id')
                ->leftJoin('bank_account as finance_liquidation_bank', 'liquidation_cash_receipt.bank_account_id', '=', 'finance_liquidation_bank.id')
                ->where('liquidation_cash_receipt.id', $request->liquidation_cash_receipt_data_id)
                ->first();

                $data->liquidation_id = $request->id;
                $data->total_received_amount = $request->total_received_amount;
                $data->liquidation_amount = $request->liquidation_amount;
                $data->paying_amount = $request->paying_amount;
                $data->payment_type = $request->payment_type;
                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->remark = $request->remark;
                $data->finance_liquidation_amount = $request->finance_liquidation_amount;
                $data->finance_paying_amount = $request->finance_paying_amount;
                $data->finance_payment_type = $request->finance_payment_type;
                if($request->finance_payment_type == 'cheque')
                {
                    $data->finance_transaction_no = $request->finance_chq_number;
                    $data->finance_bank_account_id = $request->finance_bank_account_id;
                    $data->refund_to_bank = $request->refund_to_bank;
                }
                if($request->finance_payment_type == 'vallet_payment')
                {
                    $data->finance_transaction_no = $request->finance_vallet_number;
                    $data->finance_bank_account_id = $request->finance_bank_account_id;
                    $data->refund_to_bank = $request->refund_to_bank;
                }
                if($request->finance_payment_type == 'online_transfer')
                {
                    $data->finance_transaction_no = $request->finance_trans_number;
                    $data->finance_bank_account_id = $request->finance_bank_account_id;
                    $data->refund_to_bank = $request->refund_to_bank;
                }
                $data->finance_remark = $request->finance_remark;
                $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' => 'liquidation_cash_receipt',
                    'module_id' => $request->liquidation_cash_receipt_data_id,
                    'status' => 'liquidation_cash_receipt_update',
                    'remark' => $request->remark,
                    'created_at' => date('Y-m-d H:i:s'),
                    'created_by' => auth()->user()->id,
                ];
                \DB::table('logs')->insert($crud);
            }else{
                //insert
                $data = new LiquidationCashReceipt();
                $data->liquidation_id = $request->id;
                $data->total_received_amount = $request->total_received_amount;
                $data->liquidation_amount = $request->liquidation_amount;
                $data->paying_amount = $request->paying_amount;
                $data->payment_type = $request->payment_type;
                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->remark = $request->remark;
                $data->finance_liquidation_amount = $request->finance_liquidation_amount;
                $data->finance_paying_amount = $request->finance_paying_amount;
                $data->finance_payment_type = $request->finance_payment_type;
                if($request->finance_payment_type == 'cheque')
                {
                    $data->finance_transaction_no = $request->finance_chq_number;
                    $data->finance_bank_account_id = $request->finance_bank_account_id;
                    $data->refund_to_bank = $request->refund_to_bank;
                }
                if($request->finance_payment_type == 'vallet_payment')
                {
                    $data->finance_transaction_no = $request->finance_vallet_number;
                    $data->finance_bank_account_id = $request->finance_bank_account_id;
                    $data->refund_to_bank = $request->refund_to_bank;
                }
                if($request->finance_payment_type == 'online_transfer')
                {
                    $data->finance_transaction_no = $request->finance_trans_number;
                    $data->finance_bank_account_id = $request->finance_bank_account_id;
                    $data->refund_to_bank = $request->refund_to_bank;
                }
                $data->finance_remark = $request->finance_remark;
                $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();

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

            $liquidation_cash_receipt_data_id = $data->id;
            if ($liquidation_cash_receipt_data_id) {
                $msg = '';
                if($request->liquidation_cash_receipt_data_id != ''){
                     $msg = 'Record Updated successfully';
                }else{
                     $msg = 'Record inserted successfully';
                }

                return redirect()->route('liquidation')->with('success', $msg);
            } else {                   
                 return redirect()->back()->with('error', 'Failed to update record2')->withInput();
            }


        }else {
             return view('liqudation.index')->with('error', 'No Record Found!');
        }
    }
    
    public function refund_form(Request $request){
           if ($request->isMethod('get')) {
            if (!$request->has('id')) {
                return redirect()->back()->with('error', 'No ID provided')->withInput();
            }
            $id = base64_decode($request->id);
        } 
        // For POST form submission, read encoded_id input
        elseif ($request->isMethod('post')) {
            if (!$request->has('encoded_id')) {
                return response()->json(['success' => false, 'message' => 'No ID provided']);
            }
            $id = base64_decode($request->encoded_id);
        } else {
            return redirect()->back()->with('error', 'Invalid request')->withInput();
        }
    
        $images = DB::table('global_configuration')
            ->select('gatepass_logo1')
            ->where('status', 'active')
            ->first();

        $obf_data = OBF::select(
                'obf.*',
                'branches.name as branch_name',
                'car_model.name AS product',
                'car_varient.name AS car_varient_name',
                'exteriorcolor.name as exterior_color',
                'liquidation.liquidation_amount as refund_amount',
                DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                'Team_master.team_name',
                
                DB::raw("MAX(CASE WHEN logs.status = 'refund_process' THEN CONCAT(log_users.first_name,' ',log_users.last_name) END) as requested_by"),
                DB::raw("MAX(CASE WHEN logs.status = 'refund_process' THEN DATE_FORMAT(logs.created_at, '%d-%m-%Y %h:%i %p') END) as requested_at"),
        
                DB::raw("MAX(CASE WHEN logs.status = 'liquidation_tl_accepted' THEN CONCAT(log_users.first_name,' ',log_users.last_name) END) as tl_accepted_by"),
                DB::raw("MAX(CASE WHEN logs.status = 'liquidation_tl_accepted' THEN DATE_FORMAT(logs.created_at, '%d-%m-%Y %h:%i %p') END) as tl_accepted_at"),
                
                DB::raw("MAX(CASE WHEN logs.status = 'liquidation_sm_accepted' THEN CONCAT(log_users.first_name,' ',log_users.last_name) END) as sm_accepted_by"),
                DB::raw("MAX(CASE WHEN logs.status = 'liquidation_sm_accepted' THEN DATE_FORMAT(logs.created_at, '%d-%m-%Y %h:%i %p') END) as sm_accepted_at"),
        
                DB::raw("MAX(CASE WHEN logs.status = 'liquidation_gm_accepted' THEN CONCAT(log_users.first_name,' ',log_users.last_name) END) as gm_accepted_by"),
                DB::raw("MAX(CASE WHEN logs.status = 'liquidation_gm_accepted' THEN DATE_FORMAT(logs.created_at, '%d-%m-%Y %h:%i %p') END) as gm_accepted_at"),
        
                DB::raw("MAX(CASE WHEN logs.status = 'liquidation_bh_accepted' THEN CONCAT(log_users.first_name,' ',log_users.last_name) END) as bh_accepted_by"),
                DB::raw("MAX(CASE WHEN logs.status = 'liquidation_bh_accepted' THEN DATE_FORMAT(logs.created_at, '%d-%m-%Y %h:%i %p') END) as bh_accepted_at"),
            )
            /*->leftJoin('branches', 'branches.id', '=', 'obf.branch_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('exteriorcolor', 'exteriorcolor.id', '=', 'products.exterior_color')
            ->join('liquidation', 'liquidation.obf_id', '=', 'obf.id')
            ->leftJoin('liquidation_cash_receipt', 'liquidation_cash_receipt.liquidation_id', '=', 'liquidation.id')
            ->leftJoin('users', 'users.id', '=', 'obf.sales_person_id')
            ->leftJoin('users as log_users', 'users.id', '=', 'liquidation.created_by')
            ->leftjoin('Team_master','Team_master.id','users.team_name')
            ->leftJoin('logs', 'logs.module_id', '=', 'obf.id')
            ->where('obf.id', $id)
            ->first();*/
            
            ->leftJoin('branches', 'branches.id', '=', 'obf.branch_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('exteriorcolor', 'exteriorcolor.id', '=', 'products.exterior_color')
            ->join('liquidation', 'liquidation.obf_id', '=', 'obf.id')
            ->leftJoin('liquidation_cash_receipt', 'liquidation_cash_receipt.liquidation_id', '=', 'liquidation.id')
            ->leftJoin('users', 'users.id', '=', 'obf.sales_person_id')
            ->leftJoin('logs', 'logs.module_id', '=', 'obf.id')
            ->leftJoin('users as log_users', 'log_users.id', '=', 'logs.created_by')
            ->leftJoin('Team_master','Team_master.id','=','users.team_name')
            ->where('obf.id', $id)
            ->groupBy('obf.id')
            ->first();
    
        if ($obf_data) {
            if ($request->isMethod('get')) {
                return view('liqudation.refund_form', compact('obf_data', 'images'));
            } else {
                return response()->json([
                    'success' => true,
                    'message' => 'Refund request submitted successfully.'
                ]);
            }
        } else {
            if ($request->isMethod('get')) {
                return redirect()->back()->with('error', 'No data found')->withInput();
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'No data found.'
                ]);
            }
        }

    }
    
    public function printReceipt(Request $request)
    {
        if (!isset($request->id) || $request->id == null) {
            return redirect()->back()->with('error', 'Invalid Request');
        }
    
        $id = base64_decode($request->id);

        $data = OBF::select(
            'obf.id',
            'obf.customer_name',
            'branches.name as branch_name',
            DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
            'Team_master.team_name',
            'car_model.name AS product',
            'car_varient.name AS car_varient_name',
            'obf.on_road_price',
            'obf_finance.finance_discount',
            'obf.way_off',
            'obf.foc_accessories',
            'obf.offer_ib_amount',
            'obf.offer_kin_amount',
            'obf_finance.net_disbusment', 
            'obf.refund_amount',
            'liquidation.approval_status',
            'liquidation_cash_receipt.id as liquidation_cash_receipt_id',
            DB::raw("CONCAT(refund_by.first_name,' ',refund_by.last_name) AS refund_by_name"),
            DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.status != "rejected" AND cash_receipt.refund_status = "cancel") as total_received_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" AND cash_receipt.refund_status = "cancel") 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" AND cash_receipt.refund_status = "cancel") as dp_amount'),
            DB::raw('(SELECT SUM(amount) FROM cash_receipt WHERE cash_receipt.obf_id = obf.id AND cash_receipt.receipt_type = "access_sort_receipt" AND cash_receipt.status != "rejected" AND cash_receipt.refund_status = "cancel") as access_sort_amount'),
            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')
        )
        ->join('liquidation','liquidation.obf_id','=','obf.id')
        ->leftJoin('branches','branches.id','=','obf.branch_id')
        ->leftJoin('users','users.id','=','obf.sales_person_id')
        ->leftJoin('users as refund_by','refund_by.id','=','obf.created_by')
        ->leftJoin('Team_master','Team_master.id','=','users.team_name')
        ->leftJoin('products','obf.product_id','=','products.id')
        ->leftJoin('car_model', 'car_model.id', '=', 'products.car_model')
        ->leftJoin('car_varient', 'car_varient.id', '=', 'products.veriant')
        ->leftJoin('obf_finance','obf_finance.obf_id','=','obf.id')
        ->leftJoin('exchange_purchase','exchange_purchase.obf_id','=','obf.id')
        ->leftJoin('liquidation_cash_receipt','liquidation_cash_receipt.liquidation_id','=','liquidation.id')
        ->where('obf.id', $id)
        ->first();
    
        if (!$data) {
            return redirect()->back()->with('error', 'OBF record not found');
        }
    
        $liquidation = Liquidation::where('obf_id', $id)->first();
        if (!$liquidation) {
            return redirect()->back()->with('error', 'Liquidation record not found');
        }
    
        $cashReceipt = CashReceipt::where('obf_id', $id)
            ->where('status', 'accepted')
            ->where('receipt_type', '!=', 'access_sort_receipt')
            ->first();
    
        if (!$cashReceipt) {
            return redirect()->back()->with('error', 'Cash receipt not found.');
        }
    
        $liquidation_cash_receipt_data = LiquidationCashReceipt::where('liquidation_id', $liquidation->id)->first();
    
        $bank_account = DB::table('bank_account')
            ->select('id', 'name')
            ->where('status', 'active')
            ->groupBy('bank_account.id')
            ->get();
            
        $receipt_no = $cashReceipt->receipt_no ?? 'N/A';
        $receipt_type = $cashReceipt->receipt_type ?? 'N/A';
        $payment_method = $cashReceipt->payment_type ?? 'N/A';
    
        $formatter = new NumberFormatter('en', NumberFormatter::SPELLOUT);
        $amount_word = ucwords($formatter->format($cashReceipt->cash_receipt_amount));
    
        // dd($data);
        return view('liqudation.cash_receipt', compact(
            'liquidation',
            'data',
            'cashReceipt',
            'liquidation_cash_receipt_data',
            'bank_account',
            'receipt_no',
            'receipt_type',
            'payment_method',
            'amount_word'
        ));
    }
    
    public function updateChequeStatus(Request $request)
    {
        $id = base64_decode($request->liquidation_id);
        $status = $request->approval_status;
        $remark = $request->cheque_remark;
        
         $updated = Liquidation::where('id', $id)->update([
            'approval_status' => $request->approval_status,
            'cheque_remark'   => $request->cheque_remark,
            'approval_remark' => $request->reason,
            'updated_by'      => auth()->user()->id,
            'updated_at'      => now(),
        ]);
        
        $crud = [
            'module_nm'   => 'liquidation',
            'module_id'   => $id,
            'status'      => $status,
            'remark'      => $remark,
            'created_at'  => now(),
            'created_by'  => auth()->id(),
        ];
    
        \DB::table('logs')->insert($crud);
    
        if (!$updated) {
            return response()->json(['success' => false, 'message' => 'Record not found.'], 404);
        }
    
        return response()->json(['success' => true, 'message' => 'Cheque status updated.']);
    }

    public function viewlogs(Request $request)
        {
            $id = $request->id;

            $product = Inventory::select(
                    'inventory.id as i_id',
                    'inventory.name as i_name',
                    'inventory.vin_number as vin_number',
                    'inventory.manufacturing_year as manufacturing_year',
                    '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('products', 'products.id', '=', 'inventory.name')
                ->leftJoin('car_model', 'car_model.id', '=', 'products.car_model')
                ->leftJoin('car_varient', 'car_varient.id', '=', 'products.veriant')
                ->leftJoin('exteriorcolor', 'exteriorcolor.id', '=', 'products.exterior_color')
                ->leftJoin('interiorcolor', 'interiorcolor.id', '=', 'products.interior_color')
                ->where('inventory.id', '=', $id)
                ->first();
        
            if (!$product) {
                abort(404, 'liquidation not found');
            }
        
            $crud = [
                'module_nm'   => 'liquidation',
                'module_id'   => $id,
                'status'      => $request->status,
                'created_at'  => now(),
                'created_by'  => auth()->id(),
            ];
        
            \DB::table('logs')->insert($crud);
        
            $logs_data = \DB::table('logs')
                ->leftJoin('users', 'users.id', '=', 'logs.created_by')
                ->select('logs.*', \DB::raw("CONCAT(users.first_name, ' ', users.last_name) as user_name"))
                ->where('logs.module_nm', 'liquidation')
                ->where('logs.module_id', $id)
                ->orderBy('logs.created_at', 'desc')
                ->get();
        
            return view('logs.viewliquidationlog', compact('product', 'logs_data'));
        }


}

