<?php

/**
 * Redsys
 */
require DIRLIBCOMP . 'ApiRedsysREST/initRedsysApi.php';

function devolucion_redsys($conexion, $localizador ,$refund_amount, $descripcion_devolucion ){

    // DATOS REDSYS
    $sql_redsys_data = "SELECT r.*
                        FROM localizadores l JOIN Redsys r ON l.id_pedido = r.Ds_MerchantData
                        AND r.estado = 'pagado'
                        AND l.localizador like '" . $localizador . "'";

    $result_redsys_data = $conexion->query($sql_redsys_data);

    if ($result_redsys_data->rowCount() > 0) {
        $row_redsys_data = $result_redsys_data->fetch();

        $ds_merchant_order    = $row_redsys_data['Ds_Order'];
        $ds_merchant_amount   = isset($refund_amount) ? $refund_amount : $row_redsys_data['Ds_Amount'];
        $ds_merchant_currency = $row_redsys_data['Ds_Currency'];
        $ds_merchant_data     = $row_redsys_data['Ds_MerchantData'];
        $sala_horario_id      = $row_redsys_data['sala_horario_id'];

        // Vemos si tenemos la instalación y buscamos su configuración de redsys
        $sql_redsys_conf = "SELECT *
                            FROM instalaciones i
                            JOIN redsys_configuraciones rc ON i.redsys_conf_id = rc.id
                            WHERE i.id = 43
                            LIMIT 1"; /*$$instalacion*/
        $result_redsys_conf = $conexion->query($sql_redsys_conf);

        if (!is_bool($result_redsys_conf) && $result_redsys_conf->rowCount() > 0) {

            $row_redsys           = $result_redsys_conf->fetch();
            $redsys_key           = $row_redsys['Secret_Key'];
            $redsys_merchant_code = $row_redsys['Ds_Merchant_MerchantCode'];
            $redsys_terminal      = $row_redsys['Ds_Merchant_Terminal'];

            $sentencia        = "LOCALIZADOR - refund " . $localizador. " - order ". $ds_merchant_order;
            Insertar_Sentencia($sentencia, 'anulacion');

            $refundRequest = new RestOperationMessage();

            // Operation mandatory data
            $refundRequest->setAmount((string) $ds_merchant_amount); // i.e. 1,23 (decimal point depends on currency code)
            $refundRequest->setCurrency($ds_merchant_currency); // ISO-4217 numeric currency code
            $refundRequest->setMerchant($redsys_merchant_code);
            $refundRequest->setTerminal($redsys_terminal);
            $refundRequest->setOrder($ds_merchant_order);
            $refundRequest->setTransactionType(RESTConstants::$REFUND);

            // Other optional parameters example can be added by "addParameter" method
            $refundRequest->addParameter("DS_MERCHANT_PRODUCTDESCRIPTION", $descripcion_devolucion);

            // Service setting (Signature, Environment, type of payment)
            $entorno_redsys = RESTConstants::$ENV_SANDBOX;
            if(RedsysEnviromentProduction == true){
                $entorno_redsys = RESTConstants::$ENV_PRODUCTION;
                $sentencia        = "LOCALIZADOR - refund " . $localizador. " - Entorno produccion ". $entorno_redsys . " " . RedsysEnviromentProduction  ;
                Insertar_Sentencia($sentencia, 'anulacion');
            }
            $service = new RESTOperationService($redsys_key, $entorno_redsys);

            $refundResponse = $service->sendOperation($refundRequest);

            $sentencia        = "LOCALIZADOR - refund " . $localizador. " - " . $refund_amount. " Respuesta ". $refundResponse ;
            Insertar_Sentencia($sentencia, 'anulacion');
            
            switch ($refundResponse->getResult()) {
                case RESTConstants::$RESP_LITERAL_OK:

                    $sql_tpv = "INSERT INTO Redsys (Ds_MerchantData, Ds_Order, Ds_Amount, sala_horario_id, Ds_Currency, Ds_MerchantCode, Ds_Terminal, Ds_Signature,
                        Ds_Response, Ds_SecurePayment, Ds_TransactionType, Ds_Card_Country, Ds_AuthorisationCode, Ds_ConsumerLanguage, Ds_Date, Ds_Hour, estado, localizador) VALUES (?, ?, ?, ?, ?, ?, ?, ?,
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    $result_tpv = $conexion->prepare($sql_tpv);

                    $datos_redsys = array(
                        $ds_merchant_data,
                        $ds_merchant_order,
                        $ds_merchant_amount,
                        $sala_horario_id,
                        $refundResponse->getOperation()->getCurrency(),
                        $refundResponse->getOperation()->getMerchant(),
                        $refundResponse->getOperation()->getTerminal(),
                        $refundResponse->getOperation()->getSignature(),
                        $refundResponse->getOperation()->getResponseCode(),
                        $refundResponse->getOperation()->getSecurePayment(),
                        $refundResponse->getOperation()->getTransactionType(),
                        !empty($refundResponse->getOperation()->getCardCountry()) ? $refundResponse->getOperation()->getCardCountry() : 0,
                        $refundResponse->getOperation()->getAuthCode(),
                        $refundResponse->getOperation()->getLanguage(),
                        date("d/m/Y"),
                        date("H:i"),
                        'reembolso',
                        $localizador,
                    );

                    $exec_tpv = $result_tpv->execute($datos_redsys);

                    //Guardamos un log si no podemos realizar el registro en la bbdd
                    if ($exec_tpv != 1) {
                        $file = fopen(CARPETAPROYECTO . "/modules/visitas/reservas/modulos/RegistroErrorRedsysBBDD.txt", "a");
                        fwrite($file, print_r($exec_tpv, true) . PHP_EOL);
                        fwrite($file, print_r($datos_redsys, true) . PHP_EOL);
                        fclose($file);
                    }
                   
                    $resultado_reembolso = 1;
                
                    break;

                default:
                    $resultado_reembolso = -11;
                          
                                      
                    break;
            }
        }

    } else {
        $resultado_reembolso = -10;
    }

    return $resultado_reembolso;
}

function test_redsys(){
    return "ok";
}
