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

function chcpl_register_shortcodes() {
	add_shortcode( 'comhit_pricelist', 'chcpl_render_pricelist_shortcode' );
}

function chcpl_render_pricelist_shortcode( $atts ) {
	// Ensure assets are loaded even when shortcode is used in a widget or page builder
	wp_enqueue_style( 'chcpl-front' );
	wp_enqueue_script( 'chcpl-front' );

	$atts = shortcode_atts( array(
		'id' => 0,
		'max_width' => '',
		'button_bg' => '',
		'button_text' => '',
		'force_unlock' => '', // Internal parameter to bypass lock when rendering from AJAX
	), $atts );

	$list_id = (int) $atts['id'];
	if ( $list_id <= 0 ) {
		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
		return current_user_can( 'edit_posts' ) ? '<div class="chcpl-empty">[Comhit Price List] Missing id attribute. Received: ' . esc_html( var_export( $atts['id'], true ) ) . '</div>' : '';
	}

	$list = get_post( $list_id );
	if ( ! $list || $list->post_type !== 'price_list' ) {
		$debug = '';
		if ( current_user_can( 'edit_posts' ) ) {
			$debug = ' (List ID: ' . $list_id . ', Post exists: ' . ( $list ? 'yes' : 'no' );
			if ( $list ) {
				$debug .= ', Post type: ' . $list->post_type . ', Status: ' . $list->post_status;
			}
			$debug .= ')';
		}
		return current_user_can( 'edit_posts' ) ? '<div class="chcpl-empty">[Comhit Price List] Invalid list ID' . $debug . '</div>' : '';
	}

	// If force_unlock is set, bypass the lock check (used when rendering from AJAX unlock)
	$force_unlocked = ! empty( $atts['force_unlock'] ) && ( $atts['force_unlock'] === '1' || $atts['force_unlock'] === 'true' || $atts['force_unlock'] === true );

	$is_free = function_exists( 'chcpl_is_free' ) && chcpl_is_free();
	$is_solo = ! $is_free; // solo, pro, and business all pass chcpl_is_plan('solo')
	$is_pro  = function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'pro' );

	// Free plan: only the oldest published price list may be rendered.
	if ( $is_free ) {
		$first_list_ids = get_posts( array(
			'post_type'      => 'price_list',
			'numberposts'    => 1,
			'post_status'    => 'publish',
			'orderby'        => 'date',
			'order'          => 'ASC',
			'fields'         => 'ids',
		) );
		$first_list_id = ! empty( $first_list_ids ) ? (int) $first_list_ids[0] : 0;
		if ( $list_id !== $first_list_id ) {
			return current_user_can( 'edit_posts' )
				? '<div class="chcpl-empty">[AD Pro Price Lists] Multiple price lists require a Solo plan. Only the first list renders on the free plan.</div>'
				: '';
		}
	}

	$lock_enabled = false;
	$admin_bypass = false;
	/* <fs_premium_only> */
	$redirect_enabled = $is_pro && get_post_meta( $list_id, '_chcpl_redirect_enabled', true ) === '1';
	$redirect_page_id = $is_pro ? (int) get_post_meta( $list_id, '_chcpl_redirect_page_id', true ) : 0;
	$redirect_url     = ( $redirect_enabled && $redirect_page_id > 0 ) ? get_permalink( $redirect_page_id ) : '';

	$lock_enabled = $is_pro && get_post_meta( $list_id, '_chcpl_lock_enabled', true ) === '1';
	$is_unlocked = $force_unlocked || ( function_exists( 'chcpl_is_list_unlocked' ) && chcpl_is_list_unlocked( $list_id ) );
	$settings = function_exists( 'chcpl_get_settings' ) ? chcpl_get_settings() : array();
	$admin_auto_unlock = isset( $settings['admin_auto_unlock'] ) ? $settings['admin_auto_unlock'] : '1';
	$admin_bypass = $is_pro && is_user_logged_in() && current_user_can( 'manage_options' ) && $admin_auto_unlock === '1';

	// Lock block — Pro only. Without Pro, skip the lock and fall through to the list.
	if ( $is_pro && $lock_enabled && ! $is_unlocked && ! $force_unlocked ) {
		$surtitle = get_post_meta( $list_id, '_chcpl_lock_surtitle', true );
		$title    = get_post_meta( $list_id, '_chcpl_lock_title', true );
		$desc     = get_post_meta( $list_id, '_chcpl_lock_description', true );
		if ( $surtitle === '' ) { $surtitle = __( 'Our Prices', 'ad-pro-price-list' ); }
			if ( $title === '' ) { $title = __( 'Protected list', 'ad-pro-price-list' ); }
		if ( $desc === '' ) { $desc = __( 'Please enter the password to access this list.', 'ad-pro-price-list' ); }
		$list_title = get_the_title( $list_id );
		$settings = function_exists( 'chcpl_get_settings' ) ? chcpl_get_settings() : array();
		$access_prompt = isset( $settings['access_request_prompt'] ) && $settings['access_request_prompt'] !== ''
			? $settings['access_request_prompt']
			: __( 'Would you like to see our pricing?', 'ad-pro-price-list' );
		$access_modal_id = 'chcpl-access-modal-' . $list_id;
		$button_text = isset( $settings['access_request_button_text'] ) && $settings['access_request_button_text'] !== ''
			? $settings['access_request_button_text']
			: __( 'Request access', 'ad-pro-price-list' );
		$subtext_enabled = get_post_meta( $list_id, '_chcpl_lock_subtext_enabled', true ) === '1';
		$button_subtext  = $subtext_enabled ? get_post_meta( $list_id, '_chcpl_lock_subtext', true ) : '';
		$send_text       = get_post_meta( $list_id, '_chcpl_lock_send_text', true );
		if ( $send_text === '' ) { $send_text = __( 'Send', 'ad-pro-price-list' ); }
		$back_text       = get_post_meta( $list_id, '_chcpl_lock_back_text', true );
		if ( $back_text === '' ) { $back_text = __( '← Back', 'ad-pro-price-list' ); }
		ob_start();
		?>
		<div class="chcpl-lock" data-list-id="<?php echo esc_attr( $list_id ); ?>">
			<div class="chcpl-lock-card">

				<div class="chcpl-lock-main">
					<?php if ( ! empty( $surtitle ) ) : ?>
						<p class="chcpl-lock-surtitle"><?php echo esc_html( $surtitle ); ?></p>
					<?php endif; ?>
					<h3 class="chcpl-lock-title"><?php echo esc_html( $title ); ?></h3>
					<p class="chcpl-lock-desc"><?php echo esc_html( $desc ); ?></p>
					<div class="chcpl-lock-actions">
						<button type="button" class="chcpl-lock-btn-primary" data-show-panel="form">
							<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
							<?php echo esc_html( $button_text ); ?>
						</button>
						<div class="chcpl-lock-divider">
							<span class="chcpl-lock-divider-line"></span>
							<span class="chcpl-lock-divider-text"><?php echo esc_html__( 'or', 'ad-pro-price-list' ); ?></span>
							<span class="chcpl-lock-divider-line"></span>
						</div>
						<button type="button" class="chcpl-lock-btn-secondary" data-show-panel="pw">
							<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
							<?php echo esc_html__( "I already have a password", 'ad-pro-price-list' ); ?>
						</button>
					</div>
					<?php if ( ! empty( $button_subtext ) ) : ?>
						<p class="chcpl-access-subtext"><?php echo wp_kses_post( $button_subtext ); ?></p>
					<?php endif; ?>
				</div>

				<div class="chcpl-lock-panel chcpl-lock-panel--form">
					<p class="chcpl-lock-panel-eyebrow"><?php echo esc_html__( "Access Request", 'ad-pro-price-list' ); ?></p>
				<p class="chcpl-lock-panel-mandatory"><?php echo esc_html__( 'All fields are required.', 'ad-pro-price-list' ); ?></p>
					<form class="chcpl-inquiry-form chcpl-access-form"<?php echo $redirect_url ? ' data-redirect-url="' . esc_url( $redirect_url ) . '"' : ''; ?>>
						<input type="hidden" name="action" value="chcpl_request_access" />
						<input type="hidden" name="_wpnonce" value="<?php echo esc_attr( wp_create_nonce( 'chcpl_nonce' ) ); ?>" />
						<input type="hidden" name="list_id" value="<?php echo esc_attr( $list_id ); ?>" />
						<input type="hidden" name="list_name" value="<?php echo esc_attr( $list_title ); ?>" />
						<?php /* Honeypot field */ ?>
						<input type="text" name="website" value="" style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0;tabindex:-1;" autocomplete="off" aria-hidden="true" />
						<div class="chcpl-row">
							<p class="chcpl-col">
								<label><?php echo esc_html__( 'Name', 'ad-pro-price-list' ); ?></label>
								<input type="text" name="name" autocomplete="name" required />
							</p>
							<p class="chcpl-col">
								<label><?php echo esc_html__( 'Company', 'ad-pro-price-list' ); ?></label>
								<input type="text" name="company" autocomplete="organization" required />
							</p>
						</div>
						<p>
							<label><?php echo esc_html__( 'Company number', 'ad-pro-price-list' ); ?></label>
							<input type="text" name="siren" required />
						</p>
						<p>
							<label><?php echo esc_html__( 'E-mail', 'ad-pro-price-list' ); ?></label>
							<input type="email" name="email" autocomplete="email" required />
						</p>
						<p class="chcpl-form-actions">
							<button type="submit" class="chcpl-submit"><?php echo esc_html( $send_text ); ?></button>
						</p>
						<div class="chcpl-form-status" aria-live="polite" aria-atomic="true"></div>
					</form>
					<button type="button" class="chcpl-lock-back" data-show-panel="main"><?php echo esc_html( $back_text ); ?></button>
				</div>

				<div class="chcpl-lock-panel chcpl-lock-panel--pw">
					<p class="chcpl-lock-panel-eyebrow"><?php echo esc_html__( 'Direct access', 'ad-pro-price-list' ); ?></p>
					<form class="chcpl-lock-form">
						<input type="hidden" name="action" value="chcpl_unlock_list" />
						<input type="hidden" name="_wpnonce" value="<?php echo esc_attr( wp_create_nonce( 'chcpl_nonce' ) ); ?>" />
						<input type="hidden" name="list_id" value="<?php echo esc_attr( $list_id ); ?>" />
						<?php /* Honeypot field */ ?>
						<input type="text" name="homepage" value="" style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0;tabindex:-1;" autocomplete="off" aria-hidden="true" />
						<div class="chcpl-lock-fields">
							<input type="password" name="password" placeholder="<?php echo esc_attr__( 'Password', 'ad-pro-price-list' ); ?>" required maxlength="255" />
							<button type="submit" class="chcpl-lock-submit"><?php echo esc_html__( 'Enter', 'ad-pro-price-list' ); ?></button>
						</div>
						<div class="chcpl-form-status" aria-live="polite" aria-atomic="true"></div>
					</form>
					<button type="button" class="chcpl-lock-back" data-show-panel="main"><?php echo esc_html( $back_text ); ?></button>
				</div>

			</div>
		</div>
		<?php
		return ob_get_clean();
	}
	/* </fs_premium_only> */

	$services = get_posts( array(
		'post_type' => 'price_service',
		'numberposts' => -1,
		'post_status' => array( 'publish', 'draft' ),
		'meta_key' => '_chcpl_list_id',
		'meta_value' => $list_id,
		'orderby' => array( 'menu_order' => 'ASC', 'title' => 'ASC' ),
	) );

	// Free plan: cap at 5 services.
	if ( $is_free && count( $services ) > 5 ) {
		$services = array_slice( $services, 0, 5 );
	}

	if ( empty( $services ) ) {
		if ( current_user_can( 'edit_posts' ) ) {
			$all_services = get_posts( array(
				'post_type' => 'price_service',
				'numberposts' => -1,
				'post_status' => array( 'publish', 'draft' ),
			) );
			$all_count = count( $all_services );
			
			// Check which list IDs services are assigned to
			$list_id_distribution = array();
			foreach ( $all_services as $service ) {
				$assigned_list_id = get_post_meta( $service->ID, '_chcpl_list_id', true );
				if ( ! isset( $list_id_distribution[ $assigned_list_id ] ) ) {
					$list_id_distribution[ $assigned_list_id ] = 0;
				}
				$list_id_distribution[ $assigned_list_id ]++;
			}
			
			$distribution_text = '';
			foreach ( $list_id_distribution as $lid => $count ) {
				$list_title = $lid ? get_the_title( $lid ) : 'None';
				$distribution_text .= $list_title . ' (' . $lid . '): ' . $count . ', ';
			}
			
			$with_meta = get_posts( array(
				'post_type' => 'price_service',
				'numberposts' => -1,
				'post_status' => array( 'publish', 'draft' ),
				'meta_key' => '_chcpl_list_id',
				'meta_value' => $list_id,
			) );
			$meta_count = count( $with_meta );
			return '<div class="chcpl-empty">[Comhit Price List] No services assigned to this list. (Total services: ' . $all_count . ', Assigned to list ' . $list_id . ': ' . $meta_count . ')<br/>Distribution: ' . rtrim( $distribution_text, ', ' ) . '</div>';
		}
		return '';
	}

	$style_vars = array();
	/* <fs_premium_only> */
	if ( $is_pro ) {
		if ( $atts['max_width'] !== '' ) {
			$style_vars[] = '--chcpl-max-width:' . intval( $atts['max_width'] ) . 'px';
		}
		if ( $atts['button_bg'] !== '' ) {
			$style_vars[] = '--chcpl-button-bg:' . esc_attr( $atts['button_bg'] );
		}
		if ( $atts['button_text'] !== '' ) {
			$style_vars[] = '--chcpl-button-text:' . esc_attr( $atts['button_text'] );
		}
	}
	/* </fs_premium_only> */
	$style_attr = empty( $style_vars ) ? '' : ' style="' . esc_attr( implode( ';', $style_vars ) ) . '"';

	$grouped = array();
	$category_data = array(); // Store term_id, name, and order for each category
	
	foreach ( $services as $service ) {
		$terms = get_the_terms( $service->ID, 'price_category' );
		if ( empty( $terms ) || is_wp_error( $terms ) ) {
			// No category assigned - use "Autre"
			$autre_key = __( 'Autre', 'ad-pro-price-list' );
			if ( ! isset( $grouped[ $autre_key ] ) ) {
				$grouped[ $autre_key ] = array();
				$category_data[ $autre_key ] = array(
					'term_id' => 0,
					'name' => $autre_key,
					'order' => 999999, // Always last
				);
			}
			$grouped[ $autre_key ][] = $service;
			continue;
		}
		
		foreach ( $terms as $term ) {
			$cat_name = $term->name;
			if ( ! isset( $grouped[ $cat_name ] ) ) {
				$grouped[ $cat_name ] = array();
				$order = 0;
				/* <fs_premium_only> */
				if ( $is_solo ) {
					$order = (int) get_term_meta( $term->term_id, '_chcpl_category_order', true );
				}
				/* </fs_premium_only> */
				$category_data[ $cat_name ] = array(
					'term_id' => $term->term_id,
					'name' => $cat_name,
					'order' => $order > 0 ? $order : 999998, // Categories without order go after ordered ones but before "Autre"
				);
			}
			$grouped[ $cat_name ][] = $service;
		}
	}

	// Sort categories by order, then alphabetically, but ensure "Autre" always comes last
	$autre_key = __( 'Autre', 'ad-pro-price-list' );
	uksort( $grouped, function( $a, $b ) use ( $category_data, $autre_key ) {
		$data_a = isset( $category_data[ $a ] ) ? $category_data[ $a ] : array( 'order' => 999998, 'name' => $a );
		$data_b = isset( $category_data[ $b ] ) ? $category_data[ $b ] : array( 'order' => 999998, 'name' => $b );
		
		// If either is "Autre", it goes last
		if ( $a === $autre_key ) {
			return 1;
		}
		if ( $b === $autre_key ) {
			return -1;
		}
		
		// Sort by order first
		if ( $data_a['order'] !== $data_b['order'] ) {
			return $data_a['order'] - $data_b['order'];
		}
		
		// Then alphabetically
		return strnatcasecmp( $data_a['name'], $data_b['name'] );
	} );

	$modal_id = 'chcpl-modal-' . $list_id;
	ob_start();
	/* <fs_premium_only> */
	if ( $lock_enabled && $admin_bypass ) {
		?>
		<div class="chcpl-admin-info" style="background:#fffbe6;border:1px solid #facc15;color:#92400e;padding:8px 10px;border-radius:6px;margin:10px 0;font-size:13px;">
			<?php echo esc_html__( 'This list is password-protected for visitors. You are seeing it unlocked because you are an admin.', 'ad-pro-price-list' ); ?>
		</div>
		<?php
	}
	/* </fs_premium_only> */
	?>
	<div class="chcpl-list" data-list-id="<?php echo esc_attr( $list_id ); ?>"<?php echo $style_attr; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $style_attr is escaped on line 188 ?>>

		<?php foreach ( $grouped as $category => $items ) : 
			$category_term_id = isset( $category_data[ $category ] ) && isset( $category_data[ $category ]['term_id'] ) ? (int) $category_data[ $category ]['term_id'] : 0;
			$category_icon_id = 0;
			$category_icon_url = '';
			/* <fs_premium_only> */
			if ( $is_solo && $category_term_id > 0 ) {
				$category_icon_id  = (int) get_term_meta( $category_term_id, '_chcpl_category_icon', true );
				$category_icon_url = $category_icon_id > 0 ? wp_get_attachment_image_url( $category_icon_id, 'full' ) : '';
			}
			/* </fs_premium_only> */
		?>
			<div class="chcpl-category">
				<h3 class="chcpl-category-title">
					<?php if ( $category_icon_url ) : ?>
						<img src="<?php echo esc_url( $category_icon_url ); ?>" alt="" class="chcpl-category-icon" />
					<?php endif; ?>
					<span class="chcpl-category-title-text"><?php echo esc_html( $category ); ?></span>
				</h3>
				<div class="chcpl-services">
					<?php foreach ( $items as $service ) :
						$desc     = get_post_meta( $service->ID, '_chcpl_service_description', true );
						$price    = get_post_meta( $service->ID, '_chcpl_service_price', true );
						$sur_devis = get_post_meta( $service->ID, '_chcpl_service_sur_devis', true );
						$image_id = 0;
						$image_url = '';
						/* <fs_premium_only> */
						if ( $is_pro ) {
							$image_id  = (int) get_post_meta( $service->ID, '_chcpl_service_image', true );
							$image_url = $image_id ? wp_get_attachment_image_url( $image_id, 'large' ) : '';
						}
						/* </fs_premium_only> */
						$settings = function_exists( 'chcpl_get_settings' ) ? chcpl_get_settings() : array();
						$suffix   = isset( $settings['price_suffix'] ) ? $settings['price_suffix'] : '';
						if ( $sur_devis === '1' ) {
							$display_price = __( 'On quote', 'ad-pro-price-list' );
						} else {
							$display_price = $price;
							if ( ! empty( $suffix ) && ! empty( $price ) ) {
								$display_price = $price . ' ' . $suffix;
							}
						}
					?>
					<div class="chcpl-service<?php echo $image_url ? ' chcpl-service-has-image' : ''; ?>" data-service-id="<?php echo esc_attr( $service->ID ); ?>"<?php echo $image_url ? ' data-hover-image="' . esc_url( $image_url ) . '"' : ''; ?>>
						<div class="chcpl-service-left">
							<div class="chcpl-service-title"><?php echo esc_html( get_the_title( $service ) ); ?></div>
							<?php if ( ! empty( $desc ) ) : ?>
								<div class="chcpl-service-desc"><?php echo wp_kses_post( wpautop( $desc ) ); ?></div>
							<?php endif; ?>
						</div>
						<div class="chcpl-service-right">
							<div class="chcpl-service-price"><?php echo esc_html( $display_price ); ?></div>
							<button class="chcpl-inquiry-btn" type="button" data-modal-id="<?php echo esc_attr( $modal_id ); ?>" data-service-id="<?php echo esc_attr( $service->ID ); ?>" data-service-name="<?php echo esc_attr( get_the_title( $service ) ); ?>"><?php echo esc_html__( 'Quote Request', 'ad-pro-price-list' ); ?></button>
						</div>
					</div>
					<?php endforeach; ?>
				</div>
			</div>
		<?php endforeach; ?>
	</div>

	<?php if ( $is_free ) : ?>
	<p style="margin:12px 0 0;font-size:11px;color:#9ca3af;text-align:right;">
		<a href="https://altaydagistan.com" target="_blank" rel="noopener noreferrer" style="color:#9ca3af;text-decoration:none;">AD Pro Price Lists plugin by Altay Dagistan</a>
	</p>
	<?php endif; ?>

	<div id="<?php echo esc_attr( $modal_id ); ?>" class="chcpl-modal" aria-hidden="true">
		<div class="chcpl-modal-backdrop" data-close="true"></div>
		<div class="chcpl-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="<?php echo esc_attr( $modal_id ); ?>-title">
			<button class="chcpl-modal-close" type="button" data-close="true" aria-label="Close">×</button>
			<h3 id="<?php echo esc_attr( $modal_id ); ?>-title" class="chcpl-modal-title"><?php echo esc_html__( 'Quote Request', 'ad-pro-price-list' ); ?></h3>
			<form class="chcpl-inquiry-form">
				<input type="hidden" name="action" value="chcpl_send_inquiry" />
				<input type="hidden" name="_wpnonce" value="<?php echo esc_attr( wp_create_nonce( 'chcpl_nonce' ) ); ?>" />
				<input type="hidden" name="service_id" value="" />
				<input type="hidden" name="service_name" value="" />
				<input type="hidden" name="list_id" value="<?php echo esc_attr( $list_id ); ?>" />
				<?php /* Honeypot field - hidden from users but visible to bots */ ?>
				<input type="text" name="url" value="" style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0;tabindex:-1;" autocomplete="off" aria-hidden="true" />

				<p class="chcpl-selected-service"><strong>Service: </strong> <span class="chcpl-service-name"></span></p>

				<div class="chcpl-row">
					<p class="chcpl-col">
						<label><?php echo esc_html__( 'Your name', 'ad-pro-price-list' ); ?></label>
						<input type="text" name="name" autocomplete="name" required />
					</p>
					<p class="chcpl-col">
						<label><?php echo esc_html__( 'Company', 'ad-pro-price-list' ); ?></label>
						<input type="text" name="company" autocomplete="organization" required />
					</p>
				</div>
				<p>
					<label><?php echo esc_html__( 'Your email', 'ad-pro-price-list' ); ?></label>
					<input type="email" name="email" autocomplete="email" required />
				</p>
				<p>
					<label><?php echo esc_html__( 'Message', 'ad-pro-price-list' ); ?></label>
					<textarea name="message" rows="4"></textarea>
				</p>
				<p class="chcpl-form-actions">
					<button type="submit" class="chcpl-submit"><?php echo esc_html__( 'Send', 'ad-pro-price-list' ); ?></button>
				</p>
				<div class="chcpl-form-status" aria-live="polite" aria-atomic="true"></div>
			</form>
		</div>
	</div>
	<?php
	return ob_get_clean();
}
