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

class Elex_FB_Save_Settings_Tab_Fields {

	public function __construct() {
		add_action( 'wp_ajax_elex_fpf_save_settings_tab_field', array( $this, 'elex_fpf_save_settings_tab_field_callback' ) );
		add_action( 'admin_action_elex_fb_disconnect_fb_action', array( $this, 'elex_fpf_disconnect_fb' ) );
	}

	public function elex_fpf_disconnect_fb() {
		check_admin_referer( 'elex_fb_disconnect_fb_action' );

		$fb_user_id      = get_option( 'elex_fb_user_id' );
		$fb_access_token = get_option( 'elex_fb_access_token' );

		$disconnect_url = 'https://graph.facebook.com/' . $fb_user_id . '/permissions?access_token=' . $fb_access_token;

		$response = wp_remote_request(
			$disconnect_url,
			array(
				'method' => 'DELETE',
			)
		);
		update_option( 'elex_fb_access_token', '' );
		update_option( 'elex_fb_user_id', '' );
		update_option( 'elex_fb_business_id', '' );
		update_option( 'elex_fb_catalog_id', '' );
		wp_safe_redirect( admin_url( 'admin.php?page=elex-facebook-feed-settings' ) );
		exit;
	}

	public function elex_fpf_save_settings_tab_field_callback() {
		check_ajax_referer( 'ajax-elex-fpf-nonce', '_ajax_elex_fpf_nonce' );
		$save_setting_tab_fields = array();
		// if ( isset( $_POST['custom_meta'] ) ) {
		//     $custom_meta = array_map( 'sanitize_text_field', wp_unslash( $_POST['custom_meta'] ) );
		//     foreach ( $custom_meta as $key => $value ) {
		//         if ( is_null( $value ) || '' == $value ) {
		//             unset( $custom_meta['custom_meta'][ $key ] );
		//         }
		//     }
		//     $save_setting_tab_fields['custom_meta'] = $custom_meta;
		// }
	

		if ( isset( $_POST['cat_language'] ) && '' != $_POST['cat_language'] ) {
			$save_setting_tab_fields['cat_language'] = sanitize_text_field( $_POST['cat_language'] );
		}
		if ( isset( $_POST['wpml_language'] ) && '' != $_POST['wpml_language'] ) {
			$save_setting_tab_fields['wpml_language'] = sanitize_text_field( $_POST['wpml_language'] );
		}
		update_option( 'elex_fpf_settings_tab_fields_data', $save_setting_tab_fields );
	}
}
new Elex_FB_Save_Settings_Tab_Fields();
