<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\UserWallet;
use App\Models\UserPayment;

class UserWalletAPIController extends Controller
{
    
    public function addWalletAmount(Request $request)
    {
        try{
            $post = $request->all();
            
            $user_id = 0;            
            if($request->userAuthData){
                $user_id = $request->userAuthData->user_id;
            }
            if ($user_id) {
                $wallet = [
                    'user_id'=>$user_id,
                    'type'=>'credit',
                    'amount'=>$post['wallet_amount'],
                    'description'=>'wallet amount added',
                    'created_at' => date("y-m-d H:i:s")
                ];
                $walletId = UserWallet::insertGetId($wallet);


                UserPayment::insertGetId([
                    "user_id" => $user_id,
                    "description" => 'wallet amount added',
                    "price" => $post['wallet_amount'],
                    "status" => "Paid",
                    "method" => "COD",
                    'created_at' => date("y-m-d H:i:s")
                ]);
                return $this->sendResponse($walletId,'Payment success');
            }else{
                return $this->sendError('User not found', 401);
            }

        }catch(RepositoryException $e){
            return $this->sendError($e->getMessage());
        }
    }

    public function list(Request $request)
    {
        try{
            $user_id = 0;            
            if($request->userAuthData){
                $user_id = $request->userAuthData->user_id;
            }            
            if ($user_id) {
                $UserWallet = UserWallet::where('user_id',$user_id)->orderBy('id','DESC')->get();
                return $this->sendResponse($UserWallet, 'Wallet transactions retrieved successfully');
            }else{
                return $this->sendError('User not found', 401);
            }
        }catch(RepositoryException $e){
            return $this->sendError($e->getMessage());
        }
    }

    public function walletAmountOfuser(Request $request)
    {
        try{
            $user_id = 0;            
            if($request->userAuthData){
                $user_id = $request->userAuthData->user_id;
            }
            if ($user_id) {
                $amount = UserWallet::where('user_id',$user_id)->sum('amount');
                return $this->sendResponse($amount, 'Wallet amount retrieved successfully');
            }else{
                return $this->sendError('User not found', 401);
            }
        }catch(RepositoryException $e){
            return $this->sendError($e->getMessage());
        }
    }
}
