<?php
/**
 * Created by PhpStorm.
 * User: varun_2
 * Date: 23-01-2016
 * Time: 14:15
 */

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\File;
use DB ;


use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;

use PayPal\Api\Sale ;


class PaymentPaypalController extends Controller
{

    private $_api_context;

    public function __construct()
    {
        // setup 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 verifyPayment( Request $request )
    {
        if($request->has('id')
//            && $request->has('type')
//            && $request->has('order_id')
        )
        {
            $sale = null ;
            try
            {
                $sale = Sale::get($request->input('id') , $this->_api_context);
            } catch (Exception $ex) {
                return new JsonResponse( array(
                    "status#" => "1301",
                    "message" => $sale->getId()." Exception:". $ex
                ) ) ;
            }

            return new Response($sale->getAmount()) ;
        }
        return new JsonResponse( array(
            "status#" => "0"
        )) ;
    }

    public function _verifyPayment($request_id)
    {
        $sale = null ;
        try
        {
            $sale = Sale::get($request_id , $this->_api_context);
        } catch (Exception $ex) {
            return new JsonResponse( array(
                "status#" => "1301",
                "message" => $sale->getId()." Exception:". $ex
            ) ) ;
        }
        return $sale ;
    }

    public function logpaymentID(Request $request)
    {
        if($request->has('id')
            && $request->has('amount')
            && $request->has('type') )
        {
            $res['account'] = "PAYPAL" ;
            $res['id'] = $request->input('id') ;
            $res['type'] = $request->input('type') ;
            $res['amount'] = $request->input('amount') ;
            DB::table('payment_log')
                ->insert($res) ;
        }
        return new JsonResponse( array(
            "status#" => "500",
            "message" => "Partial input"
        ) ) ;
    }

}