<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
use App\Mail\OrderNotificationMail;

class PaymentController extends Controller
{
    public function process(Request $request)
    {
        // Validar los datos del formulario
        $request->validate([
            'nonce' => 'required|string',
            'amount' => 'required|numeric|min:0.01',
            'recipient_name' => 'required|string|max:255',
            'shipping_address' => 'required|string|max:500',
        ]);

        // Captura los datos de envío
        $recipientName = $request->recipient_name;
        $shippingAddress = $request->shipping_address;

        try {
            // Configurar credenciales de Authorize.Net
            $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
            $merchantAuthentication->setName(config('services.authorizenet.api_login_id'));
            $merchantAuthentication->setTransactionKey(config('services.authorizenet.transaction_key'));

            // Crear el objeto de pago con el nonce
            $opaqueData = new AnetAPI\OpaqueDataType();
            $opaqueData->setDataDescriptor('COMMON.ACCEPT.INAPP.PAYMENT');
            $opaqueData->setDataValue($request->nonce);

            $paymentOne = new AnetAPI\PaymentType();
            $paymentOne->setOpaqueData($opaqueData);

            // Crear la transacción
            $transactionRequestType = new AnetAPI\TransactionRequestType();
            $transactionRequestType->setTransactionType('authCaptureTransaction');
            $transactionRequestType->setAmount($request->amount);
            $transactionRequestType->setPayment($paymentOne);

            // Añadir un ID de referencia único para rastreo
            $refId = 'REF-' . time();
            $requestTransaction = new AnetAPI\CreateTransactionRequest();
            $requestTransaction->setMerchantAuthentication($merchantAuthentication);
            $requestTransaction->setRefId($refId);
            $requestTransaction->setTransactionRequest($transactionRequestType);

            // Ejecutar la transacción
            $controller = new AnetController\CreateTransactionController($requestTransaction);
            $environment = config('services.authorizenet.sandbox') ? \net\authorize\api\constants\ANetEnvironment::SANDBOX : \net\authorize\api\constants\ANetEnvironment::PRODUCTION;
            $response = $controller->executeWithApiResponse($environment);

            if ($response != null && $response->getMessages()->getResultCode() == 'Ok') {
                $tresponse = $response->getTransactionResponse();
                if ($tresponse != null && $tresponse->getResponseCode() == '1') {
                    // Pago exitoso
                    // Recuperar el carrito para el correo
                    $cart = session('cart', []);
                    // Enviar correo de notificación de pedido
                    try {
                        Mail::to('ernestico0693@gmail.com')->send(
                            new OrderNotificationMail([
                                'recipient_name' => $recipientName,
                                'shipping_address' => $shippingAddress,
                                'amount' => $request->amount,
                                'cart' => $cart,
                                'transaction_id' => $tresponse->getTransId(),
                                'ref_id' => $refId,
                            ])
                        );
                    } catch (\Exception $ex) {
                        Log::error('Error enviando correo de orden: ' . $ex->getMessage());
                    }
                    session()->forget('cart');
                    return response()->json([
                        'success' => true,
                        'transactionId' => $tresponse->getTransId(),
                        'refId' => $refId
                    ]);
                } else {
                    $errorCode = $tresponse ? $tresponse->getErrors()[0]->getErrorCode() : 'Unknown';
                    $errorMessages = $tresponse ? $tresponse->getErrors()[0]->getErrorText() : 'Transacción fallida';
                    Log::error("Payment failed: Code {$errorCode}, Message: {$errorMessages}, RefId: {$refId}");
                    return response()->json([
                        'success' => false,
                        'error' => $errorMessages
                    ], 400);
                }
            } else {
                $errorCode = $response ? $response->getMessages()->getMessage()[0]->getCode() : 'Unknown';
                $errorMessages = $response ? $response->getMessages()->getMessage()[0]->getText() : 'Respuesta inválida';
                Log::error("Payment failed: Code {$errorCode}, Message: {$errorMessages}, RefId: {$refId}");
                return response()->json([
                    'success' => false,
                    'error' => $errorMessages
                ], 400);
            }
        } catch (\Exception $e) {
            Log::error('Payment error: ' . $e->getMessage() . ', RefId: ' . (isset($refId) ? $refId : 'no-ref'));
            return response()->json([
                'success' => false,
                'error' => __('messages.payment_error')
            ], 500);
        }
    }
}