<?php
/**
 * ShieldGate Security Handler
 *
 * @category Security
 * @package  ShieldGate
 * @author   Damian Cendan <damian@itdamian.com>
 * @license  GPL-2.0-or-later
 * @link     https://itdamian.com
 * @version   1.0.2
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
	// Prevent direct access for security.
}
// Load the Freemius initialization.
require_once plugin_dir_path( __FILE__ ) . 'shieldgate-init.php';
/**
 * Main ShieldGate Security Class.
 *
 * @package  ShieldGate
 * @category Security
 * @author   Damian Cendan <damian@itdamian.com>
 * @license  GPL-2.0-or-later
 * @link     https://itdamian.com
 */
class ShieldGate_Security_Handler {
	/**
	 * Lockout time in seconds.
	 *
	 * @var int
	 */
	private $lockout_time = 900;

	/**
	 * Constructor to initialize hooks.
	 */
	public function __construct() {
		add_action( 'wp_login_failed', array( $this, 'track_failed_login' ) );
		add_action( 'login_head', array( $this, 'check_for_lockout' ) );
		add_action( 'admin_menu', array( $this, 'create_settings_page' ) );
		add_action( 'admin_init', array( $this, 'setup_plugin_settings' ) );
		add_action( 'init', array( $this, 'hide_login_page' ) );
	}

	/**
	 * Creates the admin menu page.
	 */
	public function create_settings_page() {
		add_menu_page(
			'ShieldGate Settings',
			'ShieldGate',
			'manage_options',
			'shieldgate-settings',
			array( $this, 'render_settings_html' ),
			'dashicons-shield',
			80
		);
	}

	/**
	 * Tracks failed login attempts by IP.
	 */
	public function track_failed_login() {
		$ip             = ( isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '0.0.0.0' );
		$transient_name = 'shieldgate_lockout_' . str_replace( '.', '_', $ip );
		$attempts       = get_transient( $transient_name );
		$attempts       = ( $attempts ? $attempts + 1 : 1 );
		set_transient( $transient_name, $attempts, $this->lockout_time );
	}

	/**
	 * Registers plugin settings.
	 */
	public function setup_plugin_settings() {
		register_setting( 'shieldgate_settings_group', 'shieldgate_login_limit', 'absint' );
		register_setting(
			'shieldgate_settings_group',
			'shieldgate_secret_slug',
			array(
				'sanitize_callback' => 'sanitize_title',
			)
		);
	}

	/**
	 * Renders the settings page HTML.
	 */
	public function render_settings_html() {
		$current_slug  = get_option( 'shieldgate_secret_slug', '' );
		$current_limit = (int) get_option( 'shieldgate_login_limit', 5 );
		$current_ips   = get_option( 'shieldgate_ip_whitelist', '' );
		?>
		<div class="wrap">
			<h1>ShieldGate Security</h1>
			<?php
			settings_errors();
			?>
				<div style="display: flex; gap: 20px; margin-top: 20px;">
					<div style="flex: 2; background: #fff; padding: 20px; border: 1px solid #ccd0d4;">
						<form method="post" action="options.php">
							<?php
							settings_fields( 'shieldgate_settings_group' );
							wp_nonce_field( 'shieldgate_save_settings', 'shieldgate_settings_nonce' );
							?>
							<table class="form-table">
								<tr>
									<th scope="row">Login Attempt Limit</th>
									<td>
										<input
											type="number"
											name="shieldgate_login_limit"
											value="<?php echo esc_attr( $current_limit ); ?>"
										/>
									</td>

								</tr>
								<tr>
									<th scope="row">Secret Login Slug</th>
									<td>
										<input
											type="text"
											name="shieldgate_secret_slug"
											value="<?php echo esc_attr( $current_slug ); ?>"
										/>
									</td>

								</tr>
							</table>
							<?php
							submit_button();
							?>
						</form>
						<?php
						if ( ! empty( $current_slug ) ) {
							?>
							<hr>
							<h3>Emergency Access</h3>
							<p>If you forget your slug, use this <strong>Emergency URL</strong>:<br>
							<code>
								<?php
								echo esc_url( home_url( '/wp-login.php?' . $current_slug ) );
								?>
							</code>
							</p>
							<?php
						}
						?>
					</div>
					<?php
					if ( ! shieldgate_fs()->is_premium() ) {
						?>
						<div style="flex: 1; background: #2271b1; color: #fff; padding: 20px; border-radius: 4px;">
							<h2 style="color: #fff; margin-top: 0;">Upgrade to Pro</h2>
							<ul style="list-style: disc; padding-left: 20px;">
								<li><strong>IP Whitelisting</strong></li>
								<li><strong>Email Alerts</strong></li>
							</ul>
							<a href="
							<?php
							echo esc_url( shieldgate_fs()->get_upgrade_url() );
							?>
							"
								style="display: inline-block; background: #ffb900; color: #000; padding: 10px 20px; text-decoration: none; font-weight: bold; border-radius: 4px;">
								Get Pro Now
							</a>
						</div>
						<?php
					}
					?>
				</div>
			</div>
		<?php
	}

	/**
	 * Checks if the current visitor is locked out.
	 */
	public function check_for_lockout() {
		if ( is_user_logged_in() ) {
			return;
		}
					$ip = ( isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '0.0.0.0' );
		$transient_name = 'shieldgate_lockout_' . str_replace( '.', '_', $ip );
			$attempts   = get_transient( $transient_name );
				$limit  = get_option( 'shieldgate_login_limit', 5 );
		if ( $attempts && $attempts >= $limit ) {
			wp_die( 'ShieldGate: Too many failed attempts.' );
		}
	}

	/**
	 * Verifies if an IP is whitelisted.
	 *
	 * @return bool
	 */
	private function is_ip_whitelisted() {
		return false;
	}

	/**
	 * Hides the login page unless the secret slug is provided.
	 */
	public function hide_login_page() {
		if ( is_user_logged_in() ) {
			return;
		}
		$secret_slug = get_option( 'shieldgate_secret_slug' );
		if ( empty( $secret_slug ) ) {
			return;
		}
		if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] ) {
			if ( isset( $_POST['option_page'] ) && 'shieldgate_settings_group' === $_POST['option_page'] ) {
				if ( ! isset( $_POST['shieldgate_settings_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['shieldgate_settings_nonce'] ), 'shieldgate_save_settings' ) ) {
					wp_die( 'Security check failed.' );
				}
			}
			return;
		}
		$request_uri = ( isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '' );
		if ( false !== strpos( $request_uri, 'wp-login.php' ) && ! isset( $_GET[ $secret_slug ] ) ) {
			$action = filter_input( INPUT_GET, 'action', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
			if ( 'logout' !== $action && 'interim-login' !== $action ) {
				wp_safe_redirect( home_url() );
				exit;
			}
		}
	}
}

new ShieldGate_Security_Handler();
