<?php

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/reembolso_paypal.txt');
error_reporting(E_ALL);

/**
 * Redsys
 */
require DIRLIBCOMP . 'autoload.php';

use PayPal\Api\Amount;
use PayPal\Api\Refund;
use PayPal\Api\Sale;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Rest\ApiContext;

function devolucion_paypal($conexion, $localizador ,$refund_amount, $descripcion_devolucion){
    
    // DATOS REDSYS
    $sql_paypal_data = "SELECT p.*, l.instalacion_id
                        FROM localizadores l JOIN Paypal p ON l.localizador = p.localizador
                        AND p.estado = 'pagado'
                        AND l.localizador like '" . $localizador . "'";
    
    $result_paypal_data = $conexion->query($sql_paypal_data);
    
    if ($result_paypal_data->rowCount() > 0) {
        $row_paypal_data = $result_paypal_data->fetch();
    
        $saleId          = $row_paypal_data['txn_id'];
        $amount          = isset($refund_amount) ? $refund_amount : $row_paypal_data['mc_gross'];
        $currency        = $row_paypal_data['mc_currency'];
        $invoice         = $row_paypal_data['invoice'];
        $payer_id        = $row_paypal_data['payer_id'];
        $sala_horario_id = $row_paypal_data['sala_horario_id'];
        $instalacion_id  = $row_paypal_data['instalacion_id'];
    
        // ### Refund object
        $refund = new Refund();
    
        $amt = (new Amount())->setTotal($amount)->setCurrency($currency);
        $refund->setAmount($amt);
        $refund->setReason('Sale refund');
    
        // ###Sale
        // A sale transaction.
        // Create a Sale object with the
        // given sale transaction id.
        $sale = new Sale();
        $sale->setId($saleId);
        try {
            // print '<pre>' . print_r( PaypalClientId , true) .'</pre>';
            // Create a new apiContext object so we send a new
            // PayPal-Request-Id (idempotency) header for this resource
            $apiContext = getApiContext(PaypalClientId, PaypalClientSecret);
    
            // Refund the sale
            // (See bootstrap.php for more on `ApiContext`)
            $refundedSale = $sale->refund($refund, $apiContext);
    
            $sql_tpv    = "INSERT INTO Paypal (mc_gross, invoice, payer_id, payment_date, txn_id, localizador, estado, sala_horario_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $result_tpv = $conexion->prepare($sql_tpv);
            $exec_tpv   = $result_tpv->execute(array(
                $amount,
                $invoice,
                $payer_id,
                date("Y-m-d H:i:s"),
                $saleId,
                $localizador,
                'reembolso',
                $sala_horario_id,
            ));
         
            $resultado_reembolso  = 1;
    
        } catch (Exception $e) {
         
            $resultado_reembolso  = 0;
          
            $TEXTRESERVAREEMBOLSADA = _('Su reembolso no ha podido ser realizado. Por favor, póngase en contacto con nuestro equipo de atención al cliente.');
        
            $file = fopen(__DIR__ . "reembolso_paypal.txt", "a");
            fwrite($file, print_r( $e->getMessage(), true) . PHP_EOL);
            fclose($file);
        
        }
        
    } else {
        $resultado_reembolso  = -1;
        
    }
    return $resultado_reembolso;
}


function getApiContext($clientId, $clientSecret)
{

    // #### SDK configuration
    // Register the sdk_config.ini file in current directory
    // as the configuration source.
    /*
    if(!defined("PP_CONFIG_PATH")) {
    define("PP_CONFIG_PATH", __DIR__);
    }
     */

    // ### Api context
    // Use an ApiContext object to authenticate
    // API calls. The clientId and clientSecret for the
    // OAuthTokenCredential class can be retrieved from
    // developer.paypal.com

    $apiContext = new ApiContext(
        new OAuthTokenCredential(
            $clientId,
            $clientSecret
        )
    );

    // Comment this line out and uncomment the PP_CONFIG_PATH
    // 'define' block if you want to use static file
    // based configuration

    $apiContext->setConfig(
        array(
            'mode'           =>  PaypalMode,
            'log.LogEnabled' => true,
            'log.FileName'   => 'PayPal.log',
            'log.LogLevel'   => 'DEBUG', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
            'cache.enabled'  => true,
            //'cache.FileName' => '/PaypalCache' // for determining paypal cache directory
            // 'http.CURLOPT_CONNECTTIMEOUT' => 30
            // 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'
            //'log.AdapterFactory' => '\PayPal\Log\DefaultLogFactory' // Factory class implementing \PayPal\Log\PayPalLogFactory
        )
    );

    // Partner Attribution Id
    // Use this header if you are a PayPal partner. Specify a unique BN Code to receive revenue attribution.
    // To learn more or to request a BN Code, contact your Partner Manager or visit the PayPal Partner Portal
    // $apiContext->addRequestHeader('PayPal-Partner-Attribution-Id', '123123123');

    return $apiContext;
}
