<?php

namespace App\Http\Controllers\BMControllers;

use Illuminate\Http\Request;
use App\Models\bmmodels\Customer;
use App\Models\bmmodels\CustomerWallet;
use App\Models\bmmodels\CustomerWalletTransaction;
use App\Models\bmmodels\AuditLog;
use Auth;
use Exception;
use ErrorException;

class WalletController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //get customers
        if(Auth::user()->user_type == 'organization')
        {
            try
            {
            $id = Auth::user()->bulk_cust_id;
             //get wallet for customer
            $wallet = CustomerWallet::where('customer_cust_id',$id)->orderByDesc('cust_wallet_id')->get();
            }
            catch(Exception $e)
            {
                abort(500, $e->getMessage());
            }
        }
        else if(Auth::user()->user_type == 'organization_user')
        {
            try
            {
            $id = Auth::user()->customer_cust_id;
             //get wallet for customer
            $wallet = CustomerWallet::where('customer_cust_id',$id)->orderByDesc('cust_wallet_id')->get();
            }
            catch(Exception $e)
            {
                abort(500, $e->getMessage());
            }
        }
        else {
            try
            {
                //get wallet for customer
            $wallet = CustomerWallet::orderByDesc('cust_wallet_id')->get();
            }catch(Exception $e)
            {
                abort(500, $e->getMessage());
            }
        }
        
        try
        {
        //get all customers for admin
        $customers = Customer::all();
       
        
        //get wallet transacts
        $transacts = CustomerWalletTransaction::where('cust_wallet_cust_wallet_id',$wallet[0]->cust_wallet_id)->get();
        
        return view('bmviews.wallet.index', compact('customers','transacts','wallet'));
        }
        catch(Exception $e)
            {
                abort(500, $e->getMessage());
            }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('bmviews.wallet.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $transacts = CustomerWalletTransaction::where('cust_wallet_cust_wallet_id',$id)->get();
        return view('bmviews.wallet.details',compact('transacts'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $walletdata = CustomerWallet::find($id);
        return view('bmviews.wallet.edit', compact('walletdata'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    //vue topup
    public function vueTopup(Request $request)
    {
        $this->validate($request, [
            'amount' => 'required',
            'type' => 'required|string',
            'reference' => 'required|string'
                   ]);
                   $id =$request->id;
                   $walletTrans = new CustomerWalletTransaction();
                   $walletTrans->wallet_trans_amount = $request->amount;
                   $walletTrans->wallet_trans_type = $request->type;
                   $walletTrans->wallet_trans_ref = $request->reference;
                   $walletTrans->cust_wallet_cust_wallet_id = $id;
                   $walletTrans->wallet_trans_status = 1;
                   //update waller balance
                   $wallet = CustomerWallet::find($id);
                   $wallet->cust_wallet_bal += $walletTrans->wallet_trans_amount;
           
                   // log data
                   $walletLog = new AuditLog();
                   
                   if(Auth::user()->user_type == 'organization'){
                    $walletLog->audit_module = "Customer";
                    $walletLog->audit_activity = "Wallet of Customer ID# " .$request->customer. " updated by Kes. ".$walletTrans->wallet_trans_amount. " to Kes. ".$wallet->cust_wallet_bal." by Customer ID# " .Auth::user()->bulk_cust_id;
                    
                    $walletLog->user_category = "Customer";
                    $walletLog->user_id = Auth::user()->bulk_cust_id;
                    }
                   else if(Auth::user()->user_type == 'organization_user'){
                    $walletLog->audit_module = "User";
                    $walletLog->audit_activity = "Wallet of User ID# " .$request->customer. " updated by Kes. ".$walletTrans->wallet_trans_amount. " to Kes. ".$wallet->cust_wallet_bal." by User ID# " .Auth::user()->cust_user_id;
                    
                    $walletLog->user_category = "User";
                    $walletLog->user_id = Auth::user()->cust_user_id;
                   }
                   else{
                    $walletLog->audit_module = "Admin";
                    $walletLog->audit_activity = "Wallet of Customer ID# " .$request->customer. " updated by Kes. ".$walletTrans->wallet_trans_amount. " to Kes. ".$wallet->cust_wallet_bal." by Admin ID# " .Auth::user()->admin_id;
                    
                    $walletLog->user_category = "Admin";
                    $walletLog->user_id = Auth::user()->admin_id;
                    }

                   //dd($wallet . $walletTrans . $walletLog);
                   //save
                    //log
                   $module=$walletLog->audit_module;$activity=$walletLog->audit_activity;$user_category=$walletLog->user_category;$user_id=$walletLog->user_id;$datetime=date('Y-m-d h:i:s');
       
                        $list = array (
                        array($module, $activity,  $user_category,$user_id, $datetime),
                        );
                        
                        $file = fopen("csvs/Audit.csv","a+");
                        
                        foreach ($list as $line) {
                        fputcsv($file, $line);
                        }
                        
                        fclose($file);
                        
                   $walletTrans->save();
                   $wallet->save();
                   $walletLog->save();
                   
            return response()->json($id);
    }
    public function update(Request $request, $id)
    {
        try
        {
        //update wallet
        request()->validate([
            'cust_wallet_bal'=> 'required',
        ]);
        //new wallet transaction
        $walletTrans = new CustomerWalletTransaction();
        $walletTrans->wallet_trans_amount = $request->get('cust_wallet_bal');
        $walletTrans->wallet_trans_type = $request->get('wallet_trans_type');
        $walletTrans->wallet_trans_ref = $request->get('wallet_trans_ref');
        $walletTrans->cust_wallet_cust_wallet_id = $id;
        //update waller balance
        $wallet = CustomerWallet::find($id);
        $wallet->cust_wallet_bal += $walletTrans->wallet_trans_amount;

        // log data
        $walletLog = new AuditLog();
        if(Auth::user()->user_type == 'organization')
        {
        $walletLog->audit_module = "Customer";
        $walletLog->audit_activity = "Wallet of Customer ID# ".$request->get('cust_id')." updated by Kes. ".$walletTrans->wallet_trans_amount. " to Kes. ".$wallet->cust_wallet_bal." by Customer ID# " .Auth::user()->bulk_cust_id;
        
        $walletLog->user_category = "Customer";
        $walletLog->user_id = Auth::user()->bulk_cust_id;
        }
        else if(Auth::user()->user_type == 'organization_user')
        {
        $walletLog->audit_module = "User";
        $walletLog->audit_activity = "Wallet of Customer ID# ".$request->get('cust_id')." updated by Kes. ".$walletTrans->wallet_trans_amount. " to Kes. ".$wallet->cust_wallet_bal." by User ID# " .Auth::user()->cust_user_id;
        
        $walletLog->user_category = "User";
        $walletLog->user_id = Auth::user()->cust_user_id;
        }
        else
        {
            $walletLog->audit_module = "Admin";
            $walletLog->audit_activity = "Wallet of Customer ID# ".$request->get('cust_id')." updated by Kes. ".$walletTrans->wallet_trans_amount. " to Kes. ".$wallet->cust_wallet_bal." by Admin ID# " .Auth::user()->admin_id;
            
            $walletLog->user_category = "Admin";
            $walletLog->user_id = Auth::user()->admin_id;
        }
        //dd($wallet . $walletTrans . $walletLog);
        // //save
        $walletTrans->save();
        $wallet->save();
        // $walletLog->save();
        return redirect()->back()->with('success','Wallet Updated Successfully');
    }
    
    catch (Exception $exception)
    {
            return back()->withInput()
            ->with(['failure' => 'Unexpected error occurred while trying to process your request. Please try Again.']);
    }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
