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

namespace Tami\WooCommerce;
if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly
if ( ! class_exists( 'Tami\WooCommerce\TamiAdmin' ) ) {
	class TamiAdmin {
		// private $plugin_url;
		private array $plugin_pages = [
			'tami-admin'
		];

		private TamiAdminSettings $tami_admin_settings;

		public function __construct() {
			add_action( 'admin_menu', array( $this, 'tami_admin_menu' ) );
			add_action( 'admin_enqueue_scripts', array( $this, 'load_stylesheets' ) );
			add_action( 'admin_enqueue_scripts', array( $this, 'load_scripts' ) );
			$this->tami_admin_settings = new TamiAdminSettings();
			// module page redirect
			add_action( 'admin_init', array( $this, 'redirect_to_dashboard' ) );
		}

		public function redirect_to_dashboard() {
			$page    = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$tab     = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : '';// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$section = isset( $_GET['section'] ) ? sanitize_text_field( wp_unslash( $_GET['section'] ) ) : '';// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			if ( $page === 'wc-settings' && $tab === 'checkout' && $section === 'tami_woocommerce' ) {
				wp_redirect( admin_url( 'admin.php?page=tami-admin' ) );
			}
		}

		public static function get_faq(): array {
			return [
				(object) [
					'q' => __( 'How do I activate the installment options?', 'tami-payment' ),
					'a' => __( 'You can activate the installment options by going to the "Tami / Installments" menu and save the interest rates to be applied from this page. Login to Tami Portal to learn about interest rates.', 'tami-payment' )
				]
			];
		}

		public static function get_assets( $file, $return='url', $options = [] ): string {
			$plugin_url  = plugin_dir_url( TAMI_PLUGIN_PATH . '/tami-payment.php' );
			$urlStandard = trim( $plugin_url, '/' ) . '/admin/assets/' . $file;
			if (
				str_ends_with( $file, '.jpg' ) || str_ends_with( $file, '.png' ) || str_ends_with( $file, '.gif' )
				|| str_ends_with( $file, '.jpeg' )
			) {
				$fileHash      = md5( $file );
				$stored_assets = TamiAdminSettings::get_settings( 'stored_assets' );
				if ( isset( $stored_assets[ $fileHash ] ) ) {
					$attachment_id = $stored_assets[ $fileHash ];
					$file_path     = get_attached_file( $attachment_id );
                    if(file_exists($file_path)) {
	                    if($return === 'url')
		                    return wp_get_attachment_url( $attachment_id );
                        elseif ($return === 'html') {
                            return wp_get_attachment_image( $attachment_id, 'full', false, $options);
                        }
                    }
				}

				$upload_dir       = wp_upload_dir();
				$file_path        = TAMI_PLUGIN_PATH . 'admin/assets/' . $file;
				$destination_path = $upload_dir['path'] . '/' . basename( $file_path );

				if ( ! copy( $file_path, $destination_path ) ) {
					return $urlStandard;
				}


				$file_type  = wp_check_filetype( $destination_path );
				$attachment = array(
					'guid'           => wp_upload_dir()['url'] . '/' . basename( $destination_path ),
					'post_mime_type' => $file_type['type'],
					'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $destination_path ) ),
					'post_content'   => '',
					'post_status'    => 'inherit'
				);

				$attachment_id = wp_insert_attachment( $attachment, $destination_path );

				if ( ! is_wp_error( $attachment_id ) ) {
					require_once ABSPATH . 'wp-admin/includes/image.php';
					$attachment_data = wp_generate_attachment_metadata( $attachment_id, $destination_path );
					wp_update_attachment_metadata( $attachment_id, $attachment_data );
					$stored_assets[ $fileHash ] = $attachment_id;
					TamiAdminSettings::save_settings( 'stored_assets', $stored_assets, false );

				}

				if($return === 'url')
					return wp_get_attachment_url( $attachment_id );
                elseif ($return === 'html') {
					return wp_get_attachment_image( $attachment_id, 'full', false, $options);
				}
			}

			return $urlStandard;
		}

		public function is_order_detail_page(): bool {
			$screen = get_current_screen();
			$base   = $screen->get()->base;

			return $base == 'post' && isset($_GET['action']) && sanitize_text_field(wp_unslash($_GET['action'])) == 'edit';// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		}

		public function is_plugin_page(): bool {
			$current_page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';// phpcs:ignore WordPress.Security.NonceVerification.Recommended

			return in_array( $current_page, $this->plugin_pages );
		}

		public function load_stylesheets() {
			wp_register_style( 'tami_woocommerce_admin_global', self::get_assets( '/css/tami-global.css' ), false, '1.0.0' );
			wp_register_style( 'tami_woocommerce_app', self::get_assets( '/css/app.css' ), false, '1.0.0' );
			wp_register_style( 'tami_woocommerce_fontawesome', self::get_assets( '/fonts/fontawesome-free-6.4.0-web/css/all.min.css' ), false, '1.0.0' );

			if ( $this->is_plugin_page() ) {
				wp_enqueue_style( 'tami_woocommerce_app' );
				wp_enqueue_style( 'tami_woocommerce_fontawesome' );
			}
			wp_enqueue_style( 'tami_woocommerce_admin_global' );
		}

		public function load_scripts($hook) {
			wp_register_script( 'tami_woocommerce_main', self::get_assets( '/js/main.js' ), array(), '1.1', false );
			wp_register_script( 'tami_woocommerce_bootstrap', self::get_assets( '/js/bootstrap.bundle.js' ), array(), '1.0', false );
			wp_register_script( 'tami_woocommerce_checkout_swal2', TamiCheckout::get_assets( '/js/sweetalert2.all.min.js' ), array(), '1.0', false );

			wp_localize_script( 'tami_woocommerce_checkout_swal2', 'tamiCheckoutSwal_i18n', TamiCheckout::tami_swal_i18n() );
			wp_localize_script( 'tami_woocommerce_main', 'tamiAdminPanelTabs', array_map( function ( $item ) {
				return [
					'slug'    => $item->slug,
					'button'  => sprintf( 'tami-%s-tab-button', $item->slug ),
					'content' => sprintf( 'tab-tami-%s-tab', $item->slug )
				];
			}, self::get_pages() ) );

			wp_localize_script( 'tami_woocommerce_main', 'tamiAdminPanelGlobals', [
				'adminUI'               => null,
				'tamiAdminPanelMainUrl' => admin_url( 'admin.php?page=tami-admin' ),
				'i18n'                  => [
					'changes_saved'        => __( 'Changes saved!', 'tami-payment' ),
					'api_validate_success' => __( 'The information you entered looks correct.', 'tami-payment' ),
					'warning_before_save'  => __( 'Review before saving:', 'tami-payment' ),
					'warning_title'        => __( 'Warning', 'tami-payment' ),
					'warning_continue'     => __( 'Continue', 'tami-payment' ),
					'warning_cancel'       => __( 'Cancel', 'tami-payment' ),

				]
			] );

			if ( $this->is_plugin_page() ) {
				wp_enqueue_script( 'tami_woocommerce_checkout_swal2' );
				wp_enqueue_script( 'tami_woocommerce_main' );
				wp_enqueue_script( 'tami_woocommerce_bootstrap' );
			}

			if ( $this->is_order_detail_page() ) {
				global $post;
                $order_id = '';
				if ($hook === 'post.php' && isset($post) && $post->post_type === 'shop_order') {
					$order_id = $post->ID;
				}
				wp_register_script( 'tami_woocommerce_order_detail', self::get_assets( '/js/order-detail.js' ), array(), '1.0', false );
				wp_localize_script( 'tami_woocommerce_order_detail', 'tamiOrderDetailsVars', [
					'order_id' => $order_id,
					'hide'     => true
				] );
				wp_enqueue_script( 'tami_woocommerce_order_detail' );
			}
		}

		public static function get_pages() {
			$pages = [
				(object) [
					'label'   => __( 'Home', 'tami-payment' ),
					'slug'    => 'home',
					'icon'    => '<i class="fa fa-home"></i>',
					'content' => TAMI_PLUGIN_PATH . '/admin/views/pages/home.php'
				],
				(object) [
					'label'   => __( 'API Settings', 'tami-payment' ),
					'slug'    => 'api',
					'icon'    => '<i class="fa fa-cubes"></i>',
					'content' => TAMI_PLUGIN_PATH . '/admin/views/pages/api-settings.php'
				],
				(object) [
					'label'   => __( 'Installments', 'tami-payment' ),
					'slug'    => 'installment',
					'icon'    => '<i class="fa fa-credit-card"></i>',
					'content' => TAMI_PLUGIN_PATH . '/admin/views/pages/installment-settings.php'
				],
				(object) [
					'label'   => __( 'Plugin Settings', 'tami-payment' ),
					'slug'    => 'module',
					'icon'    => '<i class="fa fa-cogs"></i>',
					'content' => TAMI_PLUGIN_PATH . '/admin/views/pages/module-settings.php'
				],
				(object) [
					'label'   => __( 'Support', 'tami-payment' ),
					'slug'    => 'support',
					'icon'    => '<i class="fa fa-question-circle"></i>',
					'content' => TAMI_PLUGIN_PATH . '/admin/views/pages/support.php'
				]
			];

			return apply_filters( 'tami_woocommerce_admin_pages', $pages );
		}

		public function tami_admin_page_contents() {
			require_once TAMI_PLUGIN_PATH . '/admin/views/module-header.php';
			foreach ( self::get_pages() as $key => $page ) {
				echo sprintf( '<div class="tami-bg-default tami--tab-container tami-p-3" id="tab-tami-%s-tab" %s>', esc_attr( $page->slug ), ( ( $key > 0 ) ? ' style="display:none"' : '' ) );
				if ( is_file( $page->content ) && file_exists( $page->content ) ) {
					require_once( $page->content );
				}
				echo '</div>';
			}
			require_once TAMI_PLUGIN_PATH . '/admin/views/module-footer.php';
		}

		public function tami_admin_menu() {
			add_menu_page(
				__( 'Tami', 'tami-payment' ),
				__( 'Tami', 'tami-payment' ),
				'manage_options',
				'tami-admin',
				array( $this, 'tami_admin_page_contents' ),
				'dashicons-schedule',
				3
			);
		}

		public static function getTableContent( $environment = 'live' ) {
			$saved_settings = TamiAdminSettings::get_api_settings( false );
			$testSuffix     = '';//$environment === 'test' ? '<span class="tami-rounded-2 tami-p-1 tami-ms-1 tami-bg-tami-green">TEST</span>' : '';
			?>
            <table class="tami-table tami-table-striped tami-table-borderless">
                <tbody>
                <tr>
                    <th>
                        <label class="tami-text-tami tami-fw-normal"
                               for="form-ApiSettings-1<?php echo esc_attr( $environment ); ?>"><?php esc_attr_e( 'Security Method', 'tami-payment' ) ?><?php echo esc_attr( $testSuffix ); ?></label>
                    </th>
                    <td>
                        <select
                                class="tami-form-select"
                                name="payment_method"
                                autocomplete="off"
                                type="select"
                                id="form-ApiSettings-1<?php echo esc_attr( $environment ); ?>"
                        >
                            <option value="3D" <?php echo ( $saved_settings[ 'payment_method_' . $environment ] ?? '' ) === '3D' ? ' selected' : ''; ?>>
								<?php esc_attr_e( '3D Secure Payment', 'tami-payment' ); ?>
                            </option>
                            <option value="Nonsecure" <?php echo ( $saved_settings[ 'payment_method_' . $environment ] ?? '' ) === 'Nonsecure' ? ' selected' : ''; ?>>
								<?php esc_attr_e( 'Non-Secure Payment', 'tami-payment' ); ?>
                            </option>
                            <option value="Commonpayment" <?php echo ( $saved_settings[ 'payment_method_' . $environment ] ?? '' ) === 'Commonpayment' ? ' selected' : ''; ?>>
								<?php esc_attr_e( 'Hosted Payment Page', 'tami-payment' ); ?>
                            </option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th>
                        <label class="tami-text-tami tami-fw-normal"
                               for="form-ApiSettings-2<?php echo esc_attr( $environment ); ?>"><?php esc_attr_e( 'Merchant Id', 'tami-payment' ) ?><?php echo esc_attr( $testSuffix ); ?></label>
                    </th>
                    <td>
                        <input
                                class="tami-form-control"
                                type="tel"
                                name="merchant_id"
                                autocomplete="off"
                                id="form-ApiSettings-2<?php echo esc_attr( $environment ); ?>"
                                value="<?php echo esc_attr( $saved_settings[ 'merchant_id_' . $environment ] ); ?>"
                        />
                    </td>
                </tr>
                <tr>
                    <th>
                        <label class="tami-text-tami tami-fw-normal"
                               for="form-ApiSettings-3<?php echo esc_attr( $environment ); ?>"><?php esc_attr_e( 'Terminal Id', 'tami-payment' ) ?><?php echo esc_attr( $testSuffix ); ?></label>
                    </th>
                    <td>
                        <input
                                class="tami-form-control"
                                name="terminal_id"
                                type="tel"
                                autocomplete="off"
                                id="form-ApiSettings-3<?php echo esc_attr( $environment ); ?>"
                                value="<?php echo esc_attr( $saved_settings[ 'terminal_id_' . $environment ] ); ?>"
                        />
                    </td>
                </tr>
                <tr>
                    <th>
                        <label class="tami-text-tami tami-fw-normal"
                               for="form-ApiSettings-4<?php echo esc_attr( $environment ); ?>"><?php esc_attr_e( 'API Security Key', 'tami-payment' ) ?><?php echo esc_attr( $testSuffix ); ?></label>
                    </th>
                    <td>
                        <input
                                name="secret_key"
                                class="tami-form-control"
                                type="password"
                                autocomplete="off"
                                id="form-ApiSettings-4<?php echo esc_attr( $environment ); ?>"
                                value="<?php echo esc_attr( $saved_settings[ 'secret_key_' . $environment ] ); ?>"
                        />
                    </td>
                </tr>
                <tr>
                    <th>
                        <label class="tami-text-tami tami-fw-normal"
                               for="form-ApiSettings-7<?php echo esc_attr( $environment ); ?>"><?php esc_attr_e( 'Use API v3?', 'tami-payment' ) ?><?php echo esc_attr( $testSuffix ); ?></label>
                    </th>
                    <td>
                        <div class="tami-checkbox-custom tami-mt-2">
                        <input id="tami-v3-switch"
                               value="1"
                               type="checkbox"
                               name="use_v3"
                               class="tami-custom-switch tami-v3-switch"<?php echo ($saved_settings['use_v3_' . $environment] == '1' ) ? ' checked' : ''; ?>
                        />
                        </div>
                    </td>
                </tr>
                <tr style="visibility: collapse;">
                    <th>
                        <label class="tami-text-tami tami-fw-normal"
                               for="form-ApiSettings-5<?php echo esc_attr( $environment ); ?>"><?php esc_attr_e( 'KID Value', 'tami-payment' ) ?><?php echo esc_attr( $testSuffix ); ?></label>
                    </th>
                    <td>
                        <input
                                name="kid_value"
                                class="tami-form-control"
                                type="password"
                                autocomplete="off"
                                id="form-ApiSettings-5<?php echo esc_attr( $environment ); ?>"
                                value="<?php echo esc_attr( $saved_settings[ 'kid_value_' . $environment ] ); ?>"
                        />
                    </td>
                </tr>
                <tr style="visibility: collapse;">
                    <th>
                        <label class="tami-text-tami tami-fw-normal"
                               for="form-ApiSettings-6<?php echo esc_attr( $environment ); ?>"><?php esc_attr_e( 'K Value', 'tami-payment' ) ?><?php echo esc_attr( $testSuffix ); ?></label>
                    </th>
                    <td>
                        <input
                                name="k_value"
                                class="tami-form-control"
                                type="password"
                                autocomplete="off"
                                id="form-ApiSettings-6<?php echo esc_attr( $environment ); ?>"
                                value="<?php echo esc_attr( $saved_settings[ 'k_value_' . $environment ] ); ?>"
                        />
                    </td>
                </tr>
                </tbody>
            </table>
			<?php
		}
	}
}
new TamiAdmin();
