<?php
/**
 * Organization settings page
 *
 * Allows editing of organization identity, business type, and related settings.
 *
 * @package BW_Schema
 * @since 3.0.0-babel
 */

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

class BW_Schema_Page_Organization extends BW_Schema_Page {

	/**
	 * Initialize page properties
	 *
	 * @return void
	 */
	protected function init() {
		$this->slug   = 'bw-schema-organization';
		$this->title  = __( 'Organization', 'bw-schema' );
		$this->icon   = 'dashicons-building';
		$this->parent_slug = 'bw-schema';
	}

	/**
	 * Handle form submission
	 *
	 * Validates and saves organization data.
	 *
	 * @return void
	 */
	protected function handle_save() {
		// Handle location form submission
		if ( isset( $_POST['location_action'] ) && isset( $_POST['location_nonce'] ) ) {
			if ( wp_verify_nonce( $_POST['location_nonce'], 'bw_schema_add_location' ) ) {
				$this->handle_location_save();
				return;
			}
		}

		// Save business category and type if present in POST
		if ( isset( $_POST['bw_schema_business_category'] ) && $_POST['bw_schema_business_category'] !== '' ) {
			$category = sanitize_key( $_POST['bw_schema_business_category'] );
			update_option( 'bw_schema_business_category', $category );
		}

		if ( isset( $_POST['bw_schema_business_type'] ) && $_POST['bw_schema_business_type'] !== '' ) {
			$type = sanitize_key( $_POST['bw_schema_business_type'] );
			update_option( 'bw_schema_business_type', $type );
		}

		// "Not used" field opt-outs — absent checkboxes clear the opt-out
		$optouts = isset( $_POST['bw_schema_field_optout'] ) && is_array( $_POST['bw_schema_field_optout'] )
			? array_map( 'sanitize_key', wp_unslash( $_POST['bw_schema_field_optout'] ) )
			: array();
		BW_Schema_Service_Organization::set_field_optouts( $optouts );

		// Get field definitions and current data
		$fields = BW_Schema_Service_Organization::get_field_definitions();
		$current_data = BW_Schema_Service_Organization::get();

		// IMPORTANT: Include business type fields in the form so conditional fields are validated
		// This matches what render() does
		$all_fields = array_merge(
			$this->get_business_type_fields(),
			$fields
		);

		// Build and validate form
		$form = BW_Schema_Form_Builder::build_form( 'organization', $all_fields, $current_data );

		if ( ! $form->validate( $_POST ) ) {
			// Validation failed - errors will display in form
			return;
		}

		// Sanitize form data
		$result = $form->validate_and_save( $_POST );

		if ( is_wp_error( $result ) ) {
			$this->add_error( $result->get_error_message() );
			return;
		}

		// Add type-specific fields from POST to the sanitized data
		$sanitized_data = $result['sanitized'];

		// Process type-specific conditional fields
		$type_specific_fields = array(
			// Accommodation
			'accommodation_chain_name',
			'accommodation_star_rating',
			'accommodation_num_rooms',
			// Food & Beverage
			'food_beverage_cuisine_type',
			'food_beverage_price_range',
			'food_beverage_delivery',
			// Medical & Healthcare
			'medical_license_number',
			'medical_specialization',
			// Retail
			'retail_accepts_returns',
			// Professional Services
			'professional_license_number',
			'professional_specialization',
			'professional_years_experience',
			// Real Estate
			'realestate_mls_number',
			'realestate_specialization',
			// Automotive
			'automotive_services',
			// Entertainment
			'entertainment_capacity',
			// Beauty & Personal Care
			'beauty_services',
			// Education
			'education_accreditation',
			// Finance & Banking
			'finance_member_networks',
			// NOTE: FAQ, Review, and Article fields removed - no longer in Organization form
		);

		foreach ( $type_specific_fields as $field_name ) {
			$is_set = isset( $_POST[ $field_name ] );
			$value = $_POST[ $field_name ] ?? '';

			if ( $is_set && $value !== '' ) {
				// Find the field definition to get sanitizer
				$field_def = null;
				foreach ( $this->get_business_type_fields() as $field ) {
					if ( $field['name'] === $field_name ) {
						$field_def = $field;
						break;
					}
				}

				// Sanitize based on field type
				if ( $field_def ) {
					$sanitizer = $field_def['sanitize'] ?? 'sanitize_text_field';
					if ( is_callable( $sanitizer ) ) {
						$sanitized_data[ $field_name ] = call_user_func( $sanitizer, $_POST[ $field_name ] );
					}
				}
			}
		}

		// Save organization data
		$save_result = BW_Schema_Service_Organization::save( $sanitized_data );

		if ( is_wp_error( $save_result ) ) {
			$this->add_error( $save_result->get_error_message() );
			return;
		}

		// Success message
		$this->add_message( __( 'Organization settings saved successfully.', 'bw-schema' ), 'success' );

		// Non-blocking logo check — a broken logo URL would ship into the
		// schema markup silently, so verify it resolves to an image
		$saved_org = BW_Schema_Service_Organization::get();
		if ( ! empty( $saved_org['logo'] ) ) {
			$logo_check = BW_Schema_Service_Organization::verify_remote_image( $saved_org['logo'] );
			if ( is_wp_error( $logo_check ) ) {
				$this->add_message(
					sprintf(
						/* translators: %s: reason the logo URL failed verification */
						__( 'Heads up: the logo URL may be broken — %s', 'bw-schema' ),
						$logo_check->get_error_message()
					),
					'warning'
				);
			}
		}

		// Invalidate caches so schema is regenerated
		BW_Schema_Cache::invalidate();
		BW_Schema_Cache::invalidate_org_data();
	}

	/**
	 * Render page content
	 *
	 * The page has two tabs: Organization (identity + business type form)
	 * and Locations (shown only for location-based business types).
	 *
	 * @return void
	 */
	protected function render() {
		$this->render_health_strip();

		$show_locations = BW_Schema_Service_Locations::should_show_locations_section();
		$active_tab     = 'general';

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only tab switch
		if ( $show_locations && isset( $_GET['tab'] ) && 'locations' === $_GET['tab'] ) {
			$active_tab = 'locations';
		}

		// Tab navigation (only when there is more than one tab)
		if ( $show_locations ) {
			$base_url = admin_url( 'admin.php?page=bw-schema-organization' );
			echo '<nav class="nav-tab-wrapper" style="margin-bottom: 20px;">';
			echo '<a href="' . esc_url( $base_url ) . '" class="nav-tab ' . ( 'general' === $active_tab ? 'nav-tab-active' : '' ) . '">';
			echo esc_html__( 'Organization', 'bw-schema' );
			echo '</a>';
			echo '<a href="' . esc_url( add_query_arg( 'tab', 'locations', $base_url ) ) . '" class="nav-tab ' . ( 'locations' === $active_tab ? 'nav-tab-active' : '' ) . '">';
			echo esc_html( $this->get_locations_tab_label() );
			echo '</a>';
			echo '</nav>';
		}

		if ( 'locations' === $active_tab ) {
			$this->render_locations_tab();
			return;
		}

		$this->render_general_tab();
	}

	/**
	 * Compact health strip — the same checks the dashboard runs, scoped
	 * to organization data. One standard, no separate percentage.
	 *
	 * @return void
	 */
	private function render_health_strip() {
		$org_check_ids = array( 'org_profile', 'business_type', 'locations' );

		$checks = array_filter(
			BW_Schema_Service_Health::run_checks(),
			function ( $c ) use ( $org_check_ids ) {
				return in_array( $c['id'], $org_check_ids, true );
			}
		);

		if ( empty( $checks ) ) {
			return;
		}

		$short_labels = array(
			'org_profile'   => __( 'Profile', 'bw-schema' ),
			'business_type' => __( 'Business type', 'bw-schema' ),
			'locations'     => __( 'Location', 'bw-schema' ),
		);

		echo '<div class="bw-schema-health-strip">';
		echo '<span class="bw-schema-health-strip-label">' . esc_html__( 'Organization health:', 'bw-schema' ) . '</span>';

		foreach ( $checks as $check ) {
			$label = $short_labels[ $check['id'] ] ?? $check['title'];
			if ( ! empty( $check['progress'] ) ) {
				$label .= ' ' . $check['progress'];
			}

			$class = $check['passing'] ? 'is-pass' : 'is-warn';
			$icon  = $check['passing'] ? '✓' : '!';

			if ( $check['passing'] ) {
				echo '<span class="bw-schema-health-item ' . esc_attr( $class ) . '" title="' . esc_attr( $check['detail'] ) . '">';
				echo '<span aria-hidden="true">' . esc_html( $icon ) . '</span> ' . esc_html( $label );
				echo '</span>';
			} else {
				echo '<a class="bw-schema-health-item ' . esc_attr( $class ) . '" href="' . esc_url( $check['link'] ) . '" title="' . esc_attr( $check['detail'] ) . '">';
				echo '<span aria-hidden="true">' . esc_html( $icon ) . '</span> ' . esc_html( $label );
				echo '</a>';
			}
		}

		echo '</div>';
	}

	/**
	 * Context-appropriate label for the Locations tab
	 *
	 * @return string Tab label
	 */
	private function get_locations_tab_label() {
		$category = get_option( 'bw_schema_business_category', '' );

		$category_labels = array(
			'accommodation' => __( 'Locations & Rooms', 'bw-schema' ),
			'food_beverage' => __( 'Restaurant Locations', 'bw-schema' ),
			'medical'       => __( 'Offices & Branches', 'bw-schema' ),
			'retail'        => __( 'Store Locations', 'bw-schema' ),
			'professional'  => __( 'Office Locations', 'bw-schema' ),
			'automotive'    => __( 'Service Locations', 'bw-schema' ),
			'entertainment' => __( 'Venue Locations', 'bw-schema' ),
			'beauty'        => __( 'Salon Locations', 'bw-schema' ),
			'education'     => __( 'Campus Locations', 'bw-schema' ),
			'finance'       => __( 'Branch Locations', 'bw-schema' ),
			'realestate'    => __( 'Office & Property Locations', 'bw-schema' ),
			'services'      => __( 'Service Locations', 'bw-schema' ),
		);

		return $category_labels[ $category ] ?? __( 'Locations', 'bw-schema' );
	}

	/**
	 * Render the general (organization identity) tab
	 *
	 * @return void
	 */
	private function render_general_tab() {
		// Get current organization data
		$current_data = BW_Schema_Service_Organization::get();
		$fields = BW_Schema_Service_Organization::get_field_definitions();

		// Description
		$this->render_description(
			__( 'Configure your organization\'s basic information. This data appears in schema markup across your website.', 'bw-schema' )
		);

		// Add business classification section heading
		echo '<h2 style="margin-top: 40px;">' . esc_html__( 'Business Classification (Schema.org)', 'bw-schema' ) . '</h2>';
		echo '<p class="description">';
		echo esc_html__( 'Select your business category and specific type based on schema.org standards. The Business Type options will update automatically.', 'bw-schema' );
		echo '</p>';

		// Get saved category and type
		$saved_category = get_option( 'bw_schema_business_category', '' );
		$saved_type = get_option( 'bw_schema_business_type', '' );

		// Merge business type fields with organization fields
		$all_fields = array_merge(
			$this->get_business_type_fields(),
			$fields
		);

		$form_data = array_merge(
			$current_data,
			array(
				'bw_schema_business_category' => $saved_category,
				'bw_schema_business_type'      => $saved_type,
			)
		);

		// IMPORTANT: Render all fields in a SINGLE form to ensure all data is submitted together
		// (the form builder renders the Save Changes button inside the form)
		$this->render_form( 'organization', $all_fields, $form_data );

		// Add inline JavaScript for real-time Business Type updates
		$this->render_business_type_updater();
	}

	/**
	 * Render the locations tab
	 *
	 * @return void
	 */
	private function render_locations_tab() {
		$this->render_locations_section();
	}

	/**
	 * Render inline JavaScript for real-time Business Type dropdown updates
	 *
	 * @return void
	 */
	private function render_business_type_updater() {
		$all_types = BW_Schema_Service_Organization::get_business_types();
		?>
		<script type="text/javascript">
		(function() {
			// Business type data with array format [label, schema_type]
			var allBusinessTypes = <?php echo wp_json_encode( $all_types ); ?>;

			// Get the select elements
			var categorySelect = document.querySelector('select[name="bw_schema_business_category"]');
			var typeSelect = document.querySelector('select[name="bw_schema_business_type"]');

			if (!categorySelect || !typeSelect) {
				return; // Elements not found
			}

			// Store the current type value on load so we can detect if category changed
			var lastCategory = categorySelect.value;

			/**
			 * Update Business Type options based on selected category
			 */
			function updateBusinessTypes(isUserChange) {
				var selectedCategory = categorySelect.value;
				// IMPORTANT: Save the current type value BEFORE clearing options
				// If we clear options first, typeSelect.value resets to empty string
				var savedTypeValue = typeSelect.value;

				// Clear existing options except the first placeholder
				while (typeSelect.options.length > 1) {
					typeSelect.remove(1);
				}

				if (!selectedCategory) {
					// No category selected - disable type select
					typeSelect.disabled = true;
					typeSelect.options[0].textContent = '— Select Type —';
					return;
				}

				// Check if category has types
				if (!allBusinessTypes[selectedCategory]) {
					typeSelect.disabled = true;
					return;
				}

				// Enable type select and populate options
				typeSelect.disabled = false;
				var categoryTypes = allBusinessTypes[selectedCategory];

				for (var typeKey in categoryTypes) {
					if (categoryTypes.hasOwnProperty(typeKey)) {
						var typeData = categoryTypes[typeKey];
						// Extract label from array [label, schema_type]
						var label = Array.isArray(typeData) ? typeData[0] : typeData;

						var option = document.createElement('option');
						option.value = typeKey;
						option.textContent = label;
						typeSelect.appendChild(option);
					}
				}


				// Reset type selection ONLY if user changed the category
				// On initial load, preserve the saved type value
				var typeValue = '';
				if (isUserChange) {
					typeSelect.value = '';
					typeValue = '';
				} else {
					// Try to set the saved value - it may not exist in new options
					typeSelect.value = savedTypeValue;
					typeValue = typeSelect.value;  // Get what was actually set
				}

				// Show/hide conditional fields based on type
				updateConditionalFields(typeValue);
			}

			/**
			 * Show/hide conditional fields based on business type
			 */
			function updateConditionalFields(businessType) {
				var conditionalFields = document.querySelectorAll('[data-show-if]');

				conditionalFields.forEach(function(field) {
					var showIf = field.getAttribute('data-show-if');

					// Parse show_if condition (format: "business_type:hotel,resort" for multiple types)
					var shouldShow = false;
					if (showIf && showIf.indexOf('business_type:') === 0) {
						var requiredTypes = showIf.replace('business_type:', '').split(',');
						// Show if businessType matches any of the required types
						shouldShow = requiredTypes.indexOf(businessType) !== -1;
					}

					// Show or hide the field row
					if (shouldShow) {
						field.style.display = '';
						field.style.opacity = '1';

						// IMPORTANT: When showing, make sure the field is ENABLED so it submits
						var input = field.querySelector('input, textarea, select');
						if (input) {
							input.disabled = false;
						}
					} else {
						field.style.display = 'none';
						field.style.opacity = '0';

						// When hiding, clear the value AND disable so it doesn't submit
						var input = field.querySelector('input, textarea, select');
						if (input) {
							input.value = '';  // Clear the value
							input.disabled = true;  // Disable so it won't submit
						}
					}
				});
			}

			// Add change event listener to category select (user change)
			categorySelect.addEventListener('change', function() {
				updateBusinessTypes(true);  // true = user initiated change
			});

			// Add change event listener to type select (user selects a type)
			typeSelect.addEventListener('change', function() {
				updateConditionalFields(this.value);
			});

			// Initialize on page load (NOT a user change)
			updateBusinessTypes(false);  // false = initial load
		})();
		</script>
		<?php
	}

	/**
	 * Get business type fields for the form builder
	 *
	 * @return array Field definitions for category, type, and type-specific identity fields
	 */
	private function get_business_type_fields() {
		$categories = BW_Schema_Service_Organization::get_business_categories();
		$category = get_option( 'bw_schema_business_category', '' );
		$type = get_option( 'bw_schema_business_type', '' );
		$all_types = BW_Schema_Service_Organization::get_business_types();
		$type_options = array();

		if ( $category && isset( $all_types[ $category ] ) ) {
			foreach ( $all_types[ $category ] as $type_key => $type_data ) {
				$type_options[ $type_key ] = is_array( $type_data ) ? $type_data[0] : $type_data;
			}
		}

		// Get current field values
		$current_data = get_option( 'bw_schema_organization', array() );

		return array(
			// Main selectors
			array(
				'section'   => 'classification',
				'name'      => 'bw_schema_business_category',
				'label'     => __( 'Business Category', 'bw-schema' ),
				'type'      => 'select',
				'options'   => $categories,
				'help'      => __( 'Choose the main business category that best describes your organization.', 'bw-schema' ),
				'sanitize'  => 'sanitize_key',
			),
			array(
				'section'   => 'classification',
				'name'      => 'bw_schema_business_type',
				'label'     => __( 'Business Type', 'bw-schema' ),
				'type'      => 'select',
				'options'   => $type_options,
				'help'      => __( 'Select the specific business type. First choose a category above.', 'bw-schema' ),
				'sanitize'  => 'sanitize_key',
			),

			// Type-specific identity fields

			// ===== ACCOMMODATION =====
			array(
				'section'        => 'classification',
				'name'           => 'accommodation_chain_name',
				'label'          => __( 'Chain Name', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'If part of a hotel chain (e.g., "Marriott", "Hilton").', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'hotel', 'resort' ) ),
				'sanitize'       => 'sanitize_text_field',
			),
			array(
				'section'        => 'classification',
				'name'           => 'accommodation_star_rating',
				'label'          => __( 'Star Rating', 'bw-schema' ),
				'type'           => 'number',
				'help'           => __( 'Hotel star rating (1-5).', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'hotel', 'resort' ) ),
				'sanitize'       => 'absint',
				'validate'       => 'number',
			),
			array(
				'section'        => 'classification',
				'name'           => 'accommodation_num_rooms',
				'label'          => __( 'Number of Rooms', 'bw-schema' ),
				'type'           => 'number',
				'help'           => __( 'Total number of guest rooms.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'hotel', 'resort', 'hostel' ) ),
				'sanitize'       => 'absint',
			),

			// ===== FOOD & BEVERAGE =====
			array(
				'section'        => 'classification',
				'name'           => 'food_beverage_cuisine_type',
				'label'          => __( 'Cuisine Type', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'e.g., Italian, Japanese, Vegan, Fusion, American.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'restaurant', 'cafe', 'bakery' ) ),
				'sanitize'       => 'sanitize_text_field',
			),
			array(
				'section'        => 'classification',
				'name'           => 'food_beverage_price_range',
				'label'          => __( 'Price Range', 'bw-schema' ),
				'type'           => 'select',
				'options'        => array(
					'$'    => __( '$ - Budget Friendly', 'bw-schema' ),
					'$$'   => __( '$$ - Moderate', 'bw-schema' ),
					'$$$'  => __( '$$$ - Upscale', 'bw-schema' ),
					'$$$$' => __( '$$$$ - Fine Dining', 'bw-schema' ),
				),
				'help'           => __( 'Average price level for dining.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'restaurant', 'bar', 'cafe', 'brewery', 'icecream' ) ),
				'sanitize'       => 'sanitize_text_field',
			),
			array(
				'section'        => 'classification',
				'name'           => 'food_beverage_delivery',
				'label'          => __( 'Offers Delivery', 'bw-schema' ),
				'type'           => 'select',
				'options'        => array(
					'yes' => __( 'Yes', 'bw-schema' ),
					'no'  => __( 'No', 'bw-schema' ),
				),
				'help'           => __( 'Does this restaurant offer delivery service?', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'restaurant', 'cafe', 'bakery' ) ),
				'sanitize'       => 'sanitize_text_field',
			),

			// ===== MEDICAL & HEALTHCARE =====
			array(
				'section'        => 'classification',
				'name'           => 'medical_license_number',
				'label'          => __( 'License / Registration Number', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'Medical facility license or registration number.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'hospital', 'clinic', 'dentist', 'physician', 'pharmacy', 'veterinary' ) ),
				'sanitize'       => 'sanitize_text_field',
			),
			array(
				'section'        => 'classification',
				'name'           => 'medical_specialization',
				'label'          => __( 'Medical Specialization', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'e.g., Orthopedic Surgery, Pediatrics, Dermatology.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'physician', 'dentist', 'clinic' ) ),
				'sanitize'       => 'sanitize_text_field',
			),

			// ===== RETAIL =====
			array(
				'section'        => 'classification',
				'name'           => 'retail_accepts_returns',
				'label'          => __( 'Accepts Returns', 'bw-schema' ),
				'type'           => 'select',
				'options'        => array(
					'yes' => __( 'Yes - Full Refund', 'bw-schema' ),
					'exchange' => __( 'Exchange Only', 'bw-schema' ),
					'no'  => __( 'No Returns', 'bw-schema' ),
				),
				'help'           => __( 'Return policy for retail items.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'bookstore', 'clothingstore', 'electronicsstore', 'grocerystore', 'hardwarestore', 'toysstore' ) ),
				'sanitize'       => 'sanitize_text_field',
			),

			// ===== PROFESSIONAL SERVICES =====
			array(
				'section'        => 'classification',
				'name'           => 'professional_license_number',
				'label'          => __( 'License / Bar Number', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'Professional license or bar number.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'attorney', 'accountant', 'consulting' ) ),
				'sanitize'       => 'sanitize_text_field',
			),
			array(
				'section'        => 'classification',
				'name'           => 'professional_specialization',
				'label'          => __( 'Areas of Specialization', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'e.g., Corporate Law, Tax Planning, Business Consulting.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'attorney', 'accountant', 'consulting' ) ),
				'sanitize'       => 'sanitize_text_field',
			),
			array(
				'section'        => 'classification',
				'name'           => 'professional_years_experience',
				'label'          => __( 'Years in Business', 'bw-schema' ),
				'type'           => 'number',
				'help'           => __( 'Years of professional experience.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'attorney', 'accountant', 'realestateagent', 'consulting' ) ),
				'sanitize'       => 'absint',
			),

			// ===== REAL ESTATE =====
			array(
				'section'        => 'classification',
				'name'           => 'realestate_mls_number',
				'label'          => __( 'License / MLS Number', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'Real estate license or MLS member ID.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'realestateagent', 'realestatebiz' ) ),
				'sanitize'       => 'sanitize_text_field',
			),
			array(
				'section'        => 'classification',
				'name'           => 'realestate_specialization',
				'label'          => __( 'Specialization', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'e.g., Residential, Commercial, Investment Properties.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'realestateagent' ) ),
				'sanitize'       => 'sanitize_text_field',
			),

			// ===== AUTOMOTIVE =====
			array(
				'section'        => 'classification',
				'name'           => 'automotive_services',
				'label'          => __( 'Services Offered', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'e.g., Oil Changes, Brake Service, Full Restoration.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'autorepair', 'carwash' ) ),
				'sanitize'       => 'sanitize_text_field',
			),

			// ===== ENTERTAINMENT =====
			array(
				'section'        => 'classification',
				'name'           => 'entertainment_capacity',
				'label'          => __( 'Seating/Capacity', 'bw-schema' ),
				'type'           => 'number',
				'help'           => __( 'Maximum number of guests/spectators.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'movietheater', 'bowling', 'sportsfacility', 'nightclub' ) ),
				'sanitize'       => 'absint',
			),

			// ===== BEAUTY & PERSONAL CARE =====
			array(
				'section'        => 'classification',
				'name'           => 'beauty_services',
				'label'          => __( 'Services Offered', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'e.g., Haircuts, Color, Styling, Treatments.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'hairdresser', 'spa', 'tattoo' ) ),
				'sanitize'       => 'sanitize_text_field',
			),

			// ===== EDUCATION =====
			array(
				'section'        => 'classification',
				'name'           => 'education_accreditation',
				'label'          => __( 'Accreditation', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'Accreditation body (e.g., WASC, SACSCOC).', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'university', 'highschool', 'middleschool', 'preschool' ) ),
				'sanitize'       => 'sanitize_text_field',
			),
			array(
				'section'        => 'classification',
				'name'           => 'education_programs',
				'label'          => __( 'Programs Offered', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'e.g., Liberal Arts, STEM, Pre-Med, Business.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'university', 'highschool', 'middleschool' ) ),
				'sanitize'       => 'sanitize_text_field',
			),

			// ===== FINANCE =====
			array(
				'section'        => 'classification',
				'name'           => 'finance_charter_number',
				'label'          => __( 'Charter / FDIC Number', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'Bank charter or FDIC certificate number.', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'bank', 'creditunion' ) ),
				'sanitize'       => 'sanitize_text_field',
			),

			// ===== SERVICES =====
			array(
				'section'        => 'classification',
				'name'           => 'services_area_coverage',
				'label'          => __( 'Service Area', 'bw-schema' ),
				'type'           => 'text',
				'help'           => __( 'Geographic area served (e.g., "Within 20 miles of downtown").', 'bw-schema' ),
				'show_if'        => array( 'business_type' => array( 'cleaningservice', 'deliveryservice', 'laundry', 'movingcompany', 'plumber' ) ),
				'sanitize'       => 'sanitize_text_field',
			),
		);
	}

	/**
	 * Render the organization settings form
	 *
	 * The form builder handles section grouping and heading rendering,
	 * so we just pass all fields to it.
	 *
	 * @param array $fields Field definitions
	 * @param array $current_data Current form data
	 * @return void
	 */
	private function render_organization_form( $fields, $current_data ) {
		// Render form fields using the form builder
		// The form builder handles everything - fields, validation, etc.
		if ( class_exists( 'BW_Schema_Form_Builder' ) ) {
			$form = BW_Schema_Form_Builder::build_form( 'organization', $fields, $current_data );
			// Just output the form as-is - it has its own form tags
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo $form->render();
		}
	}

	/**
	 * Render locations section (conditionally shown based on business type)
	 *
	 * Multi-location management for organizations like hotel chains,
	 * restaurant groups, retail chains, etc.
	 *
	 * @return void
	 */
	private function render_locations_section() {
		$locations = BW_Schema_Service_Locations::get_locations();
		$business_type = get_option( 'bw_schema_business_type', '' );

		echo '<h2 style="margin-top: 40px;">' . esc_html__( 'Business Locations', 'bw-schema' ) . '</h2>';
		echo '<p class="description">';
		echo esc_html__( 'Manage your organization\'s physical locations and branches. Each location has its own contact information and address.', 'bw-schema' );
		echo '</p>';

		// Show locations list
		if ( empty( $locations ) ) {
			echo '<p style="background: #f0f0f0; padding: 15px; border-radius: 4px; margin-bottom: 20px;">';
			echo esc_html__( 'No locations configured yet. Add your first location using the form below.', 'bw-schema' );
			echo '</p>';
		}

		// Add Location button
		echo '<p style="margin-bottom: 20px;">';
		echo '<button type="button" class="button button-primary" id="bw-schema-add-location-btn">' . esc_html__( 'Add Location', 'bw-schema' ) . '</button>';
		echo '</p>';

		if ( ! empty( $locations ) ) {
			echo '<table class="widefat striped" style="margin-bottom: 20px;">';
			echo '<thead><tr>';
			echo '<th>' . esc_html__( 'Name', 'bw-schema' ) . '</th>';
			echo '<th>' . esc_html__( 'Address', 'bw-schema' ) . '</th>';
			echo '<th>' . esc_html__( 'Phone', 'bw-schema' ) . '</th>';
			echo '<th style="width: 180px;">' . esc_html__( 'Actions', 'bw-schema' ) . '</th>';
			echo '</tr></thead>';
			echo '<tbody>';

			foreach ( $locations as $location ) {
				$location_id = $location['id'] ?? '';
				echo '<tr>';
				echo '<td><strong>' . esc_html( $location['name'] ?? '—' ) . '</strong></td>';
				echo '<td>';
				$address_parts = array();
				if ( ! empty( $location['street'] ) ) {
					$address_parts[] = $location['street'];
				}
				if ( ! empty( $location['city'] ) ) {
					$address_parts[] = $location['city'];
				}
				if ( ! empty( $location['region'] ) ) {
					$address_parts[] = $location['region'];
				}
				echo esc_html( implode( ', ', $address_parts ) ?: '—' );
				echo '</td>';
				echo '<td>' . esc_html( $location['telephone'] ?? '—' ) . '</td>';
				echo '<td>';
				echo '<button type="button" class="button button-small bw-schema-edit-location" data-location-id="' . esc_attr( $location_id ) . '">';
				echo esc_html__( 'Edit', 'bw-schema' );
				echo '</button> ';
				echo '<button type="button" class="button button-small button-link-delete bw-schema-delete-location" data-location-id="' . esc_attr( $location_id ) . '">';
				echo esc_html__( 'Delete', 'bw-schema' );
				echo '</button>';
				echo '</td>';
				echo '</tr>';
			}

			echo '</tbody>';
			echo '</table>';
		}

		// Add location form
		$this->render_add_location_form();
	}

	/**
	 * Render the add/edit location form
	 *
	 * @return void
	 */
	private function render_add_location_form() {
		$fields = $this->get_location_field_definitions();

		echo '<div id="bw-schema-location-form-container" style="background: #f9f9f9; padding: 15px; border: 1px solid #ddd; border-radius: 4px; margin-top: 20px; display: none;">';
		echo '<h3 id="bw-schema-form-title">' . esc_html__( 'Add New Location', 'bw-schema' ) . '</h3>';

		echo '<form method="post" id="bw-schema-location-form" class="bw-schema-location-form">';
		wp_nonce_field( 'bw_schema_add_location', 'location_nonce' );
		echo '<input type="hidden" name="location_action" id="location_action" value="add" />';
		echo '<input type="hidden" name="location_id" id="location_id" value="" />';

		// Render location fields
		echo '<table class="form-table">';
		foreach ( $fields as $field ) {
			echo '<tr>';
			echo '<th scope="row">';
			echo '<label for="' . esc_attr( $field['name'] ) . '">' . esc_html( $field['label'] ) . '</label>';
			echo '</th>';
			echo '<td>';

			// Render field based on type
			switch ( $field['type'] ) {
				case 'text':
				case 'email':
				case 'url':
				case 'tel':
					echo '<input type="' . esc_attr( $field['type'] ) . '" id="' . esc_attr( $field['name'] ) . '" name="' . esc_attr( $field['name'] ) . '" class="regular-text" />';
					break;
				case 'textarea':
					echo '<textarea id="' . esc_attr( $field['name'] ) . '" name="' . esc_attr( $field['name'] ) . '" class="large-text" rows="3"></textarea>';
					break;
			}

			if ( ! empty( $field['help'] ) ) {
				echo '<p class="description">' . esc_html( $field['help'] ) . '</p>';
			}
			echo '</td>';
			echo '</tr>';
		}
		echo '</table>';

		echo '<p class="submit">';
		echo '<button type="submit" class="button button-primary" id="bw-schema-submit-button" name="bw_schema_location_submit">' . esc_html__( 'Add Location', 'bw-schema' ) . '</button> ';
		echo '<button type="button" class="button" id="bw-schema-cancel-location">' . esc_html__( 'Cancel', 'bw-schema' ) . '</button>';
		echo '</p>';

		echo '</form>';
		echo '</div>';

		// Add inline JavaScript for form management
		$this->render_location_form_js();
	}

	/**
	 * Render JavaScript for location form management
	 *
	 * @return void
	 */
	private function render_location_form_js() {
		?>
		<script type="text/javascript">
		(function() {
			const formContainer = document.getElementById('bw-schema-location-form-container');
			const form = document.getElementById('bw-schema-location-form');
			const locationIdInput = document.getElementById('location_id');
			const locationActionInput = document.getElementById('location_action');
			const formTitle = document.getElementById('bw-schema-form-title');
			const submitButton = document.getElementById('bw-schema-submit-button');
			const cancelButton = document.getElementById('bw-schema-cancel-location');
			const addLocationBtn = document.getElementById('bw-schema-add-location-btn');

			// Get field names for clearing
			const fieldNames = ['location_name', 'location_street', 'location_city', 'location_region', 'location_postal', 'location_country', 'location_telephone', 'location_email', 'location_url'];

			// Clear form function
			function clearForm() {
				fieldNames.forEach(name => {
					const field = document.getElementById(name);
					if (field) {
						field.value = '';
					}
				});
				locationIdInput.value = '';
				locationActionInput.value = 'add';
				formTitle.textContent = '<?php echo esc_js( __( 'Add New Location', 'bw-schema' ) ); ?>';
				submitButton.textContent = '<?php echo esc_js( __( 'Add Location', 'bw-schema' ) ); ?>';
				formContainer.style.display = 'none';
			}

			// Show form for adding
			function showAddForm() {
				clearForm();
				formContainer.style.display = 'block';
				document.getElementById('location_name').focus();
			}

			// Show form for editing
			function showEditForm(locationId) {
				const table = document.querySelector('.widefat tbody');
				if (!table) return;

				// Find location data in the table
				const rows = table.querySelectorAll('tr');
				let locationData = null;

				rows.forEach(row => {
					if (row.querySelector(`button[data-location-id="${locationId}"]`)) {
						locationData = {
							id: locationId,
							name: row.cells[0].textContent.trim(),
							address: row.cells[1].textContent.trim(),
							phone: row.cells[2].textContent.trim()
						};
					}
				});

				if (locationData) {
					locationIdInput.value = locationId;
					locationActionInput.value = 'edit';
					formTitle.textContent = '<?php echo esc_js( __( 'Edit Location', 'bw-schema' ) ); ?>';
					submitButton.textContent = '<?php echo esc_js( __( 'Update Location', 'bw-schema' ) ); ?>';

					// Parse address and populate fields
					document.getElementById('location_name').value = locationData.name;
					document.getElementById('location_telephone').value = locationData.phone;

					formContainer.style.display = 'block';
					document.getElementById('location_name').focus();
				}
			}

			// Handle delete
			function deleteLocation(locationId) {
				if (!confirm('<?php echo esc_js( __( 'Are you sure you want to delete this location?', 'bw-schema' ) ); ?>')) {
					return;
				}

				// Create a hidden form to submit delete action
				const deleteForm = document.createElement('form');
				deleteForm.method = 'POST';
				deleteForm.style.display = 'none';

				deleteForm.innerHTML = `
					<input type="hidden" name="location_action" value="delete" />
					<input type="hidden" name="location_id" value="${locationId}" />
					<input type="hidden" name="location_nonce" value="<?php echo esc_attr( wp_create_nonce( 'bw_schema_add_location' ) ); ?>" />
				`;

				document.body.appendChild(deleteForm);
				deleteForm.submit();
			}

			// Event listeners
			if (addLocationBtn) {
				addLocationBtn.addEventListener('click', showAddForm);
			}
			cancelButton.addEventListener('click', clearForm);

			// Edit buttons
			document.querySelectorAll('.bw-schema-edit-location').forEach(btn => {
				btn.addEventListener('click', function(e) {
					e.preventDefault();
					showEditForm(this.dataset.locationId);
				});
			});

			// Delete buttons
			document.querySelectorAll('.bw-schema-delete-location').forEach(btn => {
				btn.addEventListener('click', function(e) {
					e.preventDefault();
					deleteLocation(this.dataset.locationId);
				});
			});

			// Check if form should be visible after page load (if there's a message)
			const messages = document.querySelectorAll('.notice');
			if (messages.length > 0) {
				clearForm(); // Hide form after successful add
			}
		})();
		</script>
		<?php
	}

	/**
	 * Get location field definitions
	 *
	 * @return array Field definitions for the location form
	 */
	private function get_location_field_definitions() {
		return array(
			array(
				'name'   => 'location_name',
				'label'  => __( 'Location Name', 'bw-schema' ),
				'type'   => 'text',
				'help'   => __( 'e.g., "Downtown Store", "Main Office"', 'bw-schema' ),
			),
			array(
				'name'   => 'location_street',
				'label'  => __( 'Street Address', 'bw-schema' ),
				'type'   => 'text',
				'help'   => __( 'Street address of the location', 'bw-schema' ),
			),
			array(
				'name'   => 'location_city',
				'label'  => __( 'City', 'bw-schema' ),
				'type'   => 'text',
			),
			array(
				'name'   => 'location_region',
				'label'  => __( 'State / Province', 'bw-schema' ),
				'type'   => 'text',
			),
			array(
				'name'   => 'location_postal',
				'label'  => __( 'Postal Code', 'bw-schema' ),
				'type'   => 'text',
			),
			array(
				'name'   => 'location_country',
				'label'  => __( 'Country', 'bw-schema' ),
				'type'   => 'text',
				'help'   => __( 'Country name or code', 'bw-schema' ),
			),
			array(
				'name'   => 'location_telephone',
				'label'  => __( 'Phone Number', 'bw-schema' ),
				'type'   => 'tel',
				'help'   => __( 'Phone number in international format', 'bw-schema' ),
			),
			array(
				'name'   => 'location_email',
				'label'  => __( 'Email Address', 'bw-schema' ),
				'type'   => 'email',
				'help'   => __( 'Contact email for this location', 'bw-schema' ),
			),
			array(
				'name'   => 'location_url',
				'label'  => __( 'Website', 'bw-schema' ),
				'type'   => 'url',
				'help'   => __( 'Location-specific website URL (optional)', 'bw-schema' ),
			),
		);
	}

	/**
	 * Render submit button at bottom (WordPress settings page style)
	 *
	 * Uses WordPress's native submit_button() to inherit all default styles.
	 * This ensures the button automatically updates with new WordPress versions.
	 *
	 * @return void
	 */
	/**
	 * Handle location form submission (add/edit/delete)
	 *
	 * @return void
	 */
	private function handle_location_save() {
		$action = sanitize_key( $_POST['location_action'] ?? '' );
		$location_id = sanitize_text_field( $_POST['location_id'] ?? '' );

		if ( 'delete' === $action ) {
			// Handle delete
			if ( empty( $location_id ) ) {
				$this->add_error( __( 'Location ID is missing.', 'bw-schema' ) );
				return;
			}

			$result = BW_Schema_Service_Locations::delete_location( $location_id );

			if ( is_wp_error( $result ) ) {
				$this->add_error( $result->get_error_message() );
			} else {
				$this->add_message( __( 'Location deleted successfully.', 'bw-schema' ) );
			}
		} elseif ( 'edit' === $action ) {
			// Handle edit
			if ( empty( $location_id ) ) {
				$this->add_error( __( 'Location ID is missing.', 'bw-schema' ) );
				return;
			}

			$location_data = array(
				'name'      => sanitize_text_field( $_POST['location_name'] ?? '' ),
				'street'    => sanitize_text_field( $_POST['location_street'] ?? '' ),
				'city'      => sanitize_text_field( $_POST['location_city'] ?? '' ),
				'region'    => sanitize_text_field( $_POST['location_region'] ?? '' ),
				'postal'    => sanitize_text_field( $_POST['location_postal'] ?? '' ),
				'country'   => sanitize_text_field( $_POST['location_country'] ?? '' ),
				'telephone' => sanitize_text_field( $_POST['location_telephone'] ?? '' ),
				'email'     => sanitize_email( $_POST['location_email'] ?? '' ),
				'url'       => esc_url_raw( $_POST['location_url'] ?? '' ),
			);

			$result = BW_Schema_Service_Locations::update_location( $location_id, $location_data );

			if ( is_wp_error( $result ) ) {
				$this->add_error( $result->get_error_message() );
			} else {
				$this->add_message( __( 'Location updated successfully.', 'bw-schema' ) );
			}
		} elseif ( 'add' === $action ) {
			// Handle add
			$location_data = array(
				'name'      => sanitize_text_field( $_POST['location_name'] ?? '' ),
				'street'    => sanitize_text_field( $_POST['location_street'] ?? '' ),
				'city'      => sanitize_text_field( $_POST['location_city'] ?? '' ),
				'region'    => sanitize_text_field( $_POST['location_region'] ?? '' ),
				'postal'    => sanitize_text_field( $_POST['location_postal'] ?? '' ),
				'country'   => sanitize_text_field( $_POST['location_country'] ?? '' ),
				'telephone' => sanitize_text_field( $_POST['location_telephone'] ?? '' ),
				'email'     => sanitize_email( $_POST['location_email'] ?? '' ),
				'url'       => esc_url_raw( $_POST['location_url'] ?? '' ),
			);

			$result = BW_Schema_Service_Locations::add_location( $location_data );

			if ( is_wp_error( $result ) ) {
				$this->add_error( $result->get_error_message() );
			} else {
				$this->add_message( __( 'Location added successfully.', 'bw-schema' ) );
			}
		}
	}
}
