<?php
/**
 * File: TamiCheckout.php
 * Year: 2023
 */

namespace Tami\WooCommerce;

use Tami_WooCommerce_GW;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly
if ( ! class_exists( 'Tami\WooCommerce\TamiCheckout' ) ) {
	class TamiCheckout {

		private static ?TamiCheckout $instance = null;

		public function __construct() {
			add_action( 'wp_enqueue_scripts', array( $this, 'load_scripts' ) );
			add_action( 'wp_enqueue_scripts', array( $this, 'load_styles' ) );
			add_action( 'tami_woocommerce_order_failed', array( $this, 'failed_payment_hook' ), 10, 2 );
			add_action( 'tami_woocommerce_order_completed_success', array( $this, 'success_payment_hook' ), 10, 2 );
		}

		public static function get_checkout_fields(): array {
			$cartTotal = WC()->cart->total;
			if ( ! $cartTotal ) {
				$orderId    = WC()->session->get( 'order_awaiting_payment' );
				$orderTotal = 0;
				if ( $orderId ) {
					$order      = wc_get_order( $orderId );
					$orderTotal = $order->get_total();
				}
				$cartTotal = $orderTotal;
			}

			return [
				'checkoutNonce'        => wp_create_nonce( 'tami-checkout' ),
				'makePaymentNonce'     => wp_create_nonce( 'tami-make-payment-nonce' ),
				'paymentProcessDuring' => false,
				'paymentAmount'        => $cartTotal,
				'currencySymbol'       => html_entity_decode( get_woocommerce_currency_symbol() ),
				'paymentUrl'           => Tami_WooCommerce_GW::get_payment_url(),
				'installmentUrl'       => Tami_WooCommerce_GW::get_installment_url(),
				'successRedirectUrl'   => Tami_WooCommerce_GW::get_success_url(),
				'i18n'                 => [
					'required_parameters_missing' => __( 'Required parameters missing!', 'tami-payment' ),
					'unknown_error'               => __( 'Unknown error!', 'tami-payment' ),
					'confirmButtonText'           => __( 'Close', 'tami-payment' ),
				],
				'assetsPublicPath'     => self::get_assets( '' )
			];
		}

		public static function get_assets( $file ): string {
			$plugin_url = plugin_dir_url( TAMI_PLUGIN_PATH . '/tami-payment.php' );
			if ( ! str_starts_with( $file, '/' ) ) {
				$file = '/' . $file;
			}

			return trim( $plugin_url, '/' ) . '/checkout/assets' . $file;
		}

		public static function tami_swal_i18n(): array {
			return [
				'confirmButtonText' => __( 'Close', 'tami-payment' )
			];
		}

		public function load_scripts() {
			$payment_object         = new Tami_WooCommerce_GW();
			$common_payment_enabled = $payment_object->payment_object()->getPaymentMethod() === 'Commonpayment';
			wp_add_inline_script( 'jquery', sprintf( 'var tamiCommonPageEnabled = %s, tamiPaymentForm = {}, tamiFrontendAppRendered = false, tamiCheckoutFields = {}, tamiCheckoutFields = %s;', $common_payment_enabled ? 'true' : 'false', wp_json_encode( TamiCheckout::get_checkout_fields() ) ) );
			wp_register_script( 'tami_woocommerce_checkout_swal2', self::get_assets( '/js/sweetalert2.all.min.js' ), array(), '1.0', true );
			wp_register_script( 'tami_woocommerce_checkout_process', self::get_assets( '/js/tami-checkout-process.js' ), array(), '1.0', true );
			wp_register_script( 'tami_woocommerce_checkout_app_vendors', self::get_assets( '/js/tami-checkout-app-vendors.js' ), array(), '1.0', true );
			wp_register_script( 'tami_woocommerce_checkout_app', self::get_assets( 'js/tami-checkout-app.js' ), array(), '1.0', true );

			$checkoutApp_i18n = [
				'message'  => '',
				'card'     => [
					'cardHolder' => __( 'Card Holder', 'tami-payment' ),
					'fullName'   => __( 'Fullname', 'tami-payment' ),
					'expires'    => __( 'Expires', 'tami-payment' ),
					'MM'         => __( 'MM', 'tami-payment' ),
					'YY'         => __( 'YY', 'tami-payment' )
				],
				'cardForm' => [
					'cardNumber'                   => __( 'Card Number', 'tami-payment' ),
					'cardName'                     => __( 'Card Holder', 'tami-payment' ),
					'expirationDate'               => __( 'Card Expiration Date', 'tami-payment' ),
					'month'                        => __( 'Month', 'tami-payment' ),
					'year'                         => __( 'Year', 'tami-payment' ),
					'CVV'                          => __( 'CVV', 'tami-payment' ),
					'invalidCardNumber'            => __( 'Invalid card number!', 'tami-payment' ),
					'installmentTableNumber'       => __( 'Installment', 'tami-payment' ),
					'installmentTableTotal'        => __( 'Total', 'tami-payment' ),
					'installmentTableLabelAdvance' => __( 'Advance', 'tami-payment' ),
					/* translators: %d is replaced with installment number */
					'installmentTableLabel'        => __( '%d Installments', 'tami-payment' ),
				]
			];

			wp_localize_script( 'tami_woocommerce_checkout_swal2', 'tamiCheckoutSwal_i18n', self::tami_swal_i18n() );
			wp_localize_script( 'tami_woocommerce_checkout_app_vendors', 'tamiCheckoutApp_i18n', $checkoutApp_i18n );


			if ( is_checkout() ) {
				wp_enqueue_script( 'tami_woocommerce_checkout_swal2' );
				wp_enqueue_script( 'tami_woocommerce_checkout_process' );
				wp_enqueue_script( 'tami_woocommerce_checkout_app_vendors' );
				wp_enqueue_script( 'tami_woocommerce_checkout_app' );
			}
		}

		public function load_styles() {
			wp_register_style( 'tami_woocommerce_checkout_app', self::get_assets( '/css/tami-checkout-app.css' ), array(), '1.0' );
			wp_register_style( 'tami_woocommerce_checkout_process', self::get_assets( '/css/tami-checkout-process.css' ), array(), '1.0' );
			if ( is_checkout() ) {
				wp_enqueue_style( 'tami_woocommerce_checkout_process' );
				wp_enqueue_style( 'tami_woocommerce_checkout_app' );
			}
		}


		public static function getInstance(): ?TamiCheckout {
			if ( ! self::$instance ) {
				self::$instance = new TamiCheckout();
			}

			return self::$instance;
		}

		public function failed_payment_hook( $order_id, $exception_message ) {
			$order = wc_get_order( $order_id );
			if ( method_exists( $order, 'add_order_note' ) ) {
				$order->add_order_note(
					sprintf(
					/* translators: %1$s is replaced with order ID, %2$s is replaced with payment error message */
						__( '%1$s payment could not completed with success. Error message: %2$s', 'tami-payment' ),
						$order->get_id(),
						$exception_message
					)
				);
			}
		}

		public function success_payment_hook( $order_id = '', $result = '' ) {
			$order = wc_get_order( $order_id );
			if (
				is_array( $result )
			) {
				if ( isset( $result['installment'] ) ) {
					$order->update_meta_data( 'tami_installment', $result['installment'] );
				}
				if ( isset( $result['amount'] ) && $result['amount'] ) {
					$order->update_meta_data( 'tami_payment_amount', $result['amount'] );
				}
				if ( isset( $result['transaction_id'] ) && $result['transaction_id'] ) {
					$order->update_meta_data( 'tami_payment_transaction_id', $result['transaction_id'] );
				}
			}
			$order->update_meta_data( 'tami_payment_completed_time', time() );
			$order->save();
		}
	}
}
TamiCheckout::getInstance();
