<?php


namespace App\Http\Controllers\Tests;


use App\Http\Controllers\Controller;
use App\Services\OnlinePayments\PayPalRest;
use Illuminate\Http\Request;

class PayPalController extends Controller {
    protected $paypal;

    public function __construct(){
        $this->paypal = new PayPalRest();
    }

    public function index(){
        return view("tests.paypal.index");
    }

    public function charge(Request $request){
            try {
                $params = [
                    "amount" => $request->amount,
                    "currency" => env("PAYPAL_CURRENCY","USD"),
                    "returnUrl" => route("tests.paypal.success"),
                    "cancelUrl" => route("tests.paypal.error"),
                ];
               // $response =  $this->paypal->gateway->purchase($params)->send();
                $response = $this->paypal->purchase($params);
                $data = $response->getData();

                $datasTransaction = [
                    "reference" => $data['id'] ?? ""
                ];

                if ($response->isRedirect()){
                    write_log("tests/paypal-rest/charge",json_encode($data));
                    dd($response,$response->getTransactionReference(),$response->getRedirectUrl());
                    return $response->redirect() ;
                }else{
                    return $response->getMessage();
                }
            }catch (\Exception $exception){
                return format_exception_message($exception);
            }

    }

    public function success(Request $request){

        if ($request->filled("PayerID") and $request->filled("paymentId")){
            try {
                $params = [
                    "payer_id" => $request->PayerID,
                    "transactionReference" => $request->paymentId,
                ];

              //  $response = $this->paypal->gateway->completePurchase($params);
               $response = $this->paypal->complete($params);
                $data = $response->getData();

                $datasTransaction = [
                    "id" => $data['id'] ?? "",
                    "param" => $params,
                   // "TransactionReference" => $response->getTransactionReference(),
                    "data" => $data,

                ];

                if ($response->isSuccessful()){
                    //le client a payer correctement
                    write_log("tests/paypal-rest/success",json_encode($data));
                    return "Pay success with Id : ".$data['id'] ?? "";
                }else{
                    return $response->getMessage();
                }
            }catch (\Exception $exception){
                return format_exception_message($exception);
            }
        }
        else{
            return "Transaction declined";
        }

    }

    public function error(){
      return "The User Canceled payment";
    }
}
