<?php
// phpcs:disable WordPress.DB.SlowDBQuery
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

function chcpl_handle_inquiry() {
	check_ajax_referer( 'chcpl_nonce' );

	// Rate limiting
	$rate_check = chcpl_check_rate_limit( 'inquiry', 5, 300 ); // 5 attempts per 5 minutes
	if ( is_wp_error( $rate_check ) ) {
		wp_send_json_error( array( 'message' => $rate_check->get_error_message() ) );
	}

	// Honeypot check
	$honeypot_check = chcpl_check_honeypot();
	if ( is_wp_error( $honeypot_check ) ) {
		wp_send_json_error( array( 'message' => $honeypot_check->get_error_message() ) );
	}

	// Validate and sanitize input
	$fields = array(
		array( 'name' => 'name', 'type' => 'text', 'required' => true, 'max_length' => 100, 'label' => __( 'Name', 'ad-pro-price-list' ) ),
		array( 'name' => 'company', 'type' => 'text', 'required' => true, 'max_length' => 200, 'label' => __( 'Company', 'ad-pro-price-list' ) ),
		array( 'name' => 'email', 'type' => 'email', 'required' => true, 'max_length' => 100, 'label' => __( 'Email', 'ad-pro-price-list' ) ),
		array( 'name' => 'message', 'type' => 'textarea', 'required' => false, 'max_length' => 5000, 'label' => __( 'Message', 'ad-pro-price-list' ) ),
		array( 'name' => 'service_id', 'type' => 'int', 'required' => true, 'min' => 1, 'label' => __( 'Service ID', 'ad-pro-price-list' ) ),
		array( 'name' => 'list_id', 'type' => 'int', 'required' => true, 'min' => 1, 'label' => __( 'List ID', 'ad-pro-price-list' ) ),
	);

	$validated = chcpl_validate_form_input( $fields );
	if ( is_wp_error( $validated ) ) {
		wp_send_json_error( array( 'message' => $validated->get_error_message() ) );
	}

	$name         = $validated['name'];
	$company      = $validated['company'];
	$email        = $validated['email'];
	$message      = isset( $validated['message'] ) ? $validated['message'] : '';
	$service_id   = $validated['service_id'];
	$service_name = isset( $_POST['service_name'] ) ? sanitize_text_field( wp_unslash( $_POST['service_name'] ) ) : '';
	$list_id      = $validated['list_id'];

	$admin_email = get_option( 'admin_email' );
	/* translators: %s: service name */
	$subject = sprintf( __( 'Quote request: %s', 'ad-pro-price-list' ), $service_name ? $service_name : __( 'Service', 'ad-pro-price-list' ) );

	$body  = '';
	$body .= sprintf( "%s\n", __( 'New quote request', 'ad-pro-price-list' ) );
	$body .= "-------------------------\n";
	$body .= sprintf( "%s: %s\n", __( 'Service', 'ad-pro-price-list' ), $service_name );
	$body .= sprintf( "%s: %d\n", __( 'Service ID', 'ad-pro-price-list' ), $service_id );
	$body .= sprintf( "%s: %d\n", __( 'Price List ID', 'ad-pro-price-list' ), $list_id );
	$body .= "-------------------------\n";
	$body .= sprintf( "%s: %s\n", __( 'Name', 'ad-pro-price-list' ), $name );
	$body .= sprintf( "%s: %s\n", __( 'Company', 'ad-pro-price-list' ), $company );
	$body .= sprintf( "%s: %s\n\n", __( 'Email', 'ad-pro-price-list' ), $email );
	$body .= sprintf( "%s:\n%s\n", __( 'Message', 'ad-pro-price-list' ), $message );

	$headers = array( 'Content-Type: text/plain; charset=UTF-8' );
	if ( is_email( $email ) ) {
		// Sanitize name for email header to prevent header injection
		$safe_name = sanitize_text_field( $name );
		$safe_name = str_replace( array( "\r", "\n" ), '', $safe_name ); // Remove line breaks
		$headers[] = 'Reply-To: ' . $safe_name . ' <' . $email . '>';
	}

	$sent = wp_mail( $admin_email, $subject, $body, $headers );

	if ( $sent ) {
		if ( function_exists( 'chcpl_record_quote_request' ) ) {
			$list_name = get_the_title( $list_id );
			chcpl_record_quote_request( array(
				'list_id'      => $list_id,
				'list_name'    => $list_name ? $list_name : '',
				'service_id'   => $service_id,
				'service_name' => $service_name,
				'name'         => $name,
				'company'      => $company,
				'email'        => $email,
				'message'      => $message,
			) );
		}
		wp_send_json_success( array( 'message' => __( 'Thank you, your request has been sent.', 'ad-pro-price-list' ) ) );
	} else {
		wp_send_json_error( array( 'message' => __( "An error occurred. Please try again.", 'ad-pro-price-list' ) ) );
	}
}

/* <fs_premium_only> */
function chcpl_handle_unlock() {
	check_ajax_referer( 'chcpl_nonce' );

	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'pro' ) ) ) {
		wp_send_json_error( array( 'message' => __( 'This feature requires a Pro plan.', 'ad-pro-price-list' ) ) );
	}

	// Rate limiting - stricter for password attempts (prevent brute force)
	$rate_check = chcpl_check_rate_limit( 'unlock', 10, 600 ); // 10 attempts per 10 minutes
	if ( is_wp_error( $rate_check ) ) {
		wp_send_json_error( array( 'message' => $rate_check->get_error_message() ) );
	}

	// Honeypot check
	$honeypot_check = chcpl_check_honeypot();
	if ( is_wp_error( $honeypot_check ) ) {
		wp_send_json_error( array( 'message' => $honeypot_check->get_error_message() ) );
	}

	// Validate and sanitize input
	$fields = array(
		array( 'name' => 'list_id', 'type' => 'int', 'required' => true, 'min' => 1, 'label' => __( 'List ID', 'ad-pro-price-list' ) ),
		array( 'name' => 'password', 'type' => 'text', 'required' => true, 'max_length' => 255, 'label' => __( 'Password', 'ad-pro-price-list' ) ),
	);

	$validated = chcpl_validate_form_input( $fields );
	if ( is_wp_error( $validated ) ) {
		wp_send_json_error( array( 'message' => $validated->get_error_message() ) );
	}

	$list_id = $validated['list_id'];
	$password = $validated['password'];
	$enabled = get_post_meta( $list_id, '_chcpl_lock_enabled', true );
	if ( $enabled !== '1' ) {
		wp_send_json_error( array( 'message' => __( 'This list is not password-protected.', 'ad-pro-price-list' ) ) );
	}
	// Check against global passwords
	if ( ! function_exists( 'chcpl_validate_global_password' ) || ! chcpl_validate_global_password( $password ) ) {
		wp_send_json_error( array( 'message' => __( 'Password incorrect.', 'ad-pro-price-list' ) ) );
	}
	// Prevent caching for this AJAX response (important for logged-in users and LiteSpeed cache)
	nocache_headers();
	
	// Set temporary unlock state first
	if ( function_exists( 'chcpl_set_temp_unlock' ) ) {
		chcpl_set_temp_unlock( $list_id );
	}
	global $chcpl_unlocked_lists;
	if ( ! isset( $chcpl_unlocked_lists ) || ! is_array( $chcpl_unlocked_lists ) ) {
		$chcpl_unlocked_lists = array();
	}
	$chcpl_unlocked_lists[ $list_id ] = true;
	$GLOBALS['chcpl_unlocked_lists'] = $chcpl_unlocked_lists;
	
	// Directly render the shortcode with force_unlock parameter to bypass lock check
	// This is more reliable than relying on global variables, especially for logged-in users
	$html = do_shortcode( '[comhit_pricelist id="' . (int) $list_id . '" force_unlock="1"]' );
	
	// If HTML is still empty or too short, try without force_unlock (should work with global state set)
	if ( empty( $html ) || strlen( trim( wp_strip_all_tags( $html ) ) ) < 10 ) {
		$html = do_shortcode( '[comhit_pricelist id="' . (int) $list_id . '"]' );
	}
	
	// Check if we have valid HTML - be more lenient with the check
	$html_trimmed = trim( wp_strip_all_tags( $html ) );
	if ( empty( $html ) || ( strlen( $html_trimmed ) < 5 && ! current_user_can( 'edit_posts' ) ) ) {
		// For debugging: if user can edit, show more info
		$debug_msg = '';
		if ( current_user_can( 'edit_posts' ) ) {
			$services_count = count( get_posts( array(
				'post_type' => 'price_service',
				'numberposts' => -1,
				'post_status' => 'publish',
				'meta_key' => '_chcpl_list_id',
				'meta_value' => $list_id,
			) ) );
			$debug_msg = ' (Services: ' . $services_count . ', HTML length: ' . strlen( $html ) . ')';
		}
		wp_send_json_error( array( 
			'message' => __( 'Unlock error. Please refresh the page.', 'ad-pro-price-list' ) . $debug_msg,
			'html' => $html // Send HTML anyway so frontend can debug
		) );
	}
	
	wp_send_json_success( array( 'message' => __( 'Access granted.', 'ad-pro-price-list' ), 'html' => $html ) );
}

function chcpl_handle_request_access() {
	check_ajax_referer( 'chcpl_nonce' );

	// Rate limiting
	$rate_check = chcpl_check_rate_limit( 'request_access', 5, 300 ); // 5 attempts per 5 minutes
	if ( is_wp_error( $rate_check ) ) {
		wp_send_json_error( array( 'message' => $rate_check->get_error_message() ) );
	}

	// Honeypot check
	$honeypot_check = chcpl_check_honeypot();
	if ( is_wp_error( $honeypot_check ) ) {
		wp_send_json_error( array( 'message' => $honeypot_check->get_error_message() ) );
	}

	// Validate and sanitize input
	$fields = array(
		array( 'name' => 'name', 'type' => 'text', 'required' => true, 'max_length' => 100, 'label' => __( 'Name', 'ad-pro-price-list' ) ),
		array( 'name' => 'company', 'type' => 'text', 'required' => true, 'max_length' => 200, 'label' => __( 'Company', 'ad-pro-price-list' ) ),
		array( 'name' => 'siren', 'type' => 'text', 'required' => true, 'max_length' => 20, 'label' => __( 'SIREN', 'ad-pro-price-list' ) ),
		array( 'name' => 'email', 'type' => 'email', 'required' => true, 'max_length' => 100, 'label' => __( 'Email', 'ad-pro-price-list' ) ),
		array( 'name' => 'list_id', 'type' => 'int', 'required' => true, 'min' => 1, 'label' => __( 'List ID', 'ad-pro-price-list' ) ),
	);

	$validated = chcpl_validate_form_input( $fields );
	if ( is_wp_error( $validated ) ) {
		wp_send_json_error( array( 'message' => $validated->get_error_message() ) );
	}

	// Validate SIREN format
	$siren_validation = chcpl_validate_siren( $validated['siren'] );
	if ( is_wp_error( $siren_validation ) ) {
		wp_send_json_error( array( 'message' => $siren_validation->get_error_message() ) );
	}

	$name      = $validated['name'];
	$company   = $validated['company'];
	$siren     = preg_replace( '/[^0-9]/', '', $validated['siren'] ); // Clean SIREN
	$email     = $validated['email'];
	$list_id   = $validated['list_id'];
	$list_name = isset( $_POST['list_name'] ) ? sanitize_text_field( wp_unslash( $_POST['list_name'] ) ) : '';

	$admin_email = get_option( 'admin_email' );
	/* translators: %s: list name */
	$subject = sprintf( __( 'Access request for list: %s', 'ad-pro-price-list' ), $list_name ? $list_name : __( 'Price list', 'ad-pro-price-list' ) );

	$body  = '';
	$body .= sprintf( "%s\n", __( 'New price list access request', 'ad-pro-price-list' ) );
	$body .= "-------------------------\n";
	$body .= sprintf( "%s: %s\n", __( 'List', 'ad-pro-price-list' ), $list_name );
	$body .= sprintf( "%s: %d\n", __( 'List ID', 'ad-pro-price-list' ), $list_id );
	$body .= "-------------------------\n";
	$body .= sprintf( "%s: %s\n", __( 'Name', 'ad-pro-price-list' ), $name );
	$body .= sprintf( "%s: %s\n", __( 'Company', 'ad-pro-price-list' ), $company );
	$body .= sprintf( "%s: %s\n", __( 'Company number', 'ad-pro-price-list' ), $siren );
	$body .= sprintf( "%s: %s\n\n", __( 'Email', 'ad-pro-price-list' ), $email );

	$headers = array( 'Content-Type: text/plain; charset=UTF-8' );
	if ( is_email( $email ) ) {
		// Sanitize name for email header to prevent header injection
		$safe_name = sanitize_text_field( $name );
		$safe_name = str_replace( array( "\r", "\n" ), '', $safe_name ); // Remove line breaks
		$headers[] = 'Reply-To: ' . $safe_name . ' <' . $email . '>';
	}

	if ( function_exists( 'chcpl_record_access_request_submission' ) ) {
		chcpl_record_access_request_submission( array(
			'list_id'   => $list_id,
			'list_name' => $list_name,
			'name'      => $name,
			'company'   => $company,
			'siren'     => $siren,
			'email'     => $email,
			'payload'   => array(
				'name'      => $name,
				'company'   => $company,
				'siren'     => $siren,
				'email'     => $email,
				'list_id'   => $list_id,
				'list_name' => $list_name,
			),
		) );
	}

	$sent = wp_mail( $admin_email, $subject, $body, $headers );

	if ( $sent ) {
		wp_send_json_success( array( 'message' => __( 'Thank you, your request has been sent.', 'ad-pro-price-list' ) ) );
	} else {
		wp_send_json_error( array( 'message' => __( "An error occurred. Please try again.", 'ad-pro-price-list' ) ) );
	}
}
/* </fs_premium_only> */
