• File: RefundKyc.php
  • Full Path: /var/www/imalipartnersapi/app/Classes/RefundKyc.php
  • Date Modified: 02/07/2023 8:01 PM
  • File size: 18.58 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php

namespace App\Classes;

use App\Bank\Payment;
use App\Imali\ImaliAccount;
use App\Imali\ImaliAccountConfig;
use App\Imali\MerchantAccount;
use App\PeriodCloseStore;
use App\Refund;
use App\Store;
use App\StoreConfig;
use App\User;
use App\UserClient;
use DateTime;
use DateTimeZone;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use DB;

class RefundKyc
{
    public function checkRefundPaymentStore(Request $request)
    {

//        $merchantActivo = MerchantAccount::query()
//            ->where('id', '=', $request->user()->id)
//            ->where('status', '=', 'activa')
//            ->first();

        $merchant = MerchantAccount::query()
            ->join('stores', 'stores.merchant_account_id', '=', 'merchant_accounts.id')
            ->where('stores.account_number', '=', $request->storeAccountNumber)
            ->select('merchant_accounts.*', 'stores.balance as store_balance')
            ->first();

        $merchantActivo = MerchantAccount::query()
            ->join('stores', 'stores.merchant_account_id', '=', 'merchant_accounts.id')
            ->where('stores.account_number', '=', $request->storeAccountNumber)
            ->where('merchant_accounts.status', '=', 'activa')
            ->select('merchant_accounts.*')
            ->first();


        $payment = Payment::query()
            ->where('transaction_id', '=', $request->paymentTransaction)
            ->first();

        $paymentType = Payment::query()
            ->where('transaction_id', '=', $request->paymentTransaction)
            ->where('payment_type', '=', 'reembolso')
            ->first();

        if ($paymentType) {
            return response()->json(['message' => 'Este tipo de pagamento não recebe reembolso'], 400);
        }

        $store = Store::query()->where('account_number', '=', $request->storeAccountNumber)->first();

        $customer = ImaliAccount::query()->where('account_number', '=', $request->customerAccountNumber)->first();

        if ($payment->store_id != $store->id) {
            return response()->json(['message' => 'Está loja não faz parte da transacção'], 407);
        }

        if ($customer->user_id != $payment->sender_id) {
            return response()->json(['message' => 'Este cliente não faz parte da transacção'], 407);
        }

        if (!$merchant) {
            return response()->json(['message' => 'Comerciante Inválido'], 400);
        }

        if (!$merchantActivo) {
            return response()->json(['message' => 'Está conta tem problemas: Estado da conta ' . $merchantActivo->status], 400);
        }

//        if (!Hash::check($request->password, $merchant->password)) {
        if (!Hash::check($request->password, $store->password)) {
            return response()->json(['message' => 'Password Incorrecto'], 400);
        }

//        $imaliConfig = ImaliAccountConfig::find($request->user()->kyc_config_id);
        $imaliConfig = ImaliAccountConfig::find($merchant->kyc_config_id);

//        if ($request->amount + $imaliConfig->taxa_refund_mechant > $merchant->balance) {
        if (($request->amount + $imaliConfig->taxa_refund_mechant) > $merchant->store_balance) {
            return response()->json(['message' => 'Saldo Insuficiente'], 400);
        }
        if (!is_numeric($request->amount)) {
            return response()->json(['message' => 'Montante inválido'], 402);
        }

        if ($request->amount <= 0) {
            return response()->json(['data' => 'Montante inválido'], 402);
        }

        if ($request->amount > ($payment->amount_credited + $imaliConfig->taxa_refund_mechant)) {
            return response()->json(['amount' => $request->amount, 'message' => 'Montante não disponível para Reemboldo ' . ($payment->amount_credited + $imaliConfig->taxa_refund_mechant)], 409);
        }

        $refund = Refund::query()
            ->where('payment_id', $payment->id)
            ->where('estado', '=', 'success')
            ->first();

        if ($refund) {
            return response()->json(['message' => 'Lamentamos, este pagamento já foi Reembolsado'], 401);
        }


        $imaliUser = ImaliAccount::query()
            ->where('account_number', '=', $request->customerAccountNumber)
            ->first();

        if (!$imaliUser) {
            return response()->json(['message' => 'Conta i.Mali inválida'], 404);
        }

        if (!$payment) {
            return response()->json(['message' => 'Pagamento Inválido'], 404);
        }

        $storeConfig = StoreConfig::query()->where('store_id', '=', $store->id)->first();

        if ($storeConfig) {

            if ($storeConfig->use_period == 1) {
                $lastPeriod = PeriodCloseStore::query()
                    ->join('stores', 'stores.id', '=', 'period_close_stores.store_id')
                    ->select('period_close_stores.*')
                    ->where('period_close_stores.store_id', '=', $store->id)
//                    ->where('period_close_stores.status', '=', 'fechado')
                    ->get()->last();

                if ($lastPeriod->status == 'fechado') {
                    return response()->json(['message' => 'Lamentamos, não pode fazer reembolso com o período fechado'], 400);
                }
            }

            if ($storeConfig->use_refund == 0) {
                return response()->json(['message' => 'Lamentamos, esta lojá não faz reembolsos'], 400);
            }

            if ($storeConfig->accept_payment == 0) {
                return response()->json(['message' => 'Lamentamos, esta lojá não recebe e nem faz pagamentos'], 400);
            }

        } else {
            return response()->json(['message' => 'Lamentamos, esta lojá não está configurada para operar'], 400);
        }
    }

    public function checkRefundPayment(Request $request)
    {
        $merchantActivo = MerchantAccount::query()
            ->where('id', '=', $request->user()->id)
            ->where('status', '=', 'activa')
            ->first();

        $merchant = MerchantAccount::query()
            ->join('stores', 'stores.merchant_account_id', '=', 'merchant_accounts.id')
            ->where('stores.account_number', '=', $request->storeAccountNumber)
            ->select('merchant_accounts.*', 'stores.balance as store_balance')
            ->first();

        $payment = Payment::query()
            ->where('transaction_id', '=', $request->paymentTransaction)
            ->first();

        $paymentType = Payment::query()
            ->where('transaction_id', '=', $request->paymentTransaction)
            ->where('payment_type', '=', 'reembolso')
            ->first();

        if ($paymentType) {
            return response()->json(['message' => trans('payment_cannot_refund')], 400);
        }


        $store = Store::query()->where('account_number', '=', $request->storeAccountNumber)->first();

        $customer = ImaliAccount::query()->where('account_number', '=', $request->customerAccountNumber)->first();

        if ($payment->store_id != $store->id) {
            return response()->json(['message' => trans('store_not_in_transaction')], 400);
        }

        if ($customer->user_id != $payment->sender_id) {
            return response()->json(['message' => trans('customer_not_in_transaction')], 400);
        }

        if (!$merchant) {
            return response()->json(['message' => trans('invalid_merchant')], 400);
        }

        if (!$merchantActivo) {
            return response()->json(['message' => trans('account_problem')], 400);
        }

        if (!Hash::check($request->password, $merchant->password)) {
            return response()->json(['message' => trans('wrong_password')], 400);
        }

//        $imaliConfig = ImaliAccountConfig::find($request->user()->kyc_config_id);
        $imaliConfig = ImaliAccountConfig::find($merchant->kyc_config_id);

//        if ($request->amount + $imaliConfig->taxa_refund_mechant > $merchant->balance) {
        if (($request->amount + $imaliConfig->taxa_refund_mechant) > $merchant->store_balance) {
            return response()->json(['message' => trans('not_enough_funds')], 400);
        }
        if (!is_numeric($request->amount)) {
            return response()->json(['message' => trans('invalid_amount')], 402);
        }

        if ($request->amount <= 0) {
            return response()->json(['data' => trans('invalid_amount')], 402);
        }
        if ($request->amount > ($payment->amount_credited + $imaliConfig->taxa_refund_mechant)) {
            return response()->json(['amount' => $request->amount, 'message' => trans('not_available_amount_to_refund') . ' ' . ($payment->amount_credited + $imaliConfig->taxa_refund_mechant)], 400);
        }

        $refund = Refund::query()
            ->where('payment_id', $payment->id)
            ->where('estado', '=', 'success')
            ->first();

        if ($refund) {
            return response()->json(['message' => trans('request_refunded')], 401);
        }

        $imaliUser = ImaliAccount::query()
            ->where('account_number', '=', $request->customerAccountNumber)
            ->first();

        if (!$imaliUser) {
            return response()->json(['message' => trans('invalid_imali_account')], 404);
        }

        if (!$payment) {
            return response()->json(['message' => trans('invalid_payment')], 404);
        }

        $storeConfig = StoreConfig::query()->where('store_id', '=', $store->id)->first();

        if ($storeConfig) {

            if ($storeConfig->use_refund == 0) {
                return response()->json(['message' => trans('store_cannot_refund')], 400);
            }

            if ($storeConfig->accept_payment == 0) {
                return response()->json(['message' => trans('store_cannot_receive_and_make_payments')], 400);
            }
        } else {
            return response()->json(['message' => trans('store_not_configured')], 400);
        }
    }

    public function checkRefundPaymentUSSD(Request $request)
    {
        $merchantActivo = MerchantAccount::query()
            ->where('id', '=', $request->user()->id)
            ->where('status', '=', 'activa')
            ->first();

        $merchant = MerchantAccount::query()
            ->join('stores', 'stores.merchant_account_id', '=', 'merchant_accounts.id')
            ->where('stores.mobile_phone', '=', $request->phone)
            ->select('merchant_accounts.*', 'stores.balance as store_balance')
            ->first();

        $payment = Payment::query()
            ->where('transaction_id', '=', $request->paymentTransaction)
            ->first();

        $paymentType = Payment::query()
            ->where('transaction_id', '=', $request->paymentTransaction)
            ->where('payment_type', '=', 'reembolso')
            ->first();

        if ($paymentType) {
            return response()->json(['message' => 'Este tipo de pagamento não recebe reembolso'], 400);
        }


        $store = Store::query()->where('account_number', '=', $request->storeAccountNumber)->first();

        $customer = ImaliAccount::query()->where('account_number', '=', $request->customerAccountNumber)->first();

        if ($payment->store_id != $store->id) {
            return response()->json(['message' => 'Está loja não faz parte da transacção'], 407);
        }

        if ($customer->user_id != $payment->sender_id) {
            return response()->json(['message' => 'Este cliente não faz parte da transacção'], 407);
        }

        if (!$merchant) {
            return response()->json(['message' => 'Comerciante Inválido'], 400);
        }

        if (!$merchantActivo) {
            return response()->json(['message' => 'Está conta tem problemas: Estado da conta ' . $merchantActivo->status], 400);
        }

        if (!Hash::check($request->password, $merchant->password)) {
            return response()->json(['message' => 'Password Incorrecto'], 400);
        }

//        $imaliConfig = ImaliAccountConfig::find($request->user()->kyc_config_id);
        $imaliConfig = ImaliAccountConfig::find($merchant->kyc_config_id);

//        if ($request->amount + $imaliConfig->taxa_refund_mechant > $merchant->balance) {
        if (($request->amount + $imaliConfig->taxa_refund_mechant) > $merchant->store_balance) {
            return response()->json(['message' => 'Saldo Insuficiente'], 400);
        }
        if (!is_numeric($request->amount)) {
            return response()->json(['message' => 'Montante inválido'], 402);
        }

        if ($request->amount <= 0) {
            return response()->json(['data' => 'Montante inválido'], 402);
        }

        if ($request->amount > ($payment->amount_credited + $imaliConfig->taxa_refund_mechant)) {
            return response()->json(['amount' => $request->amount, 'message' => 'Montante não disponível para Reemboldo ' . ($payment->amount_credited + $imaliConfig->taxa_refund_mechant)], 409);
        }

        $refund = Refund::query()
            ->where('payment_id', $payment->id)
            ->where('estado', '=', 'success')
            ->first();

        if ($refund) {
            return response()->json(['message' => 'Lamentamos, este pagamento já foi Reembolsado'], 401);
        }


        $imaliUser = ImaliAccount::query()
            ->where('account_number', '=', $request->customerAccountNumber)
            ->first();

        if (!$imaliUser) {
            return response()->json(['message' => 'Conta i.Mali inválida'], 404);
        }

        if (!$payment) {
            return response()->json(['message' => 'Pagamento Inválido'], 404);
        }

        $storeConfig = StoreConfig::query()->where('store_id', '=', $store->id)->first();

        if ($storeConfig) {

            if ($storeConfig->use_refund == 0) {
                return response()->json(['message' => 'Lamentamos, esta lojá não faz reembolsos'], 400);
            }

            if ($storeConfig->accept_payment == 0) {
                return response()->json(['message' => 'Lamentamos, esta lojá não recebe e nem faz pagamentos'], 400);
            }
        } else {
            return response()->json(['message' => 'Lamentamos, esta lojá não está configurada para operar'], 400);
        }
    }

    public function checkConfirmRefund(Request $request)
    {
        $refund = Refund::query()
            ->where('transaction', '=', $request->transaction_id)
            ->first();

        $token = Refund::query()
            ->where('transaction', '=', $request->transaction_id)
            ->where('token', '=', $request->token_otp)
            ->first();

        $paymentRefund = Payment::query()
            ->where('transaction_id', '=', $request->paymentID)
            ->where('refund_confirmation', '=', 1)
            ->first();

        if ($paymentRefund) {
            return response()->json(['message' => trans('payment_received_refunds')], 400);
        }

        if (!$refund) {
            return response()->json(['message' => trans('invalid_request_payment')], 404);
        }

        $paymentG = Refund::query()
//            ->where('transaction', '=', $refund->transaction)
            ->where('transaction', '=', $request->transaction_id)
            ->where('estado', '=', 'successo')
            ->first();

        if ($paymentG) {
            return response()->json(['message' => trans('request_confirmed')], 401);
        }

        if (!$token) {
            return response()->json(['message' => trans('invalid_token')], 500);
        }

        if ($token) {
            $start_date = new DateTime($token->created_at, new DateTimeZone('Africa/Maputo'));
            $since_start = $start_date->diff(new DateTime(now(), new DateTimeZone('Africa/Maputo')));
//            echo $since_start->days.' days total<br>';
//            echo $since_start->y.' years<br>';
//            echo $since_start->m.' months<br>';
//            echo $since_start->d.' days<br>';
//            echo $since_start->h.' hours<br>';
//            echo $since_start->i.' minutes<br>';
//            echo $since_start->s.' seconds<br>';

            $minutos = 10;
            if ($since_start->i >= $minutos) {
                $token->update([
                    'estado' => 'expirada'
                ]);
                return response()->json(['message' => trans('transaction_expired')], 401);
            }
        }

        $paymentExpired = Refund::query()
            ->where('transaction', $request->transaction_id)
            ->where('estado', '=', 'expirada')
            ->first();

        if ($paymentExpired) {
            return response()->json(['message' => trans('transaction_expired')], 401);
        }

        $account = Store::query()->where('id', '=', $refund->store_id)->first();

        if ($refund->amount <= 0) {
            return response()->json(['message' => trans('invalid_amount')], 402);
        }
        if (!is_numeric($refund->amount)) {
            return response()->json(['message' => trans('invalid_amount')], 402);
        }

        if ($account) {

            $paymentsTotal = Payment::query()
                ->where('store_id', $account->id)
                ->whereDate('created_at', '=', date('Y-m-d'))
                ->sum('amount_credited');


            if ($paymentsTotal < $refund->amount) {
                return response()->json(['message' => trans('not_enough_funds')], 400);
            }


            $user = User::query()
                ->where('id', '=', $refund->imali_user_id)
                ->first();

            if ($user->status != 1) {
                return response()->json(['message' => trans('imali_account_blocked')], 400);
            }

        }

//        $tokenAuth = str_replace('Bearer ', '', $request->header('authorization'));
//
//        $userClient = UserClient::query()
//            ->where('client_key', '=', $tokenAuth)
//            ->first();
//
//        $loja = Store::query()
//            ->where('user_client_id', $userClient->id)
//            ->where('id', $refund->store_id)
//            ->first();

        $loja1 = Store::query()
            ->where('id', '=', $refund->store_id)
            ->first();


        if (!$loja1) {
            return response()->json(['message' => trans('invalid_store')], 404);
        }

//        if (!$loja) {
//            return response()->json(['message' => 'Não tem permissão para fazer operações nesta loja'], 400);
//        }

    }
}