<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

function chcpl_add_list_lock_metabox() {
	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'pro' ) ) ) {
		return;
	}
	add_meta_box(
		'chcpl_list_lock',
		__( 'Price List Lock', 'ad-pro-price-list' ),
		'chcpl_render_list_lock_metabox',
		'price_list',
		'normal',
		'default'
	);
}
add_action( 'add_meta_boxes', 'chcpl_add_list_lock_metabox' );

function chcpl_render_list_lock_metabox( $post ) {
	wp_nonce_field( 'chcpl_save_list_lock', 'chcpl_list_lock_nonce' );
	$enabled          = get_post_meta( $post->ID, '_chcpl_lock_enabled', true );
	$surtitle         = get_post_meta( $post->ID, '_chcpl_lock_surtitle', true );
	$title            = get_post_meta( $post->ID, '_chcpl_lock_title', true );
	$description      = get_post_meta( $post->ID, '_chcpl_lock_description', true );
	$subtext_enabled  = get_post_meta( $post->ID, '_chcpl_lock_subtext_enabled', true );
	$subtext          = get_post_meta( $post->ID, '_chcpl_lock_subtext', true );
	$back_text        = get_post_meta( $post->ID, '_chcpl_lock_back_text', true );
	$send_text        = get_post_meta( $post->ID, '_chcpl_lock_send_text', true );
	$expires      = get_post_meta( $post->ID, '_chcpl_lock_expires', true );
	$expires_type = get_post_meta( $post->ID, '_chcpl_lock_expires_type', true );
	if ( ! $expires_type ) { $expires_type = 'indefinite'; }
	
	$global_passwords = function_exists( 'chcpl_get_global_passwords' ) ? chcpl_get_global_passwords() : array();
	$passwords_count = count( $global_passwords );
	?>
	<p>
		<label><input type="checkbox" name="chcpl_lock_enabled" value="1" <?php checked( $enabled, '1' ); ?> /> <?php echo esc_html__( 'Require password to view this list', 'ad-pro-price-list' ); ?></label>
	</p>
	<?php if ( $enabled === '1' ) : ?>
		<div class="notice notice-info inline" style="margin: 10px 0;">
			<p>
				<strong><?php echo esc_html__( 'Global Passwords:', 'ad-pro-price-list' ); ?></strong>
				<?php if ( $passwords_count > 0 ) : ?>
					<?php
					/* translators: %d: number of global passwords */
					echo esc_html( sprintf( _n( '%d global password is configured.', '%d global passwords are configured.', $passwords_count, 'ad-pro-price-list' ), $passwords_count ) );
					?>
					<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=price_list&page=chcpl_passwords' ) ); ?>"><?php echo esc_html__( 'Manage passwords', 'ad-pro-price-list' ); ?></a>
				<?php else : ?>
					<?php echo esc_html__( 'No global passwords configured.', 'ad-pro-price-list' ); ?>
					<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=price_list&page=chcpl_passwords' ) ); ?>"><?php echo esc_html__( 'Add passwords', 'ad-pro-price-list' ); ?></a>
				<?php endif; ?>
			</p>
		</div>
	<?php endif; ?>
	<p>
		<label for="chcpl_lock_surtitle"><strong><?php echo esc_html__( 'Surtitle (eyebrow above title)', 'ad-pro-price-list' ); ?></strong></label><br />
		<input type="text" id="chcpl_lock_surtitle" name="chcpl_lock_surtitle" value="<?php echo esc_attr( $surtitle ); ?>" class="large-text" placeholder="<?php echo esc_attr__( 'e.g. Pricing grid', 'ad-pro-price-list' ); ?>" />
	</p>
	<p>
		<label for="chcpl_lock_title"><strong><?php echo esc_html__( 'Lock Title', 'ad-pro-price-list' ); ?></strong></label><br />
		<input type="text" id="chcpl_lock_title" name="chcpl_lock_title" value="<?php echo esc_attr( $title ); ?>" class="large-text" placeholder="<?php echo esc_attr__( 'Protected list', 'ad-pro-price-list' ); ?>" />
	</p>
	<p>
		<label for="chcpl_lock_description"><strong><?php echo esc_html__( 'Description', 'ad-pro-price-list' ); ?></strong></label><br />
		<textarea id="chcpl_lock_description" name="chcpl_lock_description" rows="3" class="large-text" placeholder="<?php echo esc_attr__( 'Please enter the password to access this list.', 'ad-pro-price-list' ); ?>"><?php echo esc_textarea( $description ); ?></textarea>
	</p>
	<p>
		<label>
			<input type="checkbox" name="chcpl_lock_subtext_enabled" value="1" <?php checked( $subtext_enabled, '1' ); ?> id="chcpl_lock_subtext_enabled" onchange="document.getElementById('chcpl_lock_subtext_wrap').style.display=this.checked?'block':'none'" />
			<strong><?php echo esc_html__( 'Show subtext below buttons', 'ad-pro-price-list' ); ?></strong>
		</label>
	</p>
	<div id="chcpl_lock_subtext_wrap" style="display:<?php echo $subtext_enabled === '1' ? 'block' : 'none'; ?>">
		<p>
			<label for="chcpl_lock_subtext"><?php echo esc_html__( 'Subtext', 'ad-pro-price-list' ); ?></label><br />
			<input type="text" id="chcpl_lock_subtext" name="chcpl_lock_subtext" value="<?php echo esc_attr( $subtext ); ?>" class="large-text" placeholder="<?php echo esc_attr__( 'e.g. Reserved for professionals', 'ad-pro-price-list' ); ?>" />
		</p>
	</div>
	<p>
		<label for="chcpl_lock_send_text"><strong><?php echo esc_html__( 'Send Button Text', 'ad-pro-price-list' ); ?></strong></label><br />
		<input type="text" id="chcpl_lock_send_text" name="chcpl_lock_send_text" value="<?php echo esc_attr( $send_text ); ?>" class="large-text" placeholder="<?php echo esc_attr__( 'Send', 'ad-pro-price-list' ); ?>" />
	</p>
	<p>
		<label for="chcpl_lock_back_text"><strong><?php echo esc_html__( 'Back Button Text', 'ad-pro-price-list' ); ?></strong></label><br />
		<input type="text" id="chcpl_lock_back_text" name="chcpl_lock_back_text" value="<?php echo esc_attr( $back_text ); ?>" class="large-text" placeholder="← Back" />
	</p>
	<p>
		<label for="chcpl_lock_expires_type"><strong><?php echo esc_html__( 'Password Expiration', 'ad-pro-price-list' ); ?></strong></label><br />
		<select id="chcpl_lock_expires_type" name="chcpl_lock_expires_type" onchange="document.getElementById('chcpl_expires_date_wrapper').style.display=this.value==='date'?'block':'none'">
			<option value="indefinite" <?php selected( $expires_type, 'indefinite' ); ?>><?php echo esc_html__( 'Indefinite (never expires)', 'ad-pro-price-list' ); ?></option>
			<option value="date" <?php selected( $expires_type, 'date' ); ?>><?php echo esc_html__( 'Expires on specific date', 'ad-pro-price-list' ); ?></option>
		</select>
	</p>
	<p id="chcpl_expires_date_wrapper" style="display:<?php echo $expires_type === 'date' ? 'block' : 'none'; ?>">
		<label for="chcpl_lock_expires"><strong><?php echo esc_html__( 'Expiration Date', 'ad-pro-price-list' ); ?></strong></label><br />
		<input type="date" id="chcpl_lock_expires" name="chcpl_lock_expires" value="<?php echo esc_attr( $expires ); ?>" class="regular-text" />
	</p>
	<?php
}

function chcpl_save_list_lock( $post_id, $post ) {
	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'pro' ) ) ) {
		return;
	}
	if ( $post->post_type !== 'price_list' ) {
		return;
	}
	if ( ! isset( $_POST['chcpl_list_lock_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['chcpl_list_lock_nonce'] ) ), 'chcpl_save_list_lock' ) ) {
		return;
	}
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	$enabled         = isset( $_POST['chcpl_lock_enabled'] ) ? '1' : '';
	$surtitle        = isset( $_POST['chcpl_lock_surtitle'] ) ? sanitize_text_field( wp_unslash( $_POST['chcpl_lock_surtitle'] ) ) : '';
	$title           = isset( $_POST['chcpl_lock_title'] ) ? sanitize_text_field( wp_unslash( $_POST['chcpl_lock_title'] ) ) : '';
	$description     = isset( $_POST['chcpl_lock_description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['chcpl_lock_description'] ) ) : '';
	$subtext_enabled = isset( $_POST['chcpl_lock_subtext_enabled'] ) ? '1' : '';
	$subtext         = isset( $_POST['chcpl_lock_subtext'] ) ? sanitize_text_field( wp_unslash( $_POST['chcpl_lock_subtext'] ) ) : '';
	$send_text       = isset( $_POST['chcpl_lock_send_text'] ) ? sanitize_text_field( wp_unslash( $_POST['chcpl_lock_send_text'] ) ) : '';
	$back_text       = isset( $_POST['chcpl_lock_back_text'] ) ? sanitize_text_field( wp_unslash( $_POST['chcpl_lock_back_text'] ) ) : '';
	$expires_type = isset( $_POST['chcpl_lock_expires_type'] ) ? sanitize_text_field( wp_unslash( $_POST['chcpl_lock_expires_type'] ) ) : 'indefinite';
	$expires      = isset( $_POST['chcpl_lock_expires'] ) && $expires_type === 'date' ? sanitize_text_field( wp_unslash( $_POST['chcpl_lock_expires'] ) ) : '';

	if ( $enabled ) { update_post_meta( $post_id, '_chcpl_lock_enabled', '1' ); } else { delete_post_meta( $post_id, '_chcpl_lock_enabled' ); }
	update_post_meta( $post_id, '_chcpl_lock_surtitle', $surtitle );
	update_post_meta( $post_id, '_chcpl_lock_title', $title );
	update_post_meta( $post_id, '_chcpl_lock_description', $description );
	if ( $subtext_enabled ) { update_post_meta( $post_id, '_chcpl_lock_subtext_enabled', '1' ); } else { delete_post_meta( $post_id, '_chcpl_lock_subtext_enabled' ); }
	update_post_meta( $post_id, '_chcpl_lock_subtext', $subtext );
	update_post_meta( $post_id, '_chcpl_lock_send_text', $send_text );
	update_post_meta( $post_id, '_chcpl_lock_back_text', $back_text );
	update_post_meta( $post_id, '_chcpl_lock_expires_type', $expires_type );
	if ( $expires_type === 'date' ) {
		update_post_meta( $post_id, '_chcpl_lock_expires', $expires );
	} else {
		delete_post_meta( $post_id, '_chcpl_lock_expires' );
	}
	// Remove old per-list password meta if it exists (cleanup)
	delete_post_meta( $post_id, '_chcpl_lock_password' );
}
add_action( 'save_post', 'chcpl_save_list_lock', 10, 2 );

// In-memory per-request unlock flag. Used to render unlocked HTML via AJAX without cookies.
// Using global variable so both functions can access the same state.
function 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[ (int) $list_id ] = true;
	// Force the global to persist by explicitly setting it
	$GLOBALS['chcpl_unlocked_lists'] = $chcpl_unlocked_lists;
}

function chcpl_is_list_unlocked( $list_id ) {
	global $chcpl_unlocked_lists;
	// Initialize if not set
	if ( ! isset( $chcpl_unlocked_lists ) || ! is_array( $chcpl_unlocked_lists ) ) {
		$chcpl_unlocked_lists = array();
	}
	// Check GLOBALS directly as fallback
	if ( isset( $GLOBALS['chcpl_unlocked_lists'][ (int) $list_id ] ) && true === $GLOBALS['chcpl_unlocked_lists'][ (int) $list_id ] ) {
		return true;
	}
	// If a previous call set a temporary unlock for this request, honor it
	if ( isset( $chcpl_unlocked_lists[ (int) $list_id ] ) && true === $chcpl_unlocked_lists[ (int) $list_id ] ) {
		return true;
	}
	// Admins see lists unlocked (if setting is enabled)
	if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) {
		$settings = function_exists( 'chcpl_get_settings' ) ? chcpl_get_settings() : array();
		$admin_auto_unlock = isset( $settings['admin_auto_unlock'] ) ? $settings['admin_auto_unlock'] : '1';
		if ( $admin_auto_unlock === '1' ) {
			return true;
		}
	}
	// By default, not unlocked (no cookies/sessions)
	return false;
}

function chcpl_output_noindex_for_locked_lists() {
	if ( is_admin() ) {
		return;
	}
	// Check if current page contains a locked price list shortcode
	global $post;
	if ( ! $post || ! has_shortcode( $post->post_content, 'comhit_pricelist' ) ) {
		return;
	}
	// Extract list IDs from shortcodes
	preg_match_all( '/\[comhit_pricelist id=["\']?(\d+)["\']?/', $post->post_content, $matches );
	if ( empty( $matches[1] ) ) {
		return;
	}
	foreach ( $matches[1] as $list_id ) {
		$lock_enabled = get_post_meta( (int) $list_id, '_chcpl_lock_enabled', true ) === '1';
		if ( $lock_enabled && ( ! function_exists( 'chcpl_is_list_unlocked' ) || ! chcpl_is_list_unlocked( (int) $list_id ) ) ) {
			echo '<meta name="robots" content="noindex, nofollow" />' . "\n";
			return;
		}
	}
}
add_action( 'wp_head', 'chcpl_output_noindex_for_locked_lists', 1 );
