<?php

namespace BitCode\BitFormPro\API\Controller;

use BitCode\BitFormPro\API\Controller\PaymentServices;
use BitCode\BitForm\Core\Util\Log;

class RazorpayPaymentController extends PaymentServices
{
  protected $paymentName = 'razorpay';
  protected $paymentType = 'order';

  public function handlePayment()
  {
    $razorpayDataString = file_get_contents('php://input');
    $razorpayData = json_decode($razorpayDataString);

    if ($razorpayData->event === 'payment.captured') {
      $this->formId = $this->sanitize($razorpayData->payload->payment->entity->notes->formID);
      $this->entryId = $this->sanitize($razorpayData->payload->payment->entity->notes->entryID);
      $this->fieldKey = $this->sanitize($razorpayData->payload->payment->entity->notes->fieldKey);
      $this->transactionId = $this->sanitize($razorpayData->payload->payment->entity->id);
      $this->apiResponseData = $razorpayData->payload->payment->entity;

      $this->savePaymentInfo();

      // test  return log
      wp_send_json_success('Razorpay payment captured and processed.', 200);
    } else {

      //TODO need to handle other events like payment.failed, etc.
      Log::debug_log("[Razorpay] Unhandled event: {$razorpayData->event}");
      $this->triggerTransactionFailure(null, null, null, null, $razorpayData, "Unhandled event: {$razorpayData->event}");
    }
  }

}