<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    protected $table = "payments";
    protected $fillable = [
        'company_id','amount','date','time','payment_id'
    ];
    public function company(){
        return $this->belongsTo('\App\Models\Company','company_id','id');
    }
    
    public $paypalEnv       = 'sandbox'?'sandbox':'production';
    public $paypalURL       = 'sandbox'?'https://api.sandbox.paypal.com/v1/':'https://api.paypal.com/v1/';
    public $paypalClientID  = 'ARnpVhpiySrvGrOB0o1WIsfHjKS9CsD_G4V2duow4Ad9pUBht6eatDgYxIra1u21XZw9wZ9Ey998TsHP';
    private $paypalSecret   = 'EL9niZvU6nPhfcbiv3QPl4P6E6Vk_ZZupi0_ym_aRszoUPuE2gwQwGrR1SY0Iu4CJh2P2MHR7KVr94TK';



    public function validate($paymentID){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->paypalURL.'oauth2/token');
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERPWD, $this->paypalClientID.":".$this->paypalSecret);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
        $response = curl_exec($ch);
        curl_close($ch);

        if(empty($response)){
            return false;
        }else{
            $jsonData = json_decode($response);
            $curl = curl_init($this->paypalURL.'payments/payment/'.$paymentID);
            curl_setopt($curl, CURLOPT_POST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer ' . $jsonData->access_token,
                'Accept: application/json',
                'Content-Type: application/xml'
            ));
            $response = curl_exec($curl);
            curl_close($curl);
            $result = json_decode($response);
            return $result;
        }
    }
}
