<?php
namespace App\Console\Commands;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Deposit;
use App\Models\Transaction;
use App\Models\Admin;
use Illuminate\Console\Command;
use App\Http\Services\PaymentServices;

class Payin extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:payin';

    /**
     * The console commands description.
     *
     * @var string
     */
    protected $description = 'Check users pending deposits';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(PaymentServices $payment)
    {
		$payName = [101 => 'shpay', 102 => 'gtr', 103 => 'ppay', 104 => 'otpay'];
		$now                = Carbon::now();
		
        try{

            $deposits = Deposit::where('method_code', 104)->take(50)->get();

            foreach($deposits as $index => $data){
				
				$checkPayment = $payment->check($data->trx, $payName[$data->method_code], $data->trx_source);

				if( $checkPayment['status'] == true){
					$record = $checkPayment['data']['data'];
					
					if( $record ){
						if( $data->method_code == 103 ){
							if( $record['state'] == 2 ){
								$updateData = self::updateDeposit($data, $record['amount'], $record);
								
							}elseif( $record['state'] == 3 || $record['state'] == 6 ){

								$data->admin_feedback  = 'Time for payment expired';
								$data->status = 3;
								$data->save();
							}else{
								$created = Carbon::parse($data->created_at);
								$difference = $created->diffInMinutes($now);
								if( $difference > 100 ){
									$data->admin_feedback  = 'Time for payment expired';
									$data->status = 3;
									$data->save();
								}
								
							}
						}elseif( $data->method_code == 102 ){
							if( $record['payStatus'] == 1 ){
								
								$updateData = self::updateDeposit($data, $record['realAmount'], $record, $record['tradeNo']);

							}else{

								$created = Carbon::parse($data->created_at);
								$difference = $created->diffInMinutes($now);
								
								if( $difference > 100 ){
									$data->admin_feedback  = 'Time for payment expired';
									$data->status = 3;
									$data->save();
								}
							}
						}elseif($data->method_code == 104 ){
							if( isset($record['payAmount']) && $record['payAmount'] > 10 ){
								
								$updateData = self::updateDeposit($data, $record['payAmount'], $record, $record['merchantOrderId']);

							}else{
								$created = Carbon::parse($data->created_at);
								$difference = $created->diffInMinutes($now);
								if( $difference > 100 ){
									$data->admin_feedback  = 'Time for payment expired';
									$data->status = 3;
									$data->save();
								}
							}
							
						}elseif($data->method_code == 101 ){
							dd($checkPayment);
						}
						
						$this->info($data->trx);
					}
					
				}else{
					$data->admin_feedback  = 'Invalid payment transaction';
					$data->status = 3;
					$data->save();
				}
				
            }
			
			$this->info('Payments updated');

        }catch(\Exception $ex){
			$this->info($ex->getMessage());
			//$admin = Admin::first();
            //sendGeneralEmail($admin->email, $ex->getMessage(), $ex->getMessage(), '');
        }
		
    }

    /**
     * Deposit update transaction
     */
    public static function updateDeposit( Deposit $deposit, string $amount, array $data , $source = null) {
        try {
            

            // Verify is transaction exisit
            if (!$deposit) throw new \Exception('Transaction not found');

            // Verify if transaction status not complete
            if (in_array($deposit->status, [1, 3])) throw new \Exception('Transaction was already complete');
            
            // Update transaction details
            $deposit->detail = $data;
            $deposit->status = 1;
			if( $source ){
				$deposit->trx_source = $source;
			}
            $deposit->save();

			$uBalance = 'balance'; 
			if(config('settings')->cur_text != 'NGN'){
				$uBalance = 'usdt_balance'; 
			}

            $user = User::find($deposit->user_id);

            // Update user balance
            $user->$uBalance = $user->$uBalance + $deposit->amount;
            $user->save();

            $transaction = Transaction::where('trx', $reference)->first();
            $transaction->status = 1;
            $transaction->save();

            return true;
        } catch (\Exception $th) {
            return $th->getMessage();
        }
    }

	
	
}