<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * GEO_Job_Manager class.
 */
class GJM_Init {

	/**
	 * The active theme.
	 *
	 * @var string
	 */
	public $active_theme = '';

	/**
	 * Constructor
	 */
	public function __construct() {

		// declare constants.
		define( 'GJM_ITEM_NAME', 'Jobs Geolocation' );
		define( 'GJM_TITLE', __( 'Jobs Geolocation', 'pointify' ) );
		define( 'GJM_LICENSE_NAME', 'geo_job_manager' );
		define( 'GJM_ITEM_ID', 5417 );
		define( 'GJM_VERSION', '2.3.2' );
		define( 'GJM_DB_VERSION', '1.2' );
		define( 'GJM_FILE', __FILE__ );
		define( 'GJM_URL', get_template_directory_uri() );
		define( 'GJM_PATH', get_template_directory_uri() );

		if ( ! defined( 'GMW_REMOTE_SITE_URL' ) ) {
			define( 'GMW_REMOTE_SITE_URL', 'https://geomywp.com' );
		}

		$this->active_theme = get_option( 'template' );

		// Verify WP Job Manager and it's version.
		if ( ! class_exists( 'WP_Job_Manager' ) || version_compare( JOB_MANAGER_VERSION, '1.23.1', '<' ) ) {
			add_action( 'admin_notices', array( $this, 'admin_notice' ) );
			return;
		}

		// init add-on.
		//add_action( 'plugins_loaded', array( $this, 'plugins_loaded' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'register_scripts' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'register_scripts' ) );
		add_filter( 'job_manager_geolocation_region_cctld', array( $this, 'append_region_code_to_geocoder' ), 20 );

		include get_template_directory() . '/inc/includes/gjm-functions.php';

		//if ( is_admin() && GOOGLE_MAPS_REMOVER !== true) {			
			include get_template_directory() . '/inc/includes/admin/class-gjm-admin.php';			
	//	}

		// include frontend files.
		//if ( GOOGLE_MAPS_REMOVER !== true && ( ! is_admin() || defined( 'DOING_AJAX' ) ) ) {
			include get_template_directory() . '/inc/includes/class-gjm-maps.php';
			include get_template_directory() . '/inc/includes/class-gjm-jobs-query.php';
	//	}
	}

	/**
	 * Include files for 3rd party plugins/extensions
	 */
	public function include_third_party_features() {

		// alerts.
		if ( class_exists( 'WP_Job_Manager_Alerts' ) ) {
			include get_template_directory() . '/inc/includes/3rd-party/alerts-geolocation/class-gjm-alerts-geolocation.php';
		}

		$themes = array( 'jobify', 'listify', 'listable', 'listingeasy', 'pointify' );

		// Jobify hero settings tab.
		// if ( in_array( $this->active_theme, $themes, true ) ) {

			include get_template_directory() . '/inc/includes/3rd-party/hero-geolocation/class-gjm-hero-geolocation.php';

			new GJM_Hero_Geolocation( $this->active_theme );
		// }
	}

	/**
	 * Plugins loaded hooks.
	 */
	public function plugins_loaded() {

		// include 3rd party integrations.
		$this->include_third_party_features();

		if ( is_admin() ) {

			// plugin updater.
			$this->updater();
		}
	}

	/**
	 * Admin notice if WP JOb Manager doesnt match.
	 *
	 * @return void
	 */
	public function admin_notice() {
		?>
		<div class="error">
			<p>
			<?php
			printf(
				// translators: %s for link to plugin.
				__( 'WP Job Manager Geolocation requires <a %s>WP Job Manager</a> plugin version 1.23.1 or higher.', 'pointify' ),
				'href="http://wordpress.org/plugins/wp-job-manager/" target=\"_blank\"'
			); // WPCS: XSS ok.
			?>
			</p>
		</div>
		<?php
	}

	/**
	 * Set region code for WPJM geocoder
	 *
	 * @param  string $region region code.
	 *
	 * @return string.
	 */
	public function append_region_code_to_geocoder( $region ) {

		if ( '' === $region ) {
			$gjm_options = get_option( 'gjm_options' );
			if (isset($gjm_options['general_settings']['gjm_region'])) {
				$new_region  = $gjm_options['general_settings']['gjm_region'];
			}
		}

		return ! empty( $new_region ) ? $new_region : $region;
	}

	/**
	 * Plugin updater and license key input field.
	 */
	public function updater() {

		// include updater files.
		// if ( ! class_exists( 'GMW_License' ) ) {
		// 	include 'updater/class-gmw-license.php';
		// }

		// Check for plugin updates.
		if ( class_exists( 'GMW_License' ) ) {
			new GMW_License(
				GJM_FILE,
				GJM_ITEM_NAME,
				GJM_LICENSE_NAME,
				GJM_VERSION,
				'Eyal Fitoussi',
				GMW_REMOTE_SITE_URL,
				GJM_ITEM_ID,
				array(
					'settings' => array(
						'label'    => 'Settings',
						'link'     => admin_url( 'edit.php?post_type=job_listing&page=job-manager-settings#settings-gjm_general_settings' ),
						'new_page' => false,
					),
					'docs'     => array(
						'label'    => 'Documentation',
						'link'     => 'https://docs.jobmanagergeolocation.com',
						'new_page' => true,
					),
				)
			);
		}
	}

	/**
	 * Temporary workaround to modify the maps API key that Listing Easy theme uses.
	 *
	 * By default it uses WP Job Manager's key which should be server key.
	 *
	 * @param  string $key the license key.
	 *
	 * @return [type]          [description]
	 */
	public function modify_listing_easy_google_api_key( $key ) {

		if ( ! empty( $_POST['job_manager_form'] ) && 'submit-job' === $_POST['job_manager_form'] ) { // WPCS: CSRF ok.
			return $key;
		}

		if ( ! empty( $_POST['resume_manager_form'] ) && 'submit-resume' === $_POST['resume_manager_form'] ) { // WPCS: CSRF ok.
			return $key;
		}

		if ( is_admin() && ! empty( $_POST['post_type'] ) && 'resume' === $_POST['post_type'] && ! empty( $_POST['resume_manager_nonce'] ) ) { // WPCS: CSRF ok.
			return $key;
		}

		if ( is_admin() && ! empty( $_POST['post_type'] ) && 'job_listing' === $_POST['post_type'] && ! empty( $_POST['job_manager_nonce'] ) ) { // WPCS: CSRF ok.
			return $key;
		}

		$gjm_api_key = get_option( 'gjm_google_api_key' );

		if ( ! empty( $gjm_api_key ) ) {
			$key = $gjm_api_key;
		}

		return $key;
	}

	/**
	 * Enqueue Google Maps API.
	 *
	 * @return [type] [description]
	 */
	public static function enqueue_google_maps_api() {

		if ( wp_script_is( 'gjm-google-maps', 'enqueued' ) || wp_script_is( 'google-maps', 'enqueued' ) ) {
			return;
		}

		$settings = get_option( 'gjm_options' );

		$language = ! empty( $settings['general_settings']['gjm_language'] ) ? $settings['general_settings']['gjm_language'] : 'en';
		$region   = ! empty( $settings['general_settings']['gjm_region'] ) ? $settings['general_settings']['gjm_region'] : 'us';
		$api_key  = ! empty( $settings['general_settings']['gjm_google_api_key'] ) ? $settings['general_settings']['gjm_google_api_key'] : '';

		$protocol   = is_ssl() ? 'https' : 'http';
		$google_url = $protocol . '://maps.googleapis.com/maps/api/js?';
		$google_url = apply_filters( 'gjm_google_maps_api_url', $google_url );

		$url_args = apply_filters(
			'gjm_google_maps_api_args',
			array(
				'key'       => $api_key,
				'libraries' => 'places',
				'region'    => $region,
				'language'  => $language,
			)
		);

		$google_url = add_query_arg( $url_args, $google_url );

		wp_enqueue_script( 'gjm-google-maps', $google_url, array( 'jquery' ), GJM_VERSION, true );
	}

	/**
	 * Register scripts function.
	 *
	 * @access public
	 * @return void
	 */
	public function register_scripts() {

		// check if WorkScout theme activeted. This is a work around to fix a conflict with WorkScout theme.
		if ( function_exists( 'workscout_setup' ) ) {

			$default_theme = false;
			$theme_name    = 'workscout';
			$reg_script    = 'workscout-wp-job-manager-ajax-filters';
			$reg_styles    = array( 'workscout-base', 'workscout-responsive', 'workscout-font-awesome' );

		} elseif ( function_exists( 'listable_setup' ) ) {

			$default_theme = false;
			$theme_name    = 'listable';
			$reg_script    = 'listable-scripts';
			$reg_styles    = array();

		} elseif ( function_exists( 'listify_setup' ) ) {

			$default_theme = false;
			$theme_name    = 'listify';
			$reg_script    = 'listify';
			$reg_styles    = array();

		} elseif ( function_exists( 'gt3_page_init' ) ) {

			$default_theme = false;
			$theme_name    = 'listingeasy';
			$reg_script    = 'gt3_theme_js';
			$reg_styles    = array( 'gt3_responsive' );

		} else {

			$default_theme = true;
			$theme_name    = 'other';
			$reg_script    = 'wp-job-manager-ajax-filters';
			$reg_styles    = array();
		}

		if ( class_exists( 'Jobify' ) ) {
			$default_theme = false;
		}

		if ( is_admin() ) {

			wp_register_script( 'gjm-autocomplete', GJM_URL . '/inc/includes/assets/js/gjm.autocomplete.min.js', array( 'jquery' ), GJM_VERSION, true );

		} else {
			wp_register_script( 'gjm-autocomplete', GJM_URL . '/inc/includes/assets/js/gjm.autocomplete.min.js', array( 'jquery', $reg_script ), GJM_VERSION, true );
			
			$localize_message = array(
				'geo_not_supported' => __('Sorry! Geolocation is not supported by this browser and we cannot locate you.', 'pointify'),
				'geocoder_failed' => __('Geocoder failed due to: ', 'pointify'),
				'user_denied_request' => __('User denied the request for Geolocation.', 'pointify'),
				'location_information' => __('Location information is unavailable.', 'pointify'),
				'user_location_timed' => __('The request to get user location timed out.', 'pointify'),
				'unknown_error' => __('An unknown error occurred', 'pointify'),
				'different_address_error_message' => __('We could not find the address you entered. Please try a different address. Error message: ', 'pointify'),
			);
			
			wp_register_script( 'gjm', GJM_URL . '/inc/includes/assets/js/gjm.js', array( 'jquery', $reg_script ), GJM_VERSION, true );
			
			wp_localize_script( 'gjm', 'localizeMsg', $localize_message );
			
			wp_enqueue_script(
				'gjm-map',
				GJM_URL . '/inc/includes/assets/js/gjm.map.js',
				array(
					'jquery',
					$reg_script,
				),
				GJM_VERSION,
				true
			);
			wp_enqueue_script( 'gjm-info-bubble', GJM_URL . '/inc/includes/assets/js/lib/info-bubble/info.bubble.min.js', array( 'jquery' ), GJM_VERSION, true );
			// wp_enqueue_style( 'gjm-frontend', GJM_URL . '/inc/includes/assets/css/gjm.frontend.min.css', $reg_styles, GJM_VERSION );
		}

		$settings = get_option( 'gjm_options' );

		// Google API settings.
		$language = ! empty( $settings['general_settings']['gjm_language'] ) ? $settings['general_settings']['gjm_language'] : 'en';
		$region   = ! empty( $settings['general_settings']['gjm_region'] ) ? $settings['general_settings']['gjm_region'] : 'us';

		$select2 = ( version_compare( JOB_MANAGER_VERSION, '1.32.0', '>=' ) ) ? true : false;

		wp_localize_script( 'gjm', 'wpjm_options', array( 'select2' => $select2 ) );		
	}
}

/**
 * Abort if older version of the plugin is installed.
 */
function gjm_old_verion_admin_notice() {
	?>
	<div class="error">
		<p><?php _e( 'An older version of WP Job Manager Geolocation ( GEO Job Manager ) is activated. Please deactivate GEO Job Manager plugin in order to use WP Job Manager Geolocation.', 'pointify' ); // WPCS: XSS ok. ?></p>
	</div>
	<?php
}

if ( class_exists( 'GEO_Job_Manager' ) ) {
	add_action( 'admin_notices', 'gjm_old_verion_admin_notice' );
	return;
}

// Get GJM Running.
new GJM_Init();
