<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserWallet;
use App\Models\WalletTransaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class WalletController extends Controller  {

    public function __construct() {
        $this->middleware('auth:api');
    }

    public function getUserWallet() {

            $user = Auth::user();
            if($user) {
                $userId = $user->id;
                $userWallet = UserWallet::where('user_id', $userId)->with('walletTransaction');
                $userWallet = $userWallet->get();
                return response()->json(['data' => $userWallet], 200);
            }
    }

    public function saveWalletTransaction(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'transaction_amount' => 'required|numeric',
            'transaction_name' => 'required|string',
            'receipt' => 'required|string',
            'bank_name' => 'required|string',
            'account_number' => 'required|string',
            'account_name' => 'required|string',
            'transaction_purpose' => 'required|string',
            'transaction_date' => 'required|date'
        ]);

        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], 422);
        }


        $userId = Auth::user()->id;
        $getUserWalletcheck = UserWallet::where('user_id', $userId)->exists();
        if($getUserWalletcheck) {
        }else{
            $getUserObj = User::find($userId);
            $wallet = new UserWallet();
            $getUserObj->userWallet()->save($wallet);
        }
        $getUserWallet = UserWallet::where('user_id', $userId)->get();
        $getUserDetails = User::where('id', $userId)->get();
        $getBusinessName = $getUserDetails[0]['business_name'];
        $walletId = $getUserWallet[0]['id'];
        $walletObj = UserWallet::find($walletId);

        $transId = $this->generateTransactionId();

        $walletTransaction = new WalletTransaction();
        $walletTransaction->transaction_amount = $request['transaction_amount'];
        $walletTransaction->transaction_name = $request['transaction_name'];
        $walletTransaction->company_name = $getBusinessName;
        $walletTransaction->transaction_id = $transId;
        $walletTransaction->bank_name = $request['bank_name'];
        $walletTransaction->account_name = $request['account_name'];
        $walletTransaction->account_number = $request['account_number'];
        $walletTransaction->transaction_type = $request['transaction_purpose'];
        $walletTransaction->transaction_date = $request['transaction_date'];
        $receiptBase64 = $request['receipt'];
        $walletTransaction->receipt = $this->receiptImage($receiptBase64);
        $walletObj->walletTransaction()->save($walletTransaction);
        $response = WalletTransaction::where('user_wallet_id', $walletId)->get()->last();
        return response()->json(['data' => $response], 200);
    }

    protected function generateTransactionId() {
        $prefix = 'TransId';
        $batchkey = Carbon::now()->format('YmdHis');
        $suffix = rand(100, 999);
        return $prefix.$batchkey.$suffix;
    }

    protected function receiptImage($base64Image) {

        $image = explode('base64,',$base64Image);
        $image = end($image);
        $image = str_replace(' ', '+', $image);
        $uniqueid = uniqid();
        $file =  "/images/" . $uniqueid . '.png';

        Storage::disk('public')->put($file,base64_decode($image));

        $sourcePath = storage_path('app/public' . $file); // Get the source path in the storage directory
        $destinationPath = public_path('images/' . $uniqueid . '.png'); // Define the destination path in the public directory

        // Move the file from the storage directory to the public directory
        File::move($sourcePath, $destinationPath);

        $url = env('APP_URL').'/public'.$file;
        return $url;
    }

}
