<?php
/**
 * The file that defines the core plugin class
 *
 * @since      1.0.0
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 */

use Elementor\Controls_Manager;
use Elementor\Widget_Base;
use Elementor\Plugin;

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

/*
 * Cross Domain Copy Paste captain-widgets-kit.
 */
if ( ! class_exists( 'Captwiki_Location' ) ) {

	/**
	 * Define Captwiki_Custom_Css class
	 *
	 * @since 1.0.0
	 */
	class Captwiki_Location {

		/**
		 * A reference to an instance of this class.
		 *
		 * @since 1.0.0
		 * @var   object
		 */
		private static $instance = null;

		/**
		 * Geo Location API Types.
		 *
		 * @since 1.0.0
		 * @var   array
		 */
		public $geo_location_types;

		/**
		 * Temporary location cache.
		 *
		 * @since 1.0.0
		 * @var   array
		 */
		private $tmp_location = null;

		/**
		 * Returns a singleton instance of the class.
		 *
		 * This method ensures that only one instance of the class is created (singleton pattern).
		 * If an instance doesn't exist, it creates one using the provided shortcodes.
		 *
		 * @since 1.0.0
		 *
		 * @param array $shortcodes Optional. An array of shortcodes to initialize the instance with.
		 * @return self The single instance of the class.
		 */
		public static function get_instance( $shortcodes = array() ) {
			if ( null === self::$instance ) {
				self::$instance = new self( $shortcodes );
			}

			return self::$instance;
		}

		/**
		 * Initialize integration hooks for custom CSS functionality.
		 *
		 * Sets up various action hooks to integrate custom CSS features with Elementor:
		 * - Adds custom CSS to post stylesheet
		 * - Enqueues custom CSS editor script
		 * - Registers custom controls for sections, columns, widgets, and containers
		 *
		 * @since 6.2.5
		 * @return void
		 */
		public function __construct() {

			add_action( 'elementor/element/common/_section_style/after_section_end', array( $this, 'captwiki_register_controls' ), 10, 2 );
			add_action( 'elementor/element/column/section_advanced/after_section_end', array( $this, 'captwiki_register_controls' ), 10, 2 );
			add_action( 'elementor/element/section/section_advanced/after_section_end', array( $this, 'captwiki_register_controls' ), 10, 2 );

			if ( \Elementor\Plugin::$instance->experiments->is_feature_active( 'container' ) ) {
				add_action( 'elementor/element/container/section_layout/after_section_end', array( $this, 'captwiki_register_controls' ), 10, 2 );
			}

			add_filter( 'elementor/frontend/widget/should_render', array( $this, 'captwiki_content_render' ), 10, 2 );
			add_filter( 'elementor/frontend/column/should_render', array( $this, 'captwiki_content_render' ), 10, 2 );
			add_filter( 'elementor/frontend/section/should_render', array( $this, 'captwiki_content_render' ), 10, 2 );
			add_filter( 'elementor/frontend/container/should_render', array( $this, 'captwiki_content_render' ), 10, 2 );
		}

		/**
		 * Register the controls for the widget.
		 *
		 * @since 1.0.0
		 *
		 * @Ref https://www.geoplugin.com/
		 * https://www.geoplugin.com/webservices/php
		 * https://www.geoplugin.com/iso3166
		 *
		 * @param Element_Base $element The element being registered.
		 * @return void
		 */
		public function captwiki_register_controls( $element ) {

			$element->start_controls_section(
				'captwiki_geo_location_section',
				array(
					'label' => esc_html__( 'Location', 'captain-widgets-kit' ),
					'tab'   => Controls_Manager::TAB_ADVANCED,
				)
			);

			$element->add_control(
				'captwiki_location_switch',
				array(
					'label'   => esc_html__( 'Geo Location', 'captain-widgets-kit' ),
					'type'    => Controls_Manager::SWITCHER,
					'default' => '',
				)
			);

			$element->add_control(
				'captwiki_apitype',
				array(
					'type'        => Controls_Manager::SELECT,
					'label_block' => true,
					'multiple'    => false,
					'options'     => $this->get_geo_location_types(),
					'default'     => 'ip-api',
					'condition'   => array(
						'captwiki_location_switch' => 'yes',
					),
				)
			);

			$element->add_control(
				'captwiki_geo_location_value',
				array(
					'type'        => Controls_Manager::SELECT2,
					'label_block' => true,
					'multiple'    => true,
					'options'     => $this->get_location_list(),
					'condition'   => array(
						'captwiki_location_switch' => 'yes',
					),
				)
			);

			$element->add_control(
				'captwiki_geo_location_logic',
				array(
					'label'      => esc_html__( 'Logic Operator', 'captain-widgets-kit' ),
					'show_label' => false,
					'type'       => Controls_Manager::CHOOSE,
					'options'    => array(
						'include' => array(
							'title' => esc_html__( 'Include', 'captain-widgets-kit' ),
							'icon'  => 'captwiki-i-right',
						),
						'exclude' => array(
							'title' => esc_html__( 'Exclude', 'captain-widgets-kit' ),
							'icon'  => 'captwiki-i-close',
						),
					),
					'default'    => 'include',
					'toggle'     => false,
					'condition'  => array(
						'captwiki_location_switch' => 'yes',
					),
				)
			);

			$element->add_control(
				'captwiki_geo_location_Note',
				array(
					'type'            => \Elementor\Controls_Manager::RAW_HTML,
					'raw'             => '<b>Note:</b> Conditional Display will take effect only on preview or live page, and not while editing in Elementor.',
					'content_classes' => 'captwiki-controller-notice',
					'condition'       => array(
						'captwiki_location_switch' => 'yes',
					),
				)
			);

			$element->end_controls_section();
		}

		/**
		 * Render the content of the widget.
		 *
		 * @param bool         $should_render Whether the content should be rendered.
		 * @param Element_Base $element The element being rendered.
		 * @return bool The updated should_render value.
		 */
		public function captwiki_content_render( $should_render, $element ) {

			if ( ! $should_render ) {
				return false;
			}

			$settings = $element->get_settings();

			$location_switch = isset( $settings['captwiki_location_switch'] ) ? $settings['captwiki_location_switch'] : '';

			if ( 'yes' !== $location_switch ) {
				return $should_render;
			}

			$location_logic   = isset( $settings['captwiki_geo_location_logic'] ) ? $settings['captwiki_geo_location_logic'] : 'include';
			$location_apitype = isset( $settings['captwiki_apitype'] ) ? $settings['captwiki_apitype'] : 'ip-api';
			$location_values  = isset( $settings['captwiki_geo_location_value'] ) ? $settings['captwiki_geo_location_value'] : array();

			if ( empty( $location_values ) ) {
				return $should_render;
			}

			$ip = '';
			if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
				$ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CLIENT_IP'] ) );
			} elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) {
				$ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
			}

			if ( empty( $ip ) || ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
				return false;
			}

			if ( ! empty( $this->tmp_location ) ) {
				if ( 'success' !== $this->tmp_location['status'] ) {
					return false;
				}

				$country_name = strtolower( $this->tmp_location['country'] );

				$is_location_match = in_array( $country_name, array_map( 'strtolower', $location_values ), true );

				if ( 'include' === $location_logic ) {
					return $is_location_match ? $should_render : false;
				} else {
					return $is_location_match ? false : $should_render;
				}
			}

			$url = '';
			if ( 'geoplugin' === $location_apitype ) {
				$url = "http://www.geoplugin.net/php.gp?ip=$ip";
			} elseif ( 'ip-api' === $location_apitype ) {
				$url = "http://ip-api.com/php/$ip";
			} elseif ( 'findip' === $location_apitype ) {
				$url = "https://api.findip.net/$ip/?token=5eab1b6ea0574b08bae0a1252e738c89";
			}

			$args = array(
				'timeout' => 60,
				'body'    => null,
				'headers' => array(
					'Accept' => 'application/json',
				),
			);

			$response = wp_remote_get( $url, $args );

			if ( is_wp_error( $response ) ) {
				return $should_render;
			}

			$response_code = wp_remote_retrieve_response_code( $response );
			if ( 200 !== $response_code ) {
				return $should_render;
			}

			$data1 = wp_remote_retrieve_body( $response );

			if ( empty( $data1 ) ) {
				return $should_render;
			}

			$country_name = '';

			if ( 'geoplugin' === $location_apitype ) {
				$data               = maybe_unserialize( $data1 );
				$this->tmp_location = $data;
				if ( ! is_array( $data ) ) {
					return $should_render;
				}
				$country_name       = ! empty( $data['geoplugin_countryName'] ) ? strtolower( $data['geoplugin_countryName'] ) : '';
			} elseif ( 'findip' === $location_apitype ) {
				$data               = json_decode( $data1, true );
				$this->tmp_location = $data;
				$country_name       = ! empty( $data['country']['names']['en'] ) ? strtolower( $data['country']['names']['en'] ) : '';
			} else {
				$data               = maybe_unserialize( $data1 );
				$this->tmp_location = $data;
				if ( ! is_array( $data ) ) {
					return $should_render;
				}

				if ( 'success' !== $data['status'] ) {
					return $should_render;
				}

				$country_name = ! empty( $data['country'] ) ? strtolower( $data['country'] ) : '';
			}

			$is_location_match = in_array( $country_name, array_map( 'strtolower', $location_values ), true );

			if ( 'include' === $location_logic ) {
				return $is_location_match ? $should_render : false;
			} else {
				return $is_location_match ? false : $should_render;
			}
		}

		/**
		 * Get geo location types.
		 *
		 * @since 1.0.0
		 * @return array
		 */
		public function get_geo_location_types() {
			return array(
				'geoplugin' => esc_html__( 'Geoplugin', 'captain-widgets-kit' ),
				'ip-api'    => esc_html__( 'IP API', 'captain-widgets-kit' ),
				'findip'    => esc_html__( 'Find IP', 'captain-widgets-kit' ),
			);
		}

		/**
		 * Get location list.
		 *
		 * @since 1.0.0
		 * @return array
		 */
		public function get_location_list() {

			return array(
				'Andorra',
				'United Arab Emirates',
				'Afghanistan',
				'Antigua and Barbuda',
				'Anguilla',
				'Albania',
				'Armenia',
				'Netherlands Antilles',
				'Angola',
				'Asia/Pacific Region',
				'Antarctica',
				'Argentina',
				'American Samoa',
				'Austria',
				'Australia',
				'Aruba',
				'Aland Islands',
				'Azerbaijan',
				'Bosnia and Herzegovina',
				'Barbados',
				'Bangladesh',
				'Belgium',
				'Burkina Faso',
				'Bulgaria',
				'Bahrain',
				'Burundi',
				'Benin',
				'Bermuda',
				'Brunei Darussalam',
				'Bolivia',
				'Brazil',
				'Bahamas',
				'Bhutan',
				'Bouvet Island',
				'Botswana',
				'Belarus',
				'Belize',
				'Canada',
				'Cocos (Keeling) Islands',
				'Congo, The Democratic Republic of the',
				'Central African Republic',
				'Congo',
				'Switzerland',
				"Cote d'Ivoire",
				'Cook Islands',
				'Chile',
				'Cameroon',
				'China',
				'Colombia',
				'Costa Rica',
				'Cuba',
				'Cape Verde',
				'Christmas Island',
				'Cyprus',
				'Czech Republic',
				'Germany',
				'Djibouti',
				'Denmark',
				'Dominica',
				'Dominican Republic',
				'Algeria',
				'Ecuador',
				'Estonia',
				'Egypt',
				'Western Sahara',
				'Eritrea',
				'Spain',
				'Ethiopia',
				'Europe',
				'Finland',
				'Fiji',
				'Falkland Islands (Malvinas)',
				'Micronesia, Federated States of',
				'Faroe Islands',
				'France',
				'Gabon',
				'United Kingdom',
				'Grenada',
				'Georgia',
				'French Guiana',
				'Guernsey',
				'Ghana',
				'Gibraltar',
				'Greenland',
				'Gambia',
				'Guinea',
				'Guadeloupe',
				'Equatorial Guinea',
				'Greece',
				'South Georgia and the South Sandwich Islands',
				'Guatemala',
				'Guam',
				'Guinea-Bissau',
				'Guyana',
				'Hong Kong',
				'Heard Island and McDonald Islands',
				'Honduras',
				'Croatia',
				'Haiti',
				'Hungary',
				'Indonesia',
				'Ireland',
				'Israel',
				'Isle of Man',
				'India',
				'British Indian Ocean Territory',
				'Iraq',
				'Iran, Islamic Republic of',
				'Iceland',
				'Italy',
				'Jersey',
				'Jamaica',
				'Jordan',
				'Japan',
				'Kenya',
				'Kyrgyzstan',
				'Cambodia',
				'Kiribati',
				'Comoros',
				'Saint Kitts and Nevis',
				"Korea, Democratic People's Republic of",
				'Korea, Republic of',
				'Kuwait',
				'Cayman Islands',
				'Kazakhstan',
				"Lao People's Democratic Republic",
				'Lebanon',
				'Saint Lucia',
				'Liechtenstein',
				'Sri Lanka',
				'Liberia',
				'Lesotho',
				'Lithuania',
				'Luxembourg',
				'Latvia',
				'Libyan Arab Jamahiriya',
				'Morocco',
				'Monaco',
				'Moldova, Republic of',
				'Montenegro',
				'Madagascar',
				'Marshall Islands',
				'Macedonia',
				'Mali',
				'Myanmar',
				'Mongolia',
				'Macao',
				'Northern Mariana Islands',
				'Martinique',
				'Mauritania',
				'Montserrat',
				'Malta',
				'Mauritius',
				'Maldives',
				'Malawi',
				'Mexico',
				'Malaysia',
				'Mozambique',
				'Namibia',
				'New Caledonia',
				'Niger',
				'Norfolk Island',
				'Nigeria',
				'Nicaragua',
				'Netherlands',
				'Norway',
				'Nepal',
				'Nauru',
				'Niue',
				'New Zealand',
				'Oman',
				'Panama',
				'Peru',
				'French Polynesia',
				'Papua New Guinea',
				'Philippines',
				'Pakistan',
				'Poland',
				'Saint Pierre and Miquelon',
				'Pitcairn',
				'Puerto Rico',
				'Palestinian Territory',
				'Portugal',
				'Palau',
				'Paraguay',
				'Qatar',
				'Reunion',
				'Romania',
				'Serbia',
				'Russian Federation',
				'Rwanda',
				'Saudi Arabia',
				'Solomon Islands',
				'Seychelles',
				'Sudan',
				'Sweden',
				'Singapore',
				'Saint Helena',
				'Slovenia',
				'Svalbard and Jan Mayen',
				'Slovakia',
				'Sierra Leone',
				'San Marino',
				'Senegal',
				'Somalia',
				'Suriname',
				'Sao Tome and Principe',
				'El Salvador',
				'Syrian Arab Republic',
				'Swaziland',
				'Turks and Caicos Islands',
				'Chad',
				'French Southern Territories',
				'Togo',
				'Thailand',
				'Tajikistan',
				'Tokelau',
				'Timor-Leste',
				'Turkmenistan',
				'Tunisia',
				'Tonga',
				'Turkey',
				'Trinidad and Tobago',
				'Tuvalu',
				'Taiwan',
				'Tanzania, United Republic of',
				'Ukraine',
				'Uganda',
				'United States Minor Outlying Islands',
				'United States',
				'Uruguay',
				'Uzbekistan',
				'Holy See (Vatican City State)',
				'Saint Vincent and the Grenadines',
				'Venezuela',
				'Virgin Islands, British',
				'Virgin Islands, U.S.',
				'Vietnam',
				'Vanuatu',
				'Wallis and Futuna',
				'Samoa',
				'Yemen',
				'Mayotte',
				'South Africa',
				'Zambia',
				'Zimbabwe',
				'Anonymous Proxy',
				'Satellite Provider',
			);
		}
	}

}

Captwiki_Location::get_instance();
