<?php
/**
 * Razorpay Payment Gateway.
 *
 * Provides a Razorpay Payment Gateway.
 *
 * @class       Razorpay
 * @extends     PaymentGateway
 * @version     2.7.1
 * @package     Masteriyo\Classes\Payment
 */

namespace Masteriyo\Addons\Razorpay;

use Exception;
use Masteriyo\Abstracts\PaymentGateway;
use Masteriyo\Contracts\PaymentGateway as PaymentGatewayInterface;
use Masteriyo\Models\Order\Order;
use Razorpay\Api\Api;

defined( 'ABSPATH' ) || exit;

/**
 * Razorpay Payment Gateway Class
 *
 * Provides a Razorpay Payment Gateway.
 *
 * @package Masteriyo\Classes\Payment
 *
 * @version 2.7.1
 */
class Razorpay extends PaymentGateway implements PaymentGatewayInterface {
	/**
	 * Payment gateway identifier.
	 *
	 * @since 2.7.1
	 *
	 * @var string
	 */
	protected $name = 'razorpay';

	/**
	 * True if the gateway shows fields on the checkout.
	 *
	 * @since 2.7.1
	 *
	 * @var bool
	 */
	protected $has_fields = false;

	/**
	 * Whether or not logging is enabled
	 *
	 * @var bool
	 */
	public static $log_enabled = false;

	/**
	 * Logger instance
	 *
	 * @since 2.7.1
	 *
	 * @var Logger
	 */
	public static $log = false;

	/**
	 * Indicate if the sandbox mode is enabled.
	 *
	 * @since 2.7.1
	 *
	 * @var bool
	 */
	protected $sandbox = false;

	/**
	 * Indicate if the debug mode is enabled.
	 *
	 * @since 2.7.1
	 *
	 * @var bool
	 */
	protected $debug = false;

	/**
	 * Supported features such as 'default_credit_card_form', 'refunds'.
	 *
	 * @since 2.7.1
	 *
	 * @var array
	 */
	protected $supports = array( 'course' );

	/**
	 * Constructor for the gateway.
	 *
	 * @since 2.7.1
	 */
	public function __construct() {

		$this->order_button_text = __( 'Proceed to Razorpay', 'learning-management-system' );
		$this->method_title      = __( 'Razorpay', 'learning-management-system' );
		/* translators: %s: Link to Masteriyo system status page */
		$this->method_description = __( 'Razorpay redirects customers to Razorpay to enter their payment information.', 'learning-management-system' );

		// Load the settings.
		$this->init_settings();

		$this->debug       = false;
		self::$log_enabled = $this->debug;

		if ( $this->sandbox ) {
			/* translators: %s: Link to sandbox testing guide page */
			$this->description .= ' ' . sprintf( __( 'SANDBOX ENABLED.', 'learning-management-system' ) );
			$this->description  = trim( $this->description );
		}

		if ( $this->enabled ) {
			add_filter( 'masteriyo_thankyou_order_received_text', array( $this, 'order_received_text' ), 10, 2 );
		}
	}


	/**
	 * Logging method.
	 *
	 * @since 2.7.1
	 *
	 * @param string $message Log message.
	 * @param string $level Optional. Default 'info'. Possible values:
	 *                      emergency|alert|critical|error|warning|notice|info|debug.
	 */
	public static function log( $message, $level = 'info' ) {
	}

	/**
	 * Init settings for gateways.
	 *
	 * @since 2.7.1
	 */
	public function init_settings() {
		$this->enabled     = Setting::get( 'enable' );
		$this->title       = Setting::get( 'title' );
		$this->description = Setting::get( 'description' );
		$this->sandbox     = masteriyo_razorpay_test_mode_enabled();
	}

	/**
	 * Process the payment and return the result.
	 *
	 * @since 2.7.1
	 *
	 * @param  int $order_id Order ID.
	 *
	 * @return array
	 */
	public function process_payment( $order_id ) {
		// process payment.
		try {
			masteriyo_get_logger()->info( 'Razorpay payment processing started', array( 'source' => 'payment-razorpay' ) );
			masteriyo_get_logger()->info( 'Order ID: ' . $order_id, array( 'source' => 'payment-razorpay' ) );
			$order   = masteriyo_get_order( $order_id );
			$session = masteriyo( 'session' );

			if ( ! $order ) {
				masteriyo_get_logger()->error( 'Order not found', array( 'source' => 'payment-razorpay' ) );
				throw new Exception( __( 'Invalid order ID or order does not exist', 'learning-management-system' ) );
			}

			if ( ! $session ) {
				masteriyo_get_logger()->error( 'Session not found', array( 'source' => 'payment-razorpay' ) );
				throw new Exception( __( 'Session not found.', 'learning-management-system' ) );
			}

			list($key, $secret) = masteriyo_razorpay_get_key_secret();

			$api = new Api( $key, $secret );

			$receipt_id = get_bloginfo( 'admin_email' );

			$payment_intent_options = array(
				'receipt'  => $receipt_id,
				'amount'   => floatval( $order->get_total() ) * 100,
				'currency' => $order->get_currency(),
			);

			$razorpay_order    = $api->order->create( $payment_intent_options );
			$razorpay_order_id = $razorpay_order->id;

			$data = array(
				'key'         => $key,
				'amount'      => $order->get_total(),
				'name'        => $this->title,
				'description' => $this->description,
				'notes'       => array(
					'receipt' => $receipt_id,
				),
				'order_id'    => $razorpay_order_id,
			);

			masteriyo_get_logger()->info( 'Razorpay payment processing completed.', array( 'source' => 'payment-razorpay' ) );

			return array(
				'result'         => 'success',
				'data'           => $data,
				'redirect'       => $this->get_return_url( $order ),
				'payment_method' => 'razorpay',
				'order_id'       => $order_id,
			);

		} catch ( Exception $e ) {
			masteriyo_get_logger()->error( $e->getMessage(), array( 'source' => 'payment-razorpay' ) );
			throw new Exception( $e->getMessage() );
		}

	}

	/**
	 * Process refund.
	 *
	 * If the gateway declares 'refund' support, this will allow it to refund.
	 * a passed in amount.
	 *
	 * @since 2.7.1
	 *
	 * @param  int        $order_id Order ID.
	 * @param  float|null $amount Refund amount.
	 * @param  string     $reason Refund reason.
	 *
	 * @return boolean True or false based on success, or a WP_Error object.
	 */
	public function process_refund( $order_id, $amount = null, $reason = '' ) {
		return false;
	}

	/**
	 * Custom Razorpay order received text.
	 *
	 * @since 2.7.1
	 *
	 * @param string   $text Default text.
	 * @param Order $order Order data.
	 *
	 * @return string
	 */
	public function order_received_text( $text, $order ) {
		masteriyo_get_logger()->info( 'Razorpay order received text processing started', array( 'source' => 'payment-razorpay' ) );
		if ( $order && $this->name === $order->get_payment_method() ) {
			masteriyo_get_logger()->info( 'Razorpay order received text processing completed.', array( 'source' => 'payment-razorpay' ) );
			return esc_html__( 'Thank you for your payment. Your transaction has been completed, and a receipt for your purchase has been emailed to you. Log into your Razorpay account to view transaction details.', 'learning-management-system' );
		}

		return $text;
	}

	/**
	 * Get the transaction URL.
	 *
	 * @since 2.7.1
	 *
	 * @param  Order $order Order object.
	 *
	 * @return string
	 */
	public function get_transaction_url( $order ) {
		$order = masteriyo_get_order( $order );

		if ( $order ) {
			$this->view_transaction_url = 'https://dashboard.razorpay.com/app/payments/' . $order->get_transaction_id();
		}

		return parent::get_transaction_url( $order );
	}
}
