<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Exchange;
use App\Models\carcompany;
use App\Models\OBF;
use App\Models\ExchangeCashReceipt;
use App\Exports\ExportDepartment;
use Maatwebsite\Excel\Facades\Excel;
use Auth, DB, Mail, Validator, File, DataTables, Exception;
use App\Imports\ImportDepartment;

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

//  index 
    public function index(Request $request){
        if($request->ajax()){
            
            $data = Exchange::with('obf')->orderBy('id', 'desc')->get();
            
            return Datatables::of($data)
            ->addIndexColumn()

            ->addColumn('customer_name', function($data) {
                return $data->obf->customer_name ?? ''; 
            })
            ->addColumn('seller_detail', function($data) {
                return $data->seller_detail ?? '';
            })
            ->addColumn('car_name', function($data) {
                return $data->obf->trade_car_name ?? '';
            })
            ->addColumn('registeration_number', function($data) {
                return $data->registration_number ?? '';
            })
            ->addColumn('chassis_number', function($data) {
                return $data->chassis_number ?? '';
            })
            ->addColumn('engine_number', function($data) {
                return $data->engine_number ?? '';
            })
            ->addColumn('amount', function($data) {
                return $data->amount ?? '';
            })
            ->addColumn('remarks', function($data) {
                return $data->remarks ?? '';
            })

            ->editColumn('status', function ($data) {
                if ($data->status == 'active') {
                    return '<span class="badge badge-pill badge-success">Active</span>';
                } else if ($data->status == 'inactive') {
                    return '<span class="badge badge-pill badge-warning">Inactive</span>';
                } else if ($data->status == 'deleted') {
                    return '<span class="badge badge-pill badge-danger">Deleted</span>';
                } else if ($data->status == 'sell') {
                    return '<span class="badge badge-pill badge-success">Sell</span>';
                } else {
                    return '-';
                }
            })

            ->addColumn('action', function($data){
                $return = '<div class="btn-group">';

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

                if(auth()->user()->can('exchange-edit')){
                    $return .= '<a href="'.route('exchange.edit',['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                    <i class="fa fa-pencil"></i>
                                </a> &nbsp;';
                }   
                
                if (auth()->user()->can('cash_receipt-generate_gate_pass') && $data->status == 'sell') {
                    $return .= '<a title="Add Cash" href="' . route('exchange_cash_receipt.create', ['id' => base64_encode($data->id)]) . '" class="btn btn-default btn-xs">
                            <i class="fas fa-file-medical"></i>
                            </a> &nbsp;';
                }

                $return .= '<div class="btn-group">
                <a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                    <i class="fa fa-bars"></i>
                </a>
                <ul class="dropdown-menu">';

                if (auth()->user()->can('exchange-delete')) {
                    if($data->status != 'sell'){
                        $return .= '
                        <li><a class="dropdown-item change-status" href="javascript:;" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                        <li><a class="dropdown-item change-status" href="javascript:;" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                        <li><a class="dropdown-item sell-status" href="javascript:;" data-status="sell" data-id="' . base64_encode($data->id) . '">Sell</a></li>';  
                    }
                        
                    $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="cancel_reason_reject(this);" data-id="' . $data->id . '">Cancel</a></li>
                        <li class="dropdown-divider"></li>';
                }
                
                if (auth()->user()->can('Selling Note') && $data->status == 'sell') {
                    $return .= '<li><a class="dropdown-item" href="' . route('obf.sellingnote', ['id' => base64_encode($data->id)]) . '" target="_blank">Selling Note</a></li>';
                }
                
                if (auth()->user()->can('Selling Receipt') && $data->status == 'sell') {
                    $return .= '<li><a class="dropdown-item" href="' . route('obf.sellingreceipt', ['id' => base64_encode($data->id)]) . '" target="_blank">Selling Receipt</a></li>';
                }
                
                $return .= '</ul>
                        </div>
                    </div>';
                
                return $return;
                            })

            ->rawColumns(['status', 'action'])
            ->make(true);
        }
        
        $branch = Branch::query();
        if (!empty(auth()->user()->branch)) {
            $branch_arr = explode(',', auth()->user()->branch);
            $branch = $branch->whereIn('id', $branch_arr);
        }
        $branch = $branch->where('status', 'active')->get();
        return view('exchange.index', compact('branch'));
    }
//  index 

// create /
    public function create(Request $request){
        $obf = OBF::select('id','customer_name')->where('trade_car_value','=','yes')->get(); 
        $data = exchange::get();
        $carcompany = carcompany::get();
        return view('exchange.create')->with(['data' => $data,'carcompany' => $carcompany,'obf' => $obf]);
    }
//  create /
//  insert 
    public function insert(Request $request){
        if($request->ajax()){
            return true ;
        }
        $crud = [
                'obf_id' => $request->obf_id ?? null,
                'seller_detail' => $request->seller_detail ?? null,
                'company_name' => $request->company_name ?? null,
                'variant' => $request->variant ?? null,
                'manufacturing_year' => $request->manufacturing_year ?? null,
                'registration_number' => $request->registration_number ?? null,
                'chassis_number' => $request->chassis_number ?? null,
                'engine_number' => $request->engine_number ?? null,
                'remarks' => $request->remarks ?? null,
                'colour' => $request->colour ?? null,
                'time' => $request->time ?? null,
                'date' => $request->date ?? null,
                'date_of_registration' => $request->date_of_registration ?? null,
                'purchase_date' => $request->purchase_date ?? null,
                'amount' => $request->amount ?? null,
                'exchange_bonus' => $request->exchange_bonus ?? null,
                'total_exchange_amount' => ($request->amount)+($request->exchange_bonus) ?? null,
                'amount_in_words' => $request->amount_in_words ?? null,
                'HPA' => $request->HPA ?? null,
                'car_status' => $request->car_status ?? null,
                'relation_with_obf' => $request->relation_with_obf ?? null,
                'status' => 'active',
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => auth()->user()->id
        ];
        // pan_image  
        if(!empty($request->file('pan_image'))){
            //dd($request->file('pan_image'));
            $pan_image = '';
            $pan_image_name_arr = [];

            $pan_image_arr = $request->file('pan_image');
           // dd($pan_image_arr);
            foreach($pan_image_arr as $key => $file_value){
                // dd($file_value);
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "pan_image_".time()."_".$filename_three.'.'.$extension_three;
                
                array_push($pan_image_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/exchange';
                
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
    //    dd($pan_image_name_arr);
            if(!empty($pan_image_name_arr)){
                $pan_image = implode(",",$pan_image_name_arr);
            }
        //dd($pan_image);
            $crud['pan_image'] = $pan_image;
        }
        // dd($pan_image);


         // adhar_image        
         if(!empty($request->file('adhar_image'))){
            $adhar_image = '';
            $adhar_image_name_arr = [];

            $adhar_image_arr = $request->file('adhar_image');
            foreach($adhar_image_arr as $key => $file_value){
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "adhar_image_".time()."_".$filename_three.'.'.$extension_three;

                array_push($adhar_image_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/exchange/';
                
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
            if(!empty($adhar_image_name_arr)){
                $adhar_image = implode(",",$adhar_image_name_arr);
            }
            $crud['adhar_image'] = $adhar_image;
        }
         // rcbook        
         if(!empty($request->file('rcbook'))){
            $rcbook = '';
            $rcbook_name_arr = [];

            $rcbook_arr = $request->file('rcbook');
            foreach($rcbook_arr as $key => $file_value){
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "rcbook_".time()."_".$filename_three.'.'.$extension_three;

                array_push($rcbook_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/exchange/';
                
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
            if(!empty($rcbook_name_arr)){
                $rcbook = implode(",",$rcbook_name_arr);
            }
            $crud['rcbook'] = $rcbook;
        }
        // insurance               
        if(!empty($request->file('insurance'))){
            $insurance = '';
            $insurance_name_arr = [];

            $insurance_arr = $request->file('insurance');
            foreach($insurance_arr as $key => $file_value){
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "insurance_".time()."_".$filename_three.'.'.$extension_three;

                array_push($insurance_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/exchange/';
                
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
            if(!empty($insurance_name_arr)){
                $insurance = implode(",",$insurance_name_arr);
            }
            $crud['insurance'] = $insurance;
        }
            // dd($insurance);
        
        // dd($crud);
        // totto        
        if(!empty($request->file('totto'))){
            $totto = '';
            $totto_name_arr = [];

            $totto_arr = $request->file('totto');
            foreach($totto_arr as $key => $file_value){
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "totto_".time()."_".$filename_three.'.'.$extension_three;

                array_push($totto_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/exchange/';
                
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
            if(!empty($totto_name_arr)){
                $totto = implode(",",$totto_name_arr);
            }
            $crud['totto'] = $totto;
        }

        DB::beginTransaction();
        try {
            DB::enableQueryLog();
            $last_id ='';
            $last_id = exchange::insertGetId($crud);
            
            $log_crud = [
                'module_nm' => 'exchange',
                'module_id' => $last_id,
                'status' => 'car_exchange',
                'remark' => $request->remarks,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
            ];
            \DB::table('logs')->insert($log_crud);
            
            if ($last_id) {
                
                DB::commit();
                return redirect()->route('exchange')->with('success', 'Record inserted successfully');
            } else {
                DB::rollback();
                return redirect()->back()->with('error', 'Failed to insert record')->withInput();
            }
        } catch (\Throwable $th) {
            dd($th);
            DB::rollback();
            return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();
        }
        
    }
//  insert /

//  view /
    public function view(Request $request){  
        $id = base64_decode($request->id);
                                
        $data = exchange::select('*')->where(['id' => $id])->first();
        // $country = exchange::select('obf_exchange.*')->where(['status'=>'active'])->get(); 
        $carcompany = carcompany::get();
        $obf = OBF::select('id','customer_name')->where('trade_car_value','=','yes')->get(); 
        return view('exchange.view')->with(['data' => $data,'carcompany' => $carcompany,'obf' => $obf]);
        
    }
// view /

// edit /
    public function edit(Request $request){
        $id = base64_decode($request->id);
                                
        $data = exchange::select('*')->where(['id' => $id])->first();
        // $country = exchange::select('obf_exchange.*')->where(['status'=>'active'])->get(); 
        $carcompany = carcompany::get();
        $obf = OBF::select('id','customer_name')->where('trade_car_value','=','yes')->get(); 
        return view('exchange.edit')->with(['data' => $data,'carcompany' => $carcompany,'obf' => $obf]);
        
    }
// edit /

//  update 
    public function update(Request $request){
        if($request->ajax()){
            return true ;
        }
       // $branch_admin=$request->branch_admin ? 1 : NULL;
        $crud = [
            'obf_id' => $request->obf_id,
            'seller_detail' => $request->seller_detail,
            'company_name' => $request->company_name,
            'variant' => $request->variant,
            'manufacturing_year' => $request->manufacturing_year,
            'registration_number' => $request->registration_number,
            'chassis_number' => $request->chassis_number,
            'engine_number' => $request->engine_number,
            'remarks' => $request->remarks,
            'colour' => $request->colour,
            'time' => $request->time,
            'amount' => $request->amount,
            'exchange_bonus' => $request->exchange_bonus,
            'total_exchange_amount' => ($request->amount)+($request->exchange_bonus),
            'amount_in_words' => $request->amount_in_words,
            'HPA' => $request->HPA,
            'car_status' => $request->car_status,
            'relation_with_obf' => $request->relation_with_obf, 
            'status' => 'active',
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => auth()->user()->id
        ];
        // pan_image  
        if(!empty($request->file('pan_image'))){
            $pan_image = '';
            $pan_image_name_arr = [];

            $pan_image_arr = $request->file('pan_image');
            foreach($pan_image_arr as $key => $file_value){
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "pan_image_".time()."_".$filename_three.'.'.$extension_three;

                array_push($pan_image_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/exchange/';
                
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
            if(!empty($pan_image_name_arr)){
                $pan_image = implode(",",$pan_image_name_arr);
            }
            $crud['pan_image'] = $pan_image;
        }
         // adhar_image  
         if(!empty($request->file('adhar_image'))){
            $adhar_image = '';
            $adhar_image_name_arr = [];

            $adhar_image_arr = $request->file('adhar_image');
            foreach($adhar_image_arr as $key => $file_value){
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "adhar_image_".time()."_".$filename_three.'.'.$extension_three;

                array_push($adhar_image_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/exchange/';
                
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
            if(!empty($adhar_image_name_arr)){
                $adhar_image = implode(",",$adhar_image_name_arr);
            }
            $crud['adhar_image'] = $adhar_image;
        }
         // rcbook  
         if(!empty($request->file('rcbook'))){
            $rcbook = '';
            $rcbook_name_arr = [];

            $rcbook_arr = $request->file('rcbook');
            foreach($rcbook_arr as $key => $file_value){
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "rcbook_".time()."_".$filename_three.'.'.$extension_three;

                array_push($rcbook_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/exchange/';
                
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
            if(!empty($rcbook_name_arr)){
                $rcbook = implode(",",$rcbook_name_arr);
            }
            $crud['rcbook'] = $rcbook;
        }
        // insurance  
        if(!empty($request->file('insurance'))){
            $insurance = '';
            $insurance_name_arr = [];

            $insurance_arr = $request->file('insurance');
            foreach($insurance_arr as $key => $file_value){
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "insurance_".time()."_".$filename_three.'.'.$extension_three;

                array_push($insurance_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/exchange/';
                
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
            if(!empty($insurance_name_arr)){
                $insurance = implode(",",$insurance_name_arr);
            }
            $crud['insurance'] = $insurance;
        }
         // totto  
         if(!empty($request->file('totto'))){
            $totto = '';
            $totto_name_arr = [];

            $totto_arr = $request->file('totto');
            foreach($totto_arr as $key => $file_value){
                $filenameWithExtension_three = $file_value->getClientOriginalName();
                $filename_three = pathinfo($filenameWithExtension_three, PATHINFO_FILENAME);
                $extension_three = $file_value->getClientOriginalExtension();
                $filenameToStore_three_new = "totto_".time()."_".$filename_three.'.'.$extension_three;

                array_push($totto_name_arr, $filenameToStore_three_new);                        
                $folder_to_upload_sn = public_path().'/uploads/exchange/';
                
                if(!\File::exists($folder_to_upload_sn))
                    \File::makeDirectory($folder_to_upload_sn, 0777, true, true);
                 $file_value->move($folder_to_upload_sn, $filenameToStore_three_new);
            }
            if(!empty($totto_name_arr)){
                $totto = implode(",",$totto_name_arr);
            }
            $crud['totto'] = $totto;
        }
        DB::beginTransaction();
        try {
            DB::enableQueryLog();
            $last_id ='';
            $last_id = exchange::insertGetId($crud);
            $update = exchange::where(['id' => $request->id])->update($crud);
            if($update){
                DB::commit();
                return redirect()->route('exchange')->with('success', 'Record updated successfully');
            } else {
                DB::rollback();
                return redirect()->back()->with('error', 'Failed to update record')->withInput();
            }
        } catch (\Throwable $th) {
            DB::rollback();
            return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();
        }
    }
//  update /

//  change-status /
    public function change_status(Request $request){
        if (!$request->ajax()) { exit('No direct script access allowed'); }
            
            $id = base64_decode($request->id);
            $data = exchange::where(['id' => $id])->first();
       
            if(!empty($data)){
                $update = exchange::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s')]);
                if($update){
                    return response()->json(['code' => 200]);
                }else{
                    return response()->json(['code' => 201]);
                }
            }else{
                return response()->json(['code' => 201]);
            }
    }
    
/* change-status /

/* car name as per obf*/
    public function car_name(Request $request){
        $id = $request->obf_id;
        $data = [];
        if($request->option_check == 'Car Name'){
            $carname = OBF::select('trade_car_name')->where('id',$id)->first();
            $car_name = $carname->trade_car_name;
        }
        $data['carname'] = $car_name;
        return json_encode(array('status'=> true ,'data' => $data));
    }

/* car name as per obf*/


        public function cancel_reason(Request $request){
            if (!$request->ajax()) {
                abort(403, 'No direct script access allowed');
            }
        
            $id = $request->id;
            $status = $request->status;
            $cancel_reason = $request->cancel_reason;
            
            $data = exchange::where(['id' => $id])->first();
            if (!empty($data)) {
                $update = exchange::where(['id' => $id])->update(['status' => $status,'cancel_reason' => $cancel_reason,'updated_by'=>auth()->user()->id, 'updated_at' => date('Y-m-d H:i:s')]);
        
                return response()->json(['code' => $update ? 200 : 201]); 
            }
            
            return response()->json(['code' => 201]);
        }
        
        public function sellingnote(Request $request) 
        {
            $id = base64_decode($request->id);
                                
            $data = exchange::select('*')->where(['id' => $id])->first();
            
            $exchange_seller_data = \DB::table('exchange_sell')->where('exchange_id',$id)->first();

            $branch = Branch::where('id',$exchange_seller_data->branch_id)->first();
            
            $exchange_cash_data = \DB::table('exchange_cash_receipt')->where('exchange_id',$id)->first();

            $carcompany = carcompany::get();
            
            $images = DB::table('global_configuration')
                ->select('gatepass_logo1', 'gatepass_logo2')
                ->first();
            $customer_data = \DB::table('exchange_sell')->where('exchange_id',$data->id)->where('status','sell')->first();    
                
            return view('exchange.sellingnote')->with(['data' => $data,'carcompany' => $carcompany,'images' => $images,'customer_data' => $customer_data,'exchange_seller_data'=>$exchange_seller_data,'branch'=>$branch,'exchange_cash_data'=>$exchange_cash_data]);
        }
        
        public function sellingreceipt(Request $request) 
        {
            $id = base64_decode($request->id);
                                
            $data = exchange::select('*')->where(['id' => $id])->first();
            $carcompany = carcompany::get();
            $obf = OBF::select('id','customer_name')->where('trade_car_value','=','yes')->get(); 
    
            $images = DB::table('global_configuration')
                    ->select('gatepass_logo1', 'gatepass_logo2')
                    ->first();
        
            return view('exchange.sellingreceipt')->with(['data' => $data,'carcompany' => $carcompany,'obf' => $obf,'images' => $images]);
        }
        
        public function exchange_receipt_create(Request $request)
        {
            $id = base64_decode($request->id);
            view()->share('id',$id);
            $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 = ExchangeCashReceipt::where(['exchange_id' => $id])->first();   
            }
            
            $bank_account = DB::table('bank_account')->select('id','name')->where('status', 'active')->groupBy('bank_account.id')->get(); 
            
           
            if ($cash_receipt_data) {
                return view('exchange.exchangereceipt')->with([
                    'data' => $cash_receipt_data,
                    'cash_receipt_data' => $cash_receipt_data,
                    'bank_account' => $bank_account, 
                ]);
            } else {
                return view('exchange.exchangereceipt')->with([
                    'error' => 'No record found!',
                    'data' => null,
                    'cash_receipt_data' => $cash_receipt_data,
                    'bank_account' => $bank_account, 
                ]);
            }
        }
        
        public function insert_cash_receipt(Request $request)
        {
            $id = $request->id;

            $request->validate([
                'amount' => 'nullable|numeric|min:0',
            ]);

            if ($request->amount == 0 || $request->amount == null) {
                return redirect()->back()->with('error', 'Amount must be greater than 0.')->withInput();
            }
            
            $exchange_data = exchange::where(['id' => $id])->exists();
            $data = [];
            if($exchange_data){
                $data = exchange::where(['id' => $id])->first();
            }

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

                    $data->exchange_id = $id;
                    $data->amount = $request->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->cash_remark = $request->cash_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' => 'exchange_cash_receipt',
                        'module_id' => $request->cash_receipt_data_id,
                        'status' => 'exchange_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 ExchangeCashReceipt();
                    $data->exchange_id = $id;
                    $data->amount = $request->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->cash_remark = $request->cash_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();

                    $cash_receipt_id_get = $data->id;
                    
                    $crud = [
                        'module_nm' => 'exchange_cash_receipt',
                        'module_id' => $cash_receipt_id_get,
                        'status' => 'exchange_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);
                }

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

                    return redirect()->route('exchange')->with('success', $msg);
                } else {                   
                     return redirect()->back()->with('error', 'Failed to update record2')->withInput();
                }
            }else {
                return view('exchange')->with('error', 'No Record Found!');
            }
        }
        
        public function sell(Request $request){
            $crud = [
                'exchange_id' => $request->id,
                'branch_id' => $request->branch,
                'customer_name' => $request->customer_name ?? null,
                'contact_no' => $request->contact_no ?? null,
                'address' => $request->address ?? null,
                'status' => 'sell',
                'remark' => $request->remark ?? null,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id
            ];
            \DB::table('exchange_sell')->insert($crud);
            
            \DB::table('exchange_purchase')->where('id',$request->id)->update(['status'=>'sell']);
            
            return response()->json(['code' => 200]);
        }

}