<?php

namespace App\Http\Controllers;

use App\Models\OBF;
use App\Models\ObfApproval;
use App\Models\Carmodel;
use App\Models\Product;
use App\Models\Lead;
use Illuminate\Http\Request;
use App\Http\Requests\ObfApprovalRequest;
use Auth, DB, Mail, Validator, File, DataTables;

class ObfApprovalController extends Controller{
    /** construct */
        public function __construct(){
            $this->middleware('permission:obf_approval-create', ['only' => ['create']]);
            $this->middleware('permission:obf_approval-edit', ['only' => ['edit']]);
            $this->middleware('permission:obf_approval-view', ['only' => ['view']]);
            $this->middleware('permission:obf_approval-delete', ['only' => ['delete']]);
        }
    /** construct */

    /** index */
        public function index(Request $request){
            if($request->ajax()){
                $departments=DB::table('department')->where('id',auth()->user()->department_id)->first();
                
                if(!empty($departments)){
                    $department=$departments->branch_admin ? 1 : 0;
                }else{
                    $department=0;
                }
               
                /*$data = OBF::select('obf.id' ,'obf.customer_name' ,'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',DB::raw('ROUND(obf.on_road_price - sum(cash_receipt.amount)) as due_amount'),DB::raw('ROUND(sum(cash_receipt.amount)) as received_amount'))
                 ->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')
                 ->where('obf.status' ,'pending')
                 //->orwhereNotNull(['cash_receipt.id'])
                // ->orwhereNotNull(['cash_receipt.amount'])
                 //->orwhereNotNull(['obf.id'])
                 ->groupBy(['obf.id']);*/
                 $data = OBF::select('obf.id' ,'obf.customer_name' ,'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',DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),'obf.gst','exteriorcolor.name as exterior_color','obf.address','obf.registration','obf_finance.loan_amount as obf_finance_loan_amount','obf_finance.finance_discount as finance_discount','Team_master.team_name',DB::raw('exchange_purchase.total_exchange_amount as total_exchange_amount'),DB::raw('SUM(IF(cash_receipt.receipt_type = "booking_receipt",cash_receipt.amount,0)) as booking_amount'),DB::raw('SUM(IF(cash_receipt.receipt_type = "downpayment_receipt",cash_receipt.amount,0)) as dp_amount'),DB::raw('ROUND(obf.on_road_price - sum(cash_receipt.amount)) as due_amount'),'inventory.vin_number',DB::raw('ROUND(sum(cash_receipt.amount)) as received_amount'))
                 ->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('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','=','products.id')
                 ->where('obf.status' ,'pending')
                // ->orwhereNull(['cash_receipt.id'])
                // ->orwhereNull(['cash_receipt.amount'])
                // ->orwhereNull(['obf.id'])
                 ->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');
                $data =$data->get();
                
            
                
                return Datatables::of($data)
                        ->addIndexColumn()
                        ->editColumn('final_total',function($data){
                            $book_amt =$data->booking_amount + $data->dp_amount + $data->loan_amount + $data->total_exchange_amount;
                            return $book_amt;
                        })
                        ->editColumn('net_total',function($data){
                            $book_amt = $data->booking_amount + $data->dp_amount + $data->loan_amount + $data->total_exchange_amount;
                            $net_amt = $book_amt - $data->finance_discount;
                            return $net_amt;
                        })
                        ->editColumn('due_amount',function($data){
                            $book_amt = $data->booking_amount + $data->dp_amount + $data->loan_amount + $data->total_exchange_amount;
                            $net_amt = $book_amt - $data->finance_discount;
                            $due_amount = $data->on_road_price - $net_amt;
                            return $due_amount;
                        })
                        ->addColumn('action', function($data)use($department){
                            $return = '<div class="btn-group">';

                            if(auth()->user()->can('obf_approval-view') || $department == 1){
                                $return .= '<a href="'.route('obf_approval.view', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-eye"></i>
                                            </a> &nbsp;';
                            }   

                            if (auth()->user()->can('obf_approval-delete') || $department == 1) {
                                $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="obf_accepted" data-id="' . base64_encode($data->id) . '">Obf Accepted</a></li>
                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status_reject(this);" data-status="obf_rejected" data-id="' . base64_encode($data->id) . '">Obf Rejected</a></li>
                                                </ul>';
                            }

                            $return .= '</div>';

                            return $return;
                        })

                        ->editColumn('name', function($data) {
                            return $data->customer_name;
                        })
                        ->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">Account Rejected</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>';
                            }
                        })

                        ->rawColumns(['name', 'action' ,'status'])
                        ->make(true);
            }

            return view('obf_approval.index');
        }
    /** index */

    /** view */
        public function view(Request $request){
            if(isset($request->id) && $request->id != null){
                $id = base64_decode($request->id);
            }else{
                return view('obf_approval')->with('error', 'No data found');
            }
            DB::enableQueryLog();
            $path = URL('/uploads/kyc').'/';

            $data = OBF::select('obf.id' ,'obf.temporary_id' ,'obf.booking_date' ,'obf.customer_name' ,'obf.customer_type' ,'branches.name AS branch_name' ,'obf.company_name' ,'obf.gst' ,'obf.address', 'obf.registration' ,'obf.email' ,'obf.pan_number' ,'obf.product_id' ,'obf.other_documents','obf.pan_image','obf.adhar_image','obf.licance_image',
           /* DB::Raw("CASE
                    WHEN ".'obf.pan_image'." != '' THEN CONCAT("."'".$path."'".", ".'obf.pan_image'.")
                    ELSE CONCAT("."'".$path."'".", 'user-icon.jpg')
                END as pan_image"),
            'obf.adhar_number',
            DB::Raw("CASE
                    WHEN ".'obf.adhar_image'." != '' THEN CONCAT("."'".$path."'".", ".'obf.adhar_image'.")
                    ELSE CONCAT("."'".$path."'".", 'user-icon.jpg')
                END as adhar_image"),
            'obf.licance_number',
            DB::Raw("CASE
                    WHEN ".'obf.licance_image'." != '' THEN CONCAT("."'".$path."'".", ".'obf.licance_image'.")
                    ELSE CONCAT("."'".$path."'".", 'user-icon.jpg')
                END as licance_image"),*/
            'obf.contact_number','obf.dob','obf.nominee_name' ,'obf.nominee_reletion' ,'obf.nominee_age' ,'obf.occupation',DB::raw("CONCAT(sales.first_name,' ',sales.last_name) AS sales_person_name") ,'products.name AS product_name' ,'products.veriant','obf.ex_showroom_price' ,'registration_tax.percentage AS registration_tax' ,'insurance.name AS insurance_name' ,'insurance.amount AS insurance_amount' ,'insurance.years AS insurance_years','municipal_tax.percentage AS municipal_tax' ,'tcs_tax.percentage AS tcs_tax','accessories.name AS accessory_name' ,'accessories.price AS accessory_price','extand_warranties.years AS warranty_years' ,'extand_warranties.amount AS warranty_amount' ,'fasttags.brand_name AS fasttag_brand_name' ,'fasttags.amount AS fasttag_amount' ,'obf.trad_in_value' ,'obf.on_road_price','obf.on_road_price_word' ,'finance.name AS finance_name', 'finance_branch.name AS finance_branch' ,'lead.name AS lead_name' ,'obf.booking_amount' ,'obf.mode_of_payment' ,'obf.reason','obf.sub_lead_id','obf.lead_id'
            )
            ->leftjoin('branches' ,'obf.branch_id' ,'branches.id')
            ->leftjoin('users AS sales' ,'obf.sales_person_id' ,'sales.id')
            ->leftjoin('products' ,'obf.product_id' ,'products.id')
            ->leftjoin('taxes AS registration_tax' ,'obf.registration_tax_id' ,'registration_tax.id')
            ->leftjoin('insurance' ,'obf.insurance_id' ,'insurance.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('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' ,'finance.branch_id' ,'finance_branch.id')
            ->leftjoin('lead' ,'obf.lead_id' ,'lead.id')
            ->where(['obf.id' => $id])->first();
            // dd(DB::getQueryLog());

             $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('obf_approval.view')->with(['data' => $data,'carmodel' => $carmodel,'Cardata' => $Cardata,'lead' => $lead]);
            else
                return redirect()->back()->with('error', 'No data found')->withInput();
        
        }
    /** view */

    /** change-status */
        public function change_status(ObfApprovalRequest $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 = OBF::where(['id' => $id])->first();

                if(!empty($data)){
                    DB::enableQueryLog();
                    if($data->status == 'obf_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]);
                    }else if($data->status == 'obf_accepted'){
                        $update = OBF::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
                    }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($request->status == 'obf_accepted'){
                        //notification insert
                        $notification_template_master_data = DB::table('notification_template_master')->select('*')->where(['template_name' => 'obf_approve','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
                    }

                    // die('sss');

                    // dd(DB::getQueryLog());
                    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 !']);
                }
            }
        }
    /** change-status */
}
