<?php

namespace App\Console\Commands\Payouts;

use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Yajny\EventsYj\Events\RecalculateBalance;
use Yajny\MailYj\Mails\NewContactEmail;
use Yajny\MailYj\Mails\PayoutsValidationStep1;
use Yajny\MailYj\Mails\PayoutsValidationStep2;
use Yajny\Member\Models\BalanceTransaction;
use Yajny\Member\Models\Sale;
use Yajny\Member\Models\UserNewBonus;
use Yajny\Member\Models\UserPayouts;
use Yajny\Member\Models\UserSales;


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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'check the status of processed payment that are not updated';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle() {


        $paymobToken=$this->tokenCurlCaller();
            $payouts = UserPayouts::where('status', 'processing')
                ->whereNotNull('api_response')
                ->where('api_response', '<>', '')
                ->get();
            foreach ($payouts as $payout){
                $response=json_decode($payout->api_response);
                $transactionId=$response->transaction_id;
                $ids=[];
                if ($transactionId){
                    $ids[]=$transactionId;
                   $newStatusResponse=$this->getPaymentUpdates($paymobToken,$ids);
                   $newDetails=$newStatusResponse->results;
                   if ($newDetails){
                       $newStatus=$newDetails[0]->disbursement_status;
                       if ($newStatus=="successful"){
                           $payout->status="completed";
                       }else if($newStatus=="rejected"){
                           $payout->status="declined";
                       }else{
                           $payout->status="pending";

                       }
                       $payout->save();
                       $this->output->write($payout->id. ' Updated Successfully',true);

                   }
                    sleep(60);

                }

            }

    }
    public function getPaymentUpdates($token,$transactionId){
        $client = new Client();
        $headers = [
            'Content-Type' => 'application/json',
            'Authorization'=> 'Bearer '. $token
        ];
        $response = $client->post('https://payouts.paymobsolutions.com/api/secure/transaction/inquire/', [
            'headers' => $headers,
            'json' => [
                "transactions_ids_list"=> $transactionId,
                "bank_transactions"=>true,
            ]
        ]);

        $statusCode = $response->getStatusCode();
        $body = $response->getBody()->getContents();
        return json_decode($body);
    }


    public function tokenCurlCaller()
    {
        $client = new Client();

        $response = $client->post('https://payouts.paymobsolutions.com/api/secure/o/token/', [
            'form_params' => [
                'client_id' => 'svkOYZkryThNBEZ1QAtrnCFZNVeCxH71palNhkD6',
                'client_secret' => 'aKve2VQ5g4znVuM7Afk19GzCEOhuRe57Nyo3pGQUpku0J1kOeKjBFUew0DfJlaqRvqGsfIEhBFgFJRdiRa5YWch1bslSYU5lHoCFsRTFSWRvu2oDMXCytuP6lonT5iDY',
                'username' => 'yajny_api_checker',
                'password' => 'Bs9Bv7H3ZQN5NNBEFkrruLy##kZD8GRd69ylW8LvzocYHhRWvsdap8',
                'grant_type' => 'password'
            ]
        ]);

        $statusCode = $response->getStatusCode();
        $body = $response->getBody()->getContents();

        return json_decode($body)->access_token;
    }
}
