<?php
/**
 * The file that defines the core plugin class
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 *
 * @link       https://wbcomdesigns.com/
 * @since      1.0.0
 *
 * @package    Bp_Checkins
 * @subpackage Bp_Checkins/includes
 */

/**
 * The core plugin class.
 *
 * This is used to define internationalization, admin-specific hooks, and
 * public-facing site hooks.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.
 *
 * @since      1.0.0
 * @package    Bp_Checkins
 * @subpackage Bp_Checkins/includes
 * @author     Wbcom Designs <admin@wbcomdesigns.com>
 */
if ( ! class_exists( 'Bpchk_Checkins' ) ) :
	class Bpchk_Checkins {

		/**
		 * The loader that's responsible for maintaining and registering all hooks that power
		 * the plugin.
		 *
		 * @since    1.0.0
		 * @access   protected
		 * @var      Bp_Checkins_Loader    $loader    Maintains and registers all hooks for the plugin.
		 */
		protected $loader;

		/**
		 * The unique identifier of this plugin.
		 *
		 * @since    1.0.0
		 * @access   protected
		 * @var      string    $plugin_name    The string used to uniquely identify this plugin.
		 */
		protected $plugin_name;

		/**
		 * The current version of the plugin.
		 *
		 * @since    1.0.0
		 * @access   protected
		 * @var      string    $version    The current version of the plugin.
		 */
		protected $version;

		/**
		 * Define the core functionality of the plugin.
		 *
		 * Set the plugin name and the plugin version that can be used throughout the plugin.
		 * Load the dependencies, define the locale, and set the hooks for the admin area and
		 * the public-facing side of the site.
		 *
		 * @since    1.0.0
		 */
		public function __construct() {

			$this->plugin_name = 'bp-check-in';
			$this->version     = '1.0.0';

			$this->load_dependencies();
			$this->set_locale();
			$this->define_admin_hooks();
			$this->define_globals();
			$this->define_public_hooks();

		}

		/**
		 * Load the required dependencies for this plugin.
		 *
		 * Include the following files that make up the plugin:
		 *
		 * - Bp_Checkins_Loader. Orchestrates the hooks of the plugin.
		 * - Bp_Checkins_I18n. Defines internationalization functionality.
		 * - Bp_Checkins_Admin. Defines all hooks for the admin area.
		 * - Bp_Checkins_Public. Defines all hooks for the public side of the site.
		 *
		 * Create an instance of the loader which will be used to register the hooks
		 * with WordPress.
		 *
		 * @since    1.0.0
		 * @access   private
		 */
		private function load_dependencies() {

			/**
			 * The class responsible for orchestrating the actions and filters of the
			 * core plugin.
			 */
			require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-bp-checkins-loader.php';

			/**
			 * The class responsible for defining internationalization functionality
			 * of the plugin.
			 */
			require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-bp-checkins-i18n.php';

			/**
			 * The class responsible for defining all actions that occur in the admin area.
			 */
			require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-bp-checkins-admin.php';

			/**
			 * The class responsible for defining the global variable of the plugin.
			 */
			require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-bp-checkins-globals.php';

			/**
			 * The class responsible for defining all actions that occur in the public-facing
			 * side of the site.
			 */
			require_once plugin_dir_path( dirname( __FILE__ ) ) . 'public/class-bp-checkins-public.php';

			/* Enqueue wbcom plugin folder file. */
			require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/wbcom/wbcom-admin-settings.php';

			/* Enqueue Admin review file.  */
			require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-bp-checkins-admin-feedback.php';

			$this->loader = new Bpchk_Checkins_Loader();

		}

		/**
		 * Define the locale for this plugin for internationalization.
		 *
		 * Uses the Bp_Checkins_I18n class in order to set the domain and to register the hook
		 * with WordPress.
		 *
		 * @since    1.0.0
		 * @access   private
		 */
		private function set_locale() {

			$plugin_i18n = new Bpchk_Checkins_I18n();

			$this->loader->add_action( 'init', $plugin_i18n, 'load_plugin_textdomain' );

		}

		/**
		 * Register all of the hooks related to the admin area functionality
		 * of the plugin.
		 *
		 * @since    1.0.0
		 * @access   private
		 */
		private function define_admin_hooks() {

			$plugin_admin = new Bpchk_Checkins_Admin( $this->get_plugin_name(), $this->get_version() );

			$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' );
			$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' );
			$this->loader->add_action( bp_core_admin_hook(), $plugin_admin, 'bpchk_add_menu_page' );
			$this->loader->add_action( 'admin_init', $plugin_admin, 'bpchk_plugin_settings' );
			$this->loader->add_action( 'bp_setup_admin_bar', $plugin_admin, 'bpchk_setup_admin_bar_links', 80 );
			$this->loader->add_action( 'in_admin_header', $plugin_admin, 'bpchk_hide_all_admin_notices_from_setting_page' );

			// Ajax call for verifying the API Key.
			$this->loader->add_action( 'wp_ajax_bpchk_verify_apikey', $plugin_admin, 'bpchk_verify_apikey' );

			if ( class_exists( 'Youzer' ) ) {
				$this->loader->add_filter( 'yz_activity_post_types', $plugin_admin, 'bp_checkin_add_yozer_activity_setting' );

			}

		}

		/**
		 * Register all of the hooks related to the public-facing functionality
		 * of the plugin.
		 *
		 * @since    1.0.0
		 * @access   private
		 */
		private function define_public_hooks() {

			$plugin_public = new Bpchk_Checkins_Public( $this->get_plugin_name(), $this->get_version() );

			$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' );
			$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' );
			$this->loader->add_action( 'bp_setup_nav', $plugin_public, 'bpchk_member_profile_checkin_tab' );
			$this->loader->add_action( 'bp_activity_posted_update', $plugin_public, 'bpchk_update_meta_on_post_update', 10, 3 );
			$this->loader->add_action( 'bp_groups_posted_update', $plugin_public, 'bpchk_update_group_meta_on_post_update', 10, 4 );
			$this->loader->add_filter( 'bp_groups_format_activity_action_group_activity_update', $plugin_public, 'bpchk_groups_activity_new_update_action', 10, 1 );
			$this->loader->add_action( 'bp_activity_entry_content', $plugin_public, 'bpchk_show_google_map_in_checkin_activity', 10 );
			$this->loader->add_action( 'bp_activity_get_embed_excerpt', $plugin_public, 'bpchk_show_google_map_in_checkin_emded_activity', 10, 2 );



			/*version 1.0.1 update*/
			$this->loader->add_filter( 'bp_activity_check_activity_types', $plugin_public, 'bpchk_add_checkin_activity_type', 10, 1 );
			$this->loader->add_action( 'bp_init', $plugin_public, 'bpchk_add_location_xprofile_field' );
			$this->loader->add_action( 'wp_ajax_bpchk_save_xprofile_location', $plugin_public, 'bpchk_save_xprofile_location' );
			$this->loader->add_filter( 'bp_get_the_profile_field_value', $plugin_public, 'bpchk_show_xprofile_location', 10, 3 );
			$this->loader->add_action( 'bp_register_activity_actions', $plugin_public, 'custom_plugin_register_activity_actions' );
			$this->loader->add_action( 'bp_activity_before_save', $plugin_public, 'bpchk_update_activity_type_checkins', 10, 1 );
			/*version 1.0.7 update*/
			$this->loader->add_action( 'bp_activity_post_form_options', $plugin_public, 'render_location_pickup_html', 0 );
			$this->loader->add_action( 'bp_activity_post_form_options', $plugin_public, 'render_location_map_panle_html', 40 );

			// Conditionally remove and reassign actions if Youzify is active.
			add_action(
				'plugins_loaded',
				function () use ( $plugin_public ) {
					if ( class_exists( 'Youzify' ) ) {
						// Remove existing actions from the 'bp_activity_post_form_options' hook.
						remove_action( 'bp_activity_post_form_options', array( $plugin_public, 'render_location_pickup_html' ), 0 );
						remove_action( 'bp_activity_post_form_options', array( $plugin_public, 'render_location_map_panle_html' ), 40 );

						// Add actions to new hooks as per requirements.
						add_action( 'bp_activity_post_form_tools', array( $plugin_public, 'render_location_pickup_html' ), 0 );
						add_action( 'bp_activity_post_form_after_actions', array( $plugin_public, 'render_location_map_panle_html' ), 40 );
					}
				},
				20
			);

			/* Filter to delete check-in location */
			$this->loader->add_action( 'wp_ajax_bpchk_delete_user_checkin_location', $plugin_public, 'bpchk_delete_user_checkin_location' );
			$this->loader->add_action( 'wp_ajax_nopriv_bpchk_delete_user_checkin_location', $plugin_public, 'bpchk_delete_user_checkin_location' );

			/* Action to embed map on clicking read more in activity content. */
			$this->loader->add_action( 'wp_ajax_bpchk_checkin_activity_read_more', $plugin_public, 'bpchk_checkin_activity_read_more' );
			$this->loader->add_action( 'wp_ajax_nopriv_bpchk_checkin_activity_read_more', $plugin_public, 'bpchk_checkin_activity_read_more' );

			if ( class_exists( 'Youzer' ) ) {
				$this->loader->add_filter( 'yz_allowed_form_post_types', $plugin_public, 'bp_checkin_allow_youzer_activity' );
			}

			$this->loader->add_filter( 'bp_after_has_profile_parse_args', $plugin_public, 'bp_checkin_hide_profile_field' );

			/* Embed activity */
			$this->loader->add_action( 'embed_head', $plugin_public, 'bp_checkin_activity_embed_add_inline_styles', 20 );
			
			add_filter( 'bp_editable_types_activity', function( $args){ $args[] = 'activity_bpchk_chkins'; return $args;} );
			$this->loader->add_filter( 'buddypress_get_edit_activity_content', $plugin_public, 'bp_checkin_get_edit_activity_content', 10, 2 );
			$this->loader->add_action( 'bp_get_addition_activity_content', $plugin_public, 'bp_checkin_get_chkins_activity_content' );
		}

		/**
		 * Registers a global variable of the plugin - bp-checkins
		 *
		 * @since    1.0.0
		 * @access   public
		 */
		public function define_globals() {
			global $bpchk_globals;
			$bpchk_globals = new Bpchk_Checkins_Globals( $this->get_plugin_name(), $this->get_version() );
		}

		/**
		 * Run the loader to execute all of the hooks with WordPress.
		 *
		 * @since    1.0.0
		 */
		public function run() {
			$this->loader->run();
		}

		/**
		 * The name of the plugin used to uniquely identify it within the context of
		 * WordPress and to define internationalization functionality.
		 *
		 * @since     1.0.0
		 * @return    string    The name of the plugin.
		 */
		public function get_plugin_name() {
			return $this->plugin_name;
		}

		/**
		 * The reference to the class that orchestrates the hooks with the plugin.
		 *
		 * @since     1.0.0
		 * @return    Bp_Checkins_Loader    Orchestrates the hooks of the plugin.
		 */
		public function get_loader() {
			return $this->loader;
		}

		/**
		 * Retrieve the version number of the plugin.
		 *
		 * @since     1.0.0
		 * @return    string    The version number of the plugin.
		 */
		public function get_version() {
			return $this->version;
		}

		/**
		 * Function to fetch google places.
		 *
		 * @since     1.0.0
		 * @param     string $apikey     Api key.
		 * @param     string $lat        Latitude.
		 * @param     string $lon        Longitude.
		 * @param     string $radius     Radius.
		 * @return    array  $response   Response array.
		 */
		public static function bpchk_fetch_google_places( $apikey, $lat = '', $lon = '', $radius = '' ) {
			$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json';
			$parameters = array(
				'location' => "$lat,$lon",
				'radius'   => $radius,
				'key'      => $apikey,
			);
			$url        = add_query_arg( $parameters, esc_url_raw( $places_url ) );
			$response   = wp_remote_get( esc_url_raw( $url ) );
			return $response;
		}


		/** Function to check the Google Maps API key 
		 * @param $api_key
		 * @return $api_response
		 * 
		 * @since 2.3.1 
		 * 
		*/
		public static function bpchk_check_google_maps_api_key($api_key) {
			// Google Maps API endpoints to test
			$endpoints = [
				'Geocoding API' => 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=' . $api_key,
				'Places API' => 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+Los+Angeles&key=' . $api_key,
				'Distance Matrix API' => 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=San+Francisco&destinations=Los+Angeles&key=' . $api_key,
				'Directions API' => 'https://maps.googleapis.com/maps/api/directions/json?origin=San+Francisco&destination=Los+Angeles&key=' . $api_key,
			];
			$error_response = [];
			
			// Iterate through the endpoints and make API requests
			foreach ($endpoints as $api_name => $url) {
				$response = wp_remote_get($url); // Use WordPress's HTTP API to make the request				
				$response_code = wp_remote_retrieve_response_code( $response );
				$response_body = wp_remote_retrieve_body($response);
				$response_data = json_decode( $response_body, true );
				// Check for errors in the request
				if ( is_wp_error($response) ) {
					$error_message = $response->get_error_message();
					$error_response[$api_name] =  $error_message;
				} elseif ( 403 === $response_code && strpos( $response_body, 'PROJECT_BILLING_DISABLED' ) !== false ) {
					$error_response['billing'] =  'Map API key verification failed. Billing is not enabled for the associated Google Cloud project. Please enable billing and retry.';
				} else {
					// For REST-based APIs, check the 'status' field
					// Check the API response status
					if ( ! isset($response_data['status']) || $response_data['status'] !== 'OK') {
						$error_response[$api_name]['error'] =  (isset($response_data['error_message']) ? $response_data['error_message'] : 'Unknown error');
					}else{
						$error_response[$api_name]['success'] =  'This API is ready to use.';
					} 
				}
			}
			return $error_response;
		}

	}
endif;
