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

namespace Tami\WooCommerce;

use Exception;
use Tami_WooCommerce_GW;
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
if(!class_exists('\Tami\WooCommerce\TamiAdminSettings')) {
	class TamiAdminSettings {

		const TAMI_SETTINGS_PREFIX = "woocommerce_tami_";

		public function __construct() {
			add_action( 'admin_init', array( $this, 'init_settings' ) );
		}

		public static function get_setting_name( $name ): string {
			return self::TAMI_SETTINGS_PREFIX . $name;
		}

		public static function save_settings( $setting_name = '', $values = [], $returnType='json' ) {
			if ( ! $setting_name || is_null( $values ) || ( is_array( $values ) && ! $values ) ) {
				if($returnType === 'json')
					Response::json_output( [ 'status' => true, 'message' => 'Missing parameters!' ] );
				else
					return false;
			}
			update_option( self::get_setting_name( $setting_name ), $values );

			if($returnType === 'json')
				Response::json_output( [ 'status' => true ] );
		}

		public function dismiss_application_banner() {
			$this->save_settings( 'dismiss_application_banner', '1' );
		}

		public function dismiss_application_banner_undo() {
			$this->save_settings( 'dismiss_application_banner', '0' );
		}


		public function check_credentials() {
			$tami_gw = new Tami_WooCommerce_GW();
			$tami    = $tami_gw->payment_object();
			try {
				$tami->check_api_connection();
				$result = [
					'status'  => true,
					'message' => ''
				];
			} catch ( Exception $exception ) {
				$result = [
					'status'  => false,
					'message' => $exception->getMessage()
				];
			}
			Response::json_output(
				apply_filters( 'tami_woocommerce_installment_query_response',
					$result )
			);
		}

		public function save_api_settings() {
			// stop unsigned actions
			$environment = isset( $_POST['environment'] ) ? sanitize_text_field( wp_unslash( $_POST['environment'] ) ?? 'live' ) : 'test';
			if ( ! in_array( $environment, [ 'live', 'test' ] ) ) {
				exit;
			}
			if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'tami_save_api_settings_' . $environment ) ) {
				exit;
			}

			$fields = [
				'merchant_id',
				'terminal_id',
				'secret_key',
				'payment_method',
				'use_v3',
				'kid_value',
				'k_value'
			];
			$data   = self::get_settings( 'api_settings' );
			foreach ( $fields as $field ) {
				$data[ $field . '_' . $environment ] = isset( $_POST[ $field ] ) ? sanitize_text_field( wp_unslash( $_POST[ $field ] ) ?? '' ) : '';
			}

			$data['environment'] = $environment;
			$api_settings        = apply_filters( 'tami_woocommerce_api_settings_array', $data );
			$this->save_settings( 'api_settings', $api_settings );
		}

		public function save_installment_settings() {
			// stop unsigned actions
			if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'tami_save_installment_settings' ) ) {
				exit;
			}

			$api_settings = apply_filters( 'tami_woocommerce_installment_settings_array', [
				'installments_enabled'       => isset( $_POST['installments_enabled'] ) ? sanitize_text_field( wp_unslash( $_POST['installments_enabled'] ) ?? '' ) : '',
				'minimum_installment_amount' => isset( $_POST['minimum_installment_amount'] ) ? sanitize_text_field( wp_unslash( $_POST['minimum_installment_amount'] ) ?? '' ) : '',
				'installment_2'              => isset( $_POST['installment_2'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_2'] ) ?? '-1' ) : '',
				'installment_3'              => isset( $_POST['installment_3'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_3'] ) ?? '-1' ) : '',
				'installment_4'              => isset( $_POST['installment_4'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_4'] ) ?? '-1' ) : '',
				'installment_5'              => isset( $_POST['installment_5'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_5'] ) ?? '-1' ) : '',
				'installment_6'              => isset( $_POST['installment_6'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_6'] ) ?? '-1' ) : '',
				'installment_7'              => isset( $_POST['installment_7'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_7'] ) ?? '-1' ) : '',
				'installment_8'              => isset( $_POST['installment_8'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_8'] ) ?? '-1' ) : '',
				'installment_9'              => isset( $_POST['installment_9'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_9'] ) ?? '-1' ) : '',
				'installment_10'             => isset( $_POST['installment_10'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_10'] ) ?? '-1' ) : '',
				'installment_11'             => isset( $_POST['installment_11'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_11'] ) ?? '-1' ) : '',
				'installment_12'             => isset( $_POST['installment_12'] ) ? sanitize_text_field( wp_unslash( $_POST['installment_12'] ) ?? '-1' ) : ''
			] );

			$this->save_settings( 'installment_settings', $api_settings );

		}

		public function save_module_settings() {
			// stop unsigned actions
			if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'tami_save_module_settings' ) ) {
				exit;
			}

			$api_settings = apply_filters( 'tami_woocommerce_module_settings_array', [
				'enabled'                  => isset( $_POST['enabled'] ) ? sanitize_text_field( wp_unslash( $_POST['enabled'] ) ?? 'no' ) : 'no',
				'title'                    => isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ?? '' ) : '',
				//'description' => sanitize_text_field($_POST['description'] ?? ''),
				'order_status'             => isset( $_POST['order_status'] ) ? sanitize_text_field( wp_unslash( $_POST['order_status'] ) ?? '' ) : '',
				'debug_mode'               => isset( $_POST['debug_mode'] ) ? sanitize_text_field( wp_unslash( $_POST['debug_mode'] ) ?? '' ) : '',
				'save_failed_transactions' => isset( $_POST['save_failed_transactions'] ) ? sanitize_text_field( wp_unslash( $_POST['save_failed_transactions'] ) ?? '' ) : '',
			] );

			$this->save_settings( 'woocommerce_settings', $api_settings );
		}

		public static function get_settings( $settings_name, $default_settings = [] ) {
			$saved_settings = get_option( self::get_setting_name( $settings_name ), $default_settings );
			// fill empty values with default
			if ( is_array( $default_settings ) ) {
				foreach ( $default_settings as $default_setting_key => $default_setting_val ) {
					if ( ! isset( $saved_settings[ $default_setting_key ] ) ) {
						$saved_settings[ $default_setting_key ] = $default_setting_val;
					}
				}
			}

			return apply_filters( 'tami_woocommerce_get_settings', $saved_settings );
		}

		public static function get_installment_settings() {
			$default_settings = [
				'installment_2'        => '-1',
				'installment_3'        => '-1',
				'installment_4'        => '-1',
				'installment_5'        => '-1',
				'installment_6'        => '-1',
				'installment_7'        => '-1',
				'installment_8'        => '-1',
				'installment_9'        => '-1',
				'installment_10'       => '-1',
				'installment_11'       => '-1',
				'installment_12'       => '-1',
				'installments_enabled' => ''
			];

			return self::get_settings( 'installment_settings', $default_settings );
		}

		public static function get_api_settings( $apiReturn = false ) {
			$default_settings = [
				'merchant_id_live'     => '',
				'terminal_id_live'     => '',
				'secret_key_live'      => '',
				'payment_method_live'  => '3D',
				'use_v3_live' => '',
				'kid_value_live' => '',
				'k_value_live'   => '',
				'merchant_id_test'     => '',
				'terminal_id_test'     => '',
				'secret_key_test'      => '',
				'payment_method_test'  => '3D',
				'kid_value_test' => '',
				'k_value_test'   => '',
				'use_v3_test' => '',
				'environment'          => 'live'
			];
			$data             = self::get_settings( 'api_settings', $default_settings );
			$wcSettings       = self::get_settings( 'woocommerce_settings', [
				'enabled' => 'no'
			] );
			$moduleEnabled    = isset( $wcSettings['enabled'] ) && $wcSettings['enabled'] === 'yes';


			if ( $apiReturn ) {
				$dataReturn   = [];
				$returnFields = [
//            'environment',
					'payment_method',
					'terminal_id',
					'merchant_id',
					'secret_key',
					'kid_value',
					'k_value',
					'use_v3'
				];

				if ( ! isset( $data['environment'] ) || ! in_array( $data['environment'], [ 'test', 'live' ] ) ) {
					$dataReturn['environment'] = 'test';
				} else {
					$dataReturn['environment'] = $data['environment'];
				}

				foreach ( $returnFields as $item ) {
					$dataReturn[ $item ] = $data[ $item . '_' . $data['environment'] ] ?? '';
				}

				$dataReturn['enabled'] = $moduleEnabled;

				return $dataReturn;
			} else {
				$data['enabled'] = $moduleEnabled;

				return $data;
			}
		}

		public static function get_module_settings( $specify = '', $default = '' ) {
			$default_settings = [
				'title'                    => __( 'Credit/Debit Card Payment', 'tami-payment' ),
				// 'description' => __('Make online payment with your credit or debit card.', 'tami-payment'),
				'order_status'             => 'wc-processing',
				'debug_mode'               => false,
				'save_failed_transactions' => false
			];

			$settings = self::get_settings( 'woocommerce_settings', $default_settings );
			if ( ! $specify ) {
				return $settings;
			}
			if ( ! isset( $settings[ $specify ] ) ) {
				return $default;
			}

			return $settings[ $specify ];
		}

		public function init_settings() {
			add_action( 'wp_ajax_tami_installment_settings_save', array( $this, 'save_installment_settings' ) );
			add_action( 'wp_ajax_tami_api_settings_save', array( $this, 'save_api_settings' ) );
			add_action( 'wp_ajax_tami_api_check_credentials', array( $this, 'check_credentials' ) );
			add_action( 'wp_ajax_tami_module_settings_save', array( $this, 'save_module_settings' ) );
			add_action( 'wp_ajax_tami_dismiss_application', array( $this, 'dismiss_application_banner' ) );
			add_action( 'wp_ajax_tami_dismiss_application_undo', array( $this, 'dismiss_application_banner_undo' ) );
		}
	}
}