<?php

namespace Yajny\Member\Models;

use App\Http\Controllers\Member\Payment as AppPayment;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Api\PayoutSenderBatchHeader;
use PayPal\Api\Payout;
use PayPal\Api\Currency;
use PayPal\Api\PayoutItem;
use PayPal\Api\PayoutBatch;




class PaypalPayout {

    public function __construct()
    {
        /** PayPal api context **/
        $paypal_conf = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'],$paypal_conf['secret']));
        $this->_api_context->setConfig($paypal_conf['settings']);
    }

    public function payPal_payOut($email,$amount) {

        $currency =  config('website.cnf_system_currency');


        $payouts = new Payout();
        $senderBatchHeader = new PayoutSenderBatchHeader();

        $senderBatchHeader->setSenderBatchId(uniqid())
                        ->setEmailSubject("You have a payment");

        $currency_data = new Currency;
        $currency_data->setCurrency( $currency)->setValue(2);
                        // ->setValue($amount);
                        

                        // TODO : Make this dynamic

        $senderItem1 = new PayoutItem();
        $senderItem1->setRecipientType('EMAIL')
                    ->setNote('Thanks you.')
                    ->setReceiver($email)
                    ->setSenderItemId("item_1" . uniqid())
                    ->setAmount($currency_data);


        $payouts->setSenderBatchHeader($senderBatchHeader)
                ->addItem($senderItem1);
        
        try {
            $output = $payouts->create(null, $this->_api_context);
            
        }catch (\PayPal\Exception\PayPalConnectionException $ex) {
            return $ex;
        } catch (Exception $ex) {    
            return $ex;
        }

        return $output;

    }



    public function getBatchStatus($payoutBatchId) {

        $payouts = new Payout();

        try {
            $output = $payouts->get($payoutBatchId, $this->_api_context);
        } catch (Exception $ex) {
            return $ex;
        }

        return $output;
    }

}

