<?php
/**
 * Frontend AJAX Handler.
 *
 * @package PrivexPasswordProtect
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class PPMSTR_Public_AJAX_Handler
 */
class PPMSTR_Public_AJAX_Handler {

	/**
	 * Register actions.
	 */
	public function init() {
		add_action( 'wp_ajax_ppmstr_unlock', array( $this, 'ajax_unlock' ) );
		add_action( 'wp_ajax_nopriv_ppmstr_unlock', array( $this, 'ajax_unlock' ) );
	}

	/**
	 * Handle AJAX form submission for unlocking protected content.
	 */
	public function ajax_unlock() {
		ob_start();

		// Basic validation.
		if ( empty( $_POST['ppmstr_password'] ) || empty( $_POST['ppmstr_nonce'] ) ) {
			ob_end_clean();
			wp_send_json_error( array( 'message' => __( 'Missing password or nonce.', 'privex-password-protect' ) ) );
		}

		$nonce_field = sanitize_text_field( wp_unslash( $_POST['ppmstr_nonce'] ) );
		$type        = isset( $_POST['ppmstr_type'] ) ? sanitize_key( $_POST['ppmstr_type'] ) : '';
		$post_id     = isset( $_POST['ppmstr_post_id'] ) ? absint( $_POST['ppmstr_post_id'] ) : 0;
		$password    = sanitize_text_field( wp_unslash( $_POST['ppmstr_password'] ) );
		$valid       = false;

		// Phase 6: Brute Force Limit Login Check.
		if ( class_exists( 'PPMSTR_Security_Handler' ) ) {
			$bf_check = PPMSTR_Security_Handler::check_brute_force();
			if ( true !== $bf_check ) {
				PPMSTR_Security_Handler::record_failed_attempt();
				ob_end_clean();
				wp_send_json_error( array( 'message' => $bf_check ) );
			}

			// Phase 6: CAPTCHA Verification.
			$captcha_check = PPMSTR_Security_Handler::verify_captcha();
			if ( true !== $captcha_check ) {
				PPMSTR_Security_Handler::record_failed_attempt();
				ob_end_clean();
				wp_send_json_error( array( 'message' => $captcha_check ) );
			}
		}

		if ( ! class_exists( 'PPMSTR_Cookie_Manager' ) ) {
			require_once PPMSTR_PLUGIN_DIR . 'includes/core/class-ppmstr-cookie-manager.php';
		}
		if ( ! class_exists( 'PPMSTR_Password_Validator' ) ) {
			require_once PPMSTR_PLUGIN_DIR . 'includes/core/class-ppmstr-password-validator.php';
		}
		if ( ! class_exists( 'PPMSTR_Logger' ) ) {
			require_once PPMSTR_PLUGIN_DIR . 'includes/core/class-ppmstr-logger.php';
		}

		$cookies   = new PPMSTR_Cookie_Manager();
		$validator = new PPMSTR_Password_Validator();

		switch ( $type ) {
			case 'site':
				if ( ! wp_verify_nonce( $nonce_field, 'ppmstr_password_site' ) ) {
					ob_end_clean();
					wp_send_json_error( array( 'message' => __( 'Security check failed.', 'privex-password-protect' ) ) );
				}
				if ( $validator->validate_master( $password ) ) {
					$cookies->set_master_cookie();
					$valid = true;
				} else {
					$valid = $validator->validate_for_site( $password );
					if ( $valid ) {
						$cookies->set_site_cookie();
					}
				}
				break;

			case 'post':
				if ( ! wp_verify_nonce( $nonce_field, 'ppmstr_password_' . $post_id ) ) {
					ob_end_clean();
					wp_send_json_error( array( 'message' => __( 'Security check failed.', 'privex-password-protect' ) ) );
				}
				$result = $validator->validate_for_post( $password, $post_id );
				if ( 'master' === $result ) {
					$cookies->set_master_cookie();
					$valid = true;
				} elseif ( $result ) {
					$cookies->set_post_cookie( $post_id );
					$valid = true;
				}
				break;

			case 'category':
				$term_id = isset( $_POST['ppmstr_term_id'] ) ? absint( $_POST['ppmstr_term_id'] ) : 0;
				if ( ! wp_verify_nonce( $nonce_field, 'ppmstr_password_cat_' . $term_id ) ) {
					ob_end_clean();
					wp_send_json_error( array( 'message' => __( 'Security check failed.', 'privex-password-protect' ) ) );
				}
				$settings = get_option( 'ppmstr_settings', array() );
				$cat_hash = isset( $settings['category_password'] ) ? $settings['category_password'] : '';
				if ( wp_check_password( $password, $cat_hash ) ) {
					$cookies->set_category_cookie( $term_id );
					$valid = true;
				}
				break;

			case 'post_type':
				$post_type = isset( $_POST['ppmstr_post_type'] ) ? sanitize_key( $_POST['ppmstr_post_type'] ) : '';
				if ( ! wp_verify_nonce( $nonce_field, 'ppmstr_password_pt_' . $post_type ) ) {
					ob_end_clean();
					wp_send_json_error( array( 'message' => __( 'Security check failed.', 'privex-password-protect' ) ) );
				}
				if ( $validator->validate_for_post_type( $password, $post_type ) ) {
					$cookies->set_post_type_cookie( $post_type );
					$valid = true;
				}
				break;

			case 'child':
				$parent_id = isset( $_POST['ppmstr_parent_id'] ) ? absint( $_POST['ppmstr_parent_id'] ) : 0;
				if ( ! wp_verify_nonce( $nonce_field, 'ppmstr_password_' . $parent_id ) ) {
					ob_end_clean();
					wp_send_json_error( array( 'message' => __( 'Security check failed.', 'privex-password-protect' ) ) );
				}
				if ( $validator->validate_for_post( $password, $parent_id ) ) {
					$cookies->set_post_cookie( $parent_id );
					$valid = true;
				}
				break;

			case 'shortcode':
				$instance_id = isset( $_POST['ppmstr_instance'] ) ? sanitize_key( $_POST['ppmstr_instance'] ) : '';
				if ( ! wp_verify_nonce( $nonce_field, 'ppmstr_password_sc_' . $instance_id ) ) {
					wp_send_json_error( array( 'message' => __( 'Security check failed.', 'privex-password-protect' ) ) );
				}
				$stored_hash = isset( $_POST['ppmstr_hash'] ) ? sanitize_text_field( wp_unslash( $_POST['ppmstr_hash'] ) ) : '';
				if ( wp_check_password( $password, $stored_hash ) ) {
					$cookies->set_shortcode_cookie( $instance_id, $password );
					$valid = true;
				}
				break;
		}

		// Determine log target safely based on POST variables.
		$log_target = 0;
		if ( 'post' === $type || 'child' === $type ) {
			$log_target = $post_id; // $post_id is defined safely at the top.
		} elseif ( 'category' === $type && isset( $_POST['ppmstr_term_id'] ) ) {
			$log_target = absint( $_POST['ppmstr_term_id'] );
		}

		if ( $valid ) {
			if ( class_exists( 'PPMSTR_Security_Handler' ) ) {
				PPMSTR_Security_Handler::reset_failed_attempts();
				PPMSTR_Security_Handler::register_session();
			}
			
			// Log successful attempt.
			if ( class_exists( 'PPMSTR_Logger' ) ) {
				PPMSTR_Logger::log_attempt( $type, $log_target, 'success' );
			}

			ob_end_clean();
			wp_send_json_success(
				array(
					'message'  => __( 'Success! Unlocking content...', 'privex-password-protect' ),
					'redirect' => '', // Empty means just reload the current page.
				)
			);
		} else {
			// Log failed attempt.
			if ( class_exists( 'PPMSTR_Logger' ) ) {
				PPMSTR_Logger::log_attempt( $type, $log_target, 'failed' );
			}

			if ( class_exists( 'PPMSTR_Security_Handler' ) ) {
				PPMSTR_Security_Handler::record_failed_attempt();
			}

			$settings = get_option( 'ppmstr_settings', array() );
			$msg      = isset( $settings['form_error_message'] ) && ! empty( $settings['form_error_message'] ) 
							? $settings['form_error_message'] 
							: __( 'Incorrect password. Please try again.', 'privex-password-protect' );

			ob_end_clean();
			wp_send_json_error(
				array(
					'message' => $msg,
				)
			);
		}
	}
}
