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

namespace Tami\WooCommerce;

use DateTime;
use DateTimeZone;

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

		public static ?TamiAdminOrderDetails $instance = null;

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

			return self::$instance;
		}

		public function __construct() {

			add_action( 'add_meta_boxes', array( $this, 'add_widget_to_order' ) );
			$this->assets();
		}

		public function assets() {
			wp_register_style( 'tami_woocommerce_widget_style', TamiAdmin::get_assets( '/css/widget.css' ), false, '1.0.0' );
			wp_enqueue_style( 'tami_woocommerce_widget_style' );
		}

		public function add_widget_to_order() {
			$screen = ! tami_isHposDisabled() ? wc_get_page_screen_id( 'shop-order' ) : 'shop_order';
			add_meta_box(
				'tami_woocommerce_order_widget',
				__( 'Tami Payment Details', 'tami-payment' ),
				array( $this, 'widget' ),
				$screen,
				'side',
				'high'
			);
		}

		public function widget( $post_or_order_object ) {
			$order         = ( $post_or_order_object instanceof \WP_Post ) ? wc_get_order( $post_or_order_object->ID ) : $post_or_order_object;
			$amount        = $order->get_meta( 'tami_payment_amount', true );
			$refunded      = $order->get_meta( 'tami_refund_amount', true );
			$refunded_time = $order->get_meta( 'tami_refund_completed_time', true );


			$cardInfo = $order->get_meta( 'tami_threeD_started_card_info', true );
			if ( $cardInfo && strpos( $cardInfo, '{' ) === 0 ) {
				$cardInfo = json_decode( $cardInfo );
			}

			$installment     = $order->get_meta( 'tami_installment', true );
			$paymentTime     = $order->get_meta( 'tami_payment_completed_time', true );
			$transactionId   = $order->get_meta( 'tami_payment_transaction_id', true );
			$testPayment     = $order->get_meta( 'tami_test_environment_payment', true );
			$paymentDateTime = new DateTime();

			if ( $paymentTime ) {
				$paymentDateTime->setTimestamp( $paymentTime );
			}
			$tz = new DateTimeZone( 'Europe/Istanbul' );
			$paymentDateTime->setTimezone( $tz );

			if ( $refunded_time ) {
				$refundDateTime = new DateTime();
				$paymentDateTime->setTimestamp( $refunded_time );
				$tz = new DateTimeZone( 'Europe/Istanbul' );
				$refundDateTime->setTimezone( $tz );
			}

			$info_data   = [];
			$info_data[] = [
				'label' => __( 'Payment Time', 'tami-payment' ),
				'title' => $paymentDateTime->format( 'd/m/Y H:i:s (T)' ),
				'value' => $paymentDateTime->format( 'd/m/Y H:i:s' ) . ' (TSİ)'
			];
			$info_data[] = [
				'label' => __( 'Paid Total', 'tami-payment' ),
				'value' => get_woocommerce_currency_symbol( $order->get_currency() ) . '' . number_format( floatval( $amount ), 2 )
			];
			$info_data[] = [
				'label' => __( 'Installment', 'tami-payment' ),
				'value' => $installment
			];
			$info_data[] = [
				'label' => __( 'Transaction Number', 'tami-payment' ),
				'value' => $transactionId
			];
			if ( is_object( $cardInfo ) && isset( $cardInfo->maskedNumber ) ) {
				$info_data[] = [
					'label' => __( 'Card Number', 'tami-payment' ),
					'value' => sprintf( '%s%s', $cardInfo->maskedNumber, ( $cardInfo->cardType ? ' (' . $cardInfo->cardType . ')' : '' ) )
				];
			}
			if ( $refunded ) {
				$info_data[] = [
					'label' => __( 'Refund Total', 'tami-payment' ),
					'title' => __( 'Refund Total', 'tami-payment' ),
					'value' => get_woocommerce_currency_symbol( $order->get_currency() ) . '' . number_format( floatval( $refunded ), 2 )
				];
				if ( isset( $refundDateTime ) ) {
					$info_data[] = [
						'label' => __( 'Refund Time', 'tami-payment' ),
						'title' => $refundDateTime->format( 'd/m/Y H:i:s (T)' ),
						'value' => $refundDateTime->format( 'd/m/Y H:i:s' ) . ' (TSİ)'
					];
				}
				?>
                <span class="tami-text-paid-with-tami"><span
                            class="dashicons dashicons-warning"></span> <?php esc_attr_e( 'This payment refunded.', 'tami-payment' ); ?></span>
				<?php
			}
			if ( $testPayment ) {
				?>
                <span class="tami-text-paid-with-tami"><span
                            class="dashicons dashicons-warning"></span> <?php esc_attr_e( 'This payment was made in a test environment.', 'tami-payment' ); ?></span>
				<?php
			} else {
				?>
                <span class="tami-text-paid-with-tami"><?php esc_attr_e( 'This order paid with Tami!', 'tami-payment' ); ?></span>
				<?php
			}
			$widgetOut = '<div class="tami-widget-content" id="tami-widget-content-box" data-hidebox="' . empty( $paymentTime ) . '">';
			$widgetOut .= '<table border="0" cellpadding="0" cellspacing="0">';
			$widgetOut .= '<tbody>';

			foreach ( $info_data as $datum ) {
				$widgetOut .= sprintf(
					'<tr class="tami-widget-content-row">' .
					'<th class="tami-widget-content-title">%s</th>' .
					'<td title="%s" class="tami-widget-content-value">%s</td>' .
					'</tr>',
					esc_attr( $datum['label'] ),
					esc_attr( $datum['title'] ?? '' ),
					esc_attr( $datum['value'] ?? '' )
				);
			}

			$widgetOut .= '</tbody>';
			$widgetOut .= '</table>';
			$widgetOut .= '</div>';

			echo wp_kses( $widgetOut, [
				'div'   => array( 'class' => true, 'data-hidebox' => true ),
				'table' => array( 'border' => true, 'collspacing' => true, 'cellpadding' => true ),
				'tbody' => array(),
				'th'    => array( 'class' => true ),
				'tr'    => array( 'class' => true ),
				'td'    => array( 'title' => true, 'class' => true )
			] );
		}
	}
}

TamiAdminOrderDetails::getInstance();
