<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


class Elex_FB_Settings_Tab_Fields {

	public function __construct() {
		$this->elex_fpf_load_script_and_styles();
		$this->elex_fpf_add_setting_fields();
	}

	public function elex_fpf_load_script_and_styles() {
		wp_nonce_field( 'ajax-elex-fpf-nonce', '_ajax_elex_fpf_nonce' );
		global $woocommerce;
		$woocommerce_version = function_exists( 'WC' ) ? WC()->version : $woocommerce->version;
		wp_enqueue_style( 'woocommerce_admin_styles', $woocommerce->plugin_url() . '/assets/css/admin.css', array(), $woocommerce_version );
		wp_register_style( 'elex-fpf-plugin-bootstrap', plugins_url( '/assets/css/bootstrap.css', dirname( __FILE__ ) ), array(), $woocommerce_version );
		wp_enqueue_style( 'elex-fpf-plugin-bootstrap' );
		wp_register_script( 'elex-fpf-tooltip-jquery', plugins_url( '/assets/js/tooltip.js', dirname( __FILE__ ) ), array(), $woocommerce_version );
		wp_enqueue_script( 'elex-fpf-tooltip-jquery' );
		wp_register_script( 'elex-fpf-settings-tab', plugins_url( '/assets/js/elex-settings-tab-script.js', dirname( __FILE__ ) ), array(), $woocommerce_version );
		wp_enqueue_script( 'elex-fpf-settings-tab' );
		wp_register_style( 'elex-setting-style', ELEX_FACEBOOK_FEED_MAIN_URL_PATH . '/assets/css/elex-setting-styles.css', array(), $woocommerce_version );
		wp_enqueue_style( 'elex-setting-style' );
	}

	public function elex_fpf_add_setting_fields() {
		$saved_data = get_option( 'elex_fpf_settings_tab_fields_data' );
		$meta_keys  = '';
		$upload_dir = wp_upload_dir();
		$base       = $upload_dir['basedir'];
		$path       = realpath( $base . '/elex-facebook-feed/' );
		if ( isset( $saved_data['custom_meta'] ) ) {
			$meta_keys = implode( ',', $saved_data['custom_meta'] );
		}
		$category_languages = array(
			'en' => __( 'English', 'elex-product-feed' ),
			'ru' => __( 'Russian', 'elex-product-feed' ),
			'es' => __( 'Spanish', 'elex-product-feed' ),
			'de' => __( 'German', 'elex-product-feed' ),
			'fr' => __( 'French', 'elex-product-feed' ),
			'cz' => __( 'Czech', 'elex-product-feed' ),
			'pl' => __( 'Polish', 'elex-product-feed' ),
			'nl' => __( 'Dutch', 'elex-product-feed' ),
			'se' => __( 'Swedish', 'elex-product-feed' ),
		);
		$wpml_languages     = array(
			''   => '-----',
			'en' => __( 'English', 'elex-product-feed' ),
			'ru' => __( 'Russian', 'elex-product-feed' ),
			'es' => __( 'Spanish', 'elex-product-feed' ),
			'de' => __( 'German', 'elex-product-feed' ),
			'fr' => __( 'French', 'elex-product-feed' ),
			'nl' => __( 'Dutch', 'elex-product-feed' ),
			'el' => __( 'Greek', 'elex-product-feed' ),
			'pl' => __( 'Polish', 'elex-product-feed' ),
			'it' => __( 'Italian', 'elex-product-feed' ),
			'cz' => __( 'Czech', 'elex-product-feed' ),
			'hu' => __( 'Hungarian', 'elex-product-feed' ),
			'sk' => __( 'Slovak', 'elex-product-feed' ),
			'se' => __( 'Swedish', 'elex-product-feed' ),
			'fi' => __( 'Finnish', 'elex-product-feed' ),
			'ro' => __( 'Romania', 'elex-product-feed' ),
		);
		$is_connected_to_fb = false;
		if ( get_option( 'elex_fb_access_token' ) ) {
			$is_connected_to_fb = true;
		}
		if (isset($_GET['error'])) {
			$response_error = sanitize_text_field($_GET['error']);
			echo "<script>alert('" . esc_js( $response_error ) . "');</script>";
			$is_connected_to_fb = false;
		} elseif ( isset( $_GET['fb_access_token'] ) && ! empty( $_GET['fb_access_token'] ) ) {
			update_option( 'elex_fb_access_token', sanitize_text_field( $_GET['fb_access_token'] ) );
			if ( isset( $_GET['fb_user_id'] ) ) {
				update_option( 'elex_fb_user_id', sanitize_text_field( $_GET['fb_user_id'] ) );
			}
			$fb_business_id = '';
			$fb_catalog_id  = '';
			if ( isset( $_GET['fb_business_id'] ) ) {
				$fb_business_id = sanitize_text_field( $_GET['fb_business_id'] );
			}
			if ( isset( $_GET['fb_catalog_id'] ) ) {
				$fb_catalog_id = sanitize_text_field( $_GET['fb_catalog_id'] );
				$fb_catalog_id = stripslashes( $fb_catalog_id );
				$fb_catalog_id = unserialize( $fb_catalog_id );
			}
			update_option( 'elex_fb_business_id', $fb_business_id );
			update_option( 'elex_fb_catalog_id', $fb_catalog_id );
			$is_connected_to_fb = true;
			wp_redirect( admin_url( 'admin.php?page=elex-facebook-feed-settings' ) );
		}
		?>
			<div class="elex-fpf-loader"></div>
			<div class="postbox elex-fpf-table-box elex-fpf-table-box-main ">
			<h1>
		<?php esc_html_e( 'Settings', 'elex-product-feed' ); ?>
			</h1>
			<table class="elex-fpf-settings-table">
				
				<tr>
					<td class="elex-fpf-settings-table-left">
		<?php esc_html_e( 'Google Product Category Language', 'elex-product-feed' ); ?>
					</td>
					<td class='elex-fpf-settings-table-middle'>
						<span class='woocommerce-help-tip tooltip' data-tooltip='<?php esc_html_e( 'Change the language used for google product category taxonomy. The default will be set as English regardless of any country chosen while creating the feed.', 'elex-product-feed' ); ?>'></span>
					</td>
					<td class="elex-fpf-settings-table-right">
						<select id="elex_google_cat_language_selector">
		<?php
								$selected_value = isset( $saved_data['cat_language'] ) ? $saved_data['cat_language'] : 'en';
		foreach ( $category_languages as $key => $value ) {
			if ( $key == $selected_value ) {
				?>
									<option value="<?php echo esc_attr( $key ); ?>" selected="true"><?php echo esc_attr( $value ); ?></option>
				<?php
			} else {
				?>
									<option value="<?php echo esc_attr( $key ); ?>"><?php echo esc_attr( $value ); ?></option>
				<?php
			}
		}
		?>
						</select>
					</td>
				</tr>
				<tr>
					<td class="elex-fpf-settings-table-left">
		 <?php esc_html_e( 'WPML Language', 'elex-product-feed' ); ?>
					</td>
					<td class='elex-fpf-settings-table-middle'>
						<span class='woocommerce-help-tip tooltip' data-tooltip='<?php esc_html_e( 'Select the language for the Product data to be included in the feed. Please note, WPML plugin must be activated and there should be a translation available for the selected language.', 'elex-product-feed' ); ?>'></span>
					</td>
					<td class="elex-fpf-settings-table-right">
						<select id="elex_google_wpml_language_selector">
		  <?php
			$selected_value = isset( $saved_data['wpml_language'] ) ? $saved_data['wpml_language'] : '';
			foreach ( $wpml_languages as $key => $value ) {
				if ( $key == $selected_value ) {
					?>
									<option value="<?php echo esc_attr( $key ); ?>" selected="true"><?php echo esc_attr( $value ); ?></option>
					   <?php
				} else {
					?>
									<option value="<?php echo esc_attr( $key ); ?>"><?php echo esc_attr( $value ); ?></option>
					<?php
				}
			}
			?>
						</select>
					</td>
				</tr>
				</table>
				<h3> <?php esc_html_e( 'Connect to Facebook', 'elex-product-feed' ); ?> <span style="margin-bottom: 1%;" class='woocommerce-help-tip tooltip' data-tooltip='<?php esc_html_e( 'Please click button to connect your store with Facebook.', 'elex-product-feed' ); ?>'></span> </h3>
		<?php
		if ( ! $is_connected_to_fb ) {
			$fb_connect_url = $this->elex_fpf_get_fb_connect_url();
			?>
						<a href="<?php echo esc_url( $fb_connect_url ); ?>" class="botton button-large button-primary"> <?php esc_html_e( 'Connect FB', 'elex-product-feed' ); ?> </a>
			<?php
		} else {
			$fb_disconnect_url = $this->elex_fpf_get_fb_disconnect_url();
			?>
					<table id="elex_fb_sync_details_table" >
						<tr>
							<td>
								Connected Account
							</td>
							<td>
							</td>
							<td>
								<a href="<?php echo esc_url( $fb_disconnect_url ); ?>" class="botton button-large button-primary elex-fb-disconnect-btn"> <?php esc_html_e( 'Disconnect FB', 'elex-product-feed' ); ?> </a>
							</td>
						</tr>
						<tr>
							<td class="elex-fpf-settings-table-left">
			<?php esc_html_e( 'fb_user_id', 'elex-product-feed' ); ?>
							</td>
							<td class='elex-fpf-settings-table-middle'>
								<span class='woocommerce-help-tip tooltip' data-tooltip='<?php esc_html_e( 'Facebook User ID.', 'elex-product-feed' ); ?>'></span>
							</td>
							<td class="elex-fpf-settings-table-right">
			<?php echo esc_html( get_option( 'elex_fb_user_id' ) ); ?>
							</td>
						</tr>
						<tr>
							<td class="elex-fpf-settings-table-left">
			<?php esc_html_e( 'fb_business_id', 'elex-product-feed' ); ?>
							</td>
							<td class='elex-fpf-settings-table-middle'>
								<span class='woocommerce-help-tip tooltip' data-tooltip='<?php esc_html_e( 'Facebook Business ID.', 'elex-product-feed' ); ?>'></span>
							</td>
							<td class="elex-fpf-settings-table-right">
			<?php echo esc_html( get_option( 'elex_fb_business_id' ) ); ?>
							</td>
						</tr>
						<tr>
							<td class="elex-fpf-settings-table-left">
			<?php esc_html_e( 'Catalogs', 'elex-product-feed' ); ?>
							</td>
							<td class='elex-fpf-settings-table-middle'>
								<span class='woocommerce-help-tip tooltip' data-tooltip='<?php esc_html_e( 'Catalogs associated with your Facebook account.', 'elex-product-feed' ); ?>'></span>
							</td>
							<td class="elex-fpf-settings-table-right">
			<?php
			$fb_catalogs   = get_option( 'elex_fb_catalog_id' );
			$catalog_links = '';
			if ( ! empty( $fb_catalogs ) ) {
				foreach ( $fb_catalogs as $key => $value ) {
					$catalog_links .= '<a target="_blank" href="https://facebook.com/products/catalogs/' . esc_attr( $key ) . ' ">' . esc_attr( $value ) . ' </a> | ';
				}
			} 
			$catalog_links = substr( $catalog_links, 0, -2 );
			echo wp_kses_post( $catalog_links );
			?>
							</td>
						</tr>
						</table>
						<!-- <h3> <?php esc_html_e( 'View logs', 'elex-product-feed' ); ?> <span style="margin-bottom: 1%;" class='woocommerce-help-tip tooltip' data-tooltip='<?php esc_html_e( 'View Logs.', 'elex-product-feed' ); ?>'></span> </h3>
						<select id="elex_fpf_log_files">
			<?php
			$upload_dir = wp_upload_dir();
			$base       = $upload_dir['basedir'];
			$path       = $base . '/elex-facebook-sync-logs/';
			$dir_url    = $upload_dir['baseurl'] . '/elex-facebook-sync-logs/';
			if ( is_dir( $path ) ) {
				$files = array_diff( scandir( $path ), array( '..', '.' ) );
				foreach ( $files as $key => $file ) {
					echo ( '<option value="' . esc_url( $dir_url ) . esc_html( $file ) . '">' . esc_html( $file ) . '</option>' );
				}
			}
			?>
						</select> <button onclick="elex_fpf_view_logfile_fun()" class="botton button-large button-primary" >view</button> -->
			<?php

		}

		?>
			<div style="margin-bottom: 4%;">
			<button class="botton button-large button-primary" id="elex_save_settings_tab_data" style="float: right; width: 10%;">Save</button>
			</div>
			</div>

		<?php
	}

	public function elex_fpf_get_fb_connect_url() {
		$fb_client_id     = '288432566165373';
		$oauth_url        = 'https://facebook.com/dialog/oauth';
		$redirect_uri     = 'https://facebookintegration.elextensions.com/';
		$scopes           = 'catalog_management,business_management';
		$extra_parameters = $this->elex_fpf_get_extra_paramenter();

		/**
		 * Filters the Facebook connect parameters before they are used to generate the connect URL.
		 *
		 * @param array $parameters {
		 *     An array of parameters for the Facebook connect URL.
		 *
		 *  @since 1.0.0
		 * 
		 *     @type string $client_id     The Facebook App client ID.
		 *     @type string $redirect_uri  The URI to redirect to after Facebook authentication.
		 *     @type string $state         The state parameter for the Facebook connect URL.
		 *     @type string $display       The display mode for the Facebook login page.
		 *     @type string $response_type The response type, typically 'code'.
		 *     @type string $scope         The permissions requested during Facebook login.
		 *     @type array  $extras        Additional parameters to include in the URL.
		 * }
		 */
		$fb_connect_url = apply_filters(
			'elex_fb_connect_parameters',
			array(
				'client_id'     => $fb_client_id,
				'redirect_uri'  => $redirect_uri,
				'state'         => admin_url( 'admin.php?page=elex-facebook-feed-settings' ),
				'display'       => 'page',
				'response_type' => 'code',
				'scope'         => $scopes,
				'extras'        => $extra_parameters,
			) 
		);
		return add_query_arg( rawurlencode_deep( $fb_connect_url ), $oauth_url );
	}

	public function elex_fpf_get_extra_paramenter() {
		$extra_parameters = array(
			'setup'           => array(
				'external_business_id' => uniqid( get_bloginfo( 'name' ) . '-', false ),
				'timezone'             => wc_timezone_string(),
				'currency'             => get_woocommerce_currency(),
				'business_vertical'    => 'ECOMMERCE',
			),
			'business_config' => array(
				'business' => array(
					'name' => get_bloginfo( 'name' ),
				),
			),
			'repeat'          => false,
		);
		return json_encode( $extra_parameters );
	}
	public function elex_fpf_get_fb_disconnect_url() {
		return wp_nonce_url( add_query_arg( 'action', 'elex_fb_disconnect_fb_action', admin_url( 'admin.php' ) ), 'elex_fb_disconnect_fb_action' );
	}
}

new Elex_FB_Settings_Tab_Fields();
