<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Openpay;
use OpenpayApiTransactionError;

require_once '../vendor/autoload.php';

class OpenPayController extends Controller
{
    /**
     * Create charge in OpenPay
     * https://www.openpay.mx/docs/api/?php#con-id-de-tarjeta-o-token
     *
     */

     public function __construct()
     {
       $this->id = env('OPEN_PAY_ID');
       $this->secret = env('OPEN_PAY_SECRET');
       $this->mode = env('OPEN_PAY_PRODUCTION_MODE');
     }

    public function store(Request $request)
    {
        try {
            // create instance OpenPay
            $openpay = Openpay::getInstance($this->id, $this->secret);

            Openpay::setProductionMode($this->mode);

            // create object customer
            $customer = array(
                'name' => $request->user()->customer->name,
                'last_name' => $request->user()->customer->last_name,
                'email' => $request->user()->email
            );

            $pago = (float)preg_replace('/[^0-9]+/', '',$request->get('amount'));
            // create object charge
            $chargeRequest =  array(
                'method' => 'card',
                'source_id' => $request->token,
                'amount' => (float) $request->amount,
                'currency' => 'MXN',
                'description' => $request->description,
                'device_session_id' => $request->deviceSessionId,
                'customer' => $customer
            );

            $charge = $openpay->charges->create($chargeRequest);

            return response()->json([
                'transaction_id' => $charge->id
            ]);

          } catch (OpenpayApiTransactionError $e) {

            return response()->json([
              'errors' => array([
                'code' => $e->getHttpCode(),
                'message' => $e->getMessage(),
                'error_code' => $e->getErrorCode(),
                'error_category' => $e->getCategory(),
                'request_id' => $e->getRequestId()
                ])
            ],$e->getHttpCode());

          } catch (OpenpayApiRequestError $e) {
            error_log('ERROR on the request: ' . $e->getMessage(), 0);
          } catch (OpenpayApiConnectionError $e) {
            error_log('ERROR while connecting to the API: ' . $e->getMessage(), 0);
          } catch (OpenpayApiAuthError $e) {
            error_log('ERROR on the authentication: ' . $e->getMessage(), 0);
          } catch (OpenpayApiError $e) {
            error_log('ERROR on the API: ' . $e->getMessage(), 0);
          } catch (Exception $e) {
            error_log('Error on the script: ' . $e->getMessage(), 0);
          }
    }
}
