<?php
/**
 * FAQ Schema Management Service
 *
 * Manages FAQ (Frequently Asked Questions) schema for SEO.
 *
 * @package BW_Schema
 * @since 3.0.0-babel
 */

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

class BW_Schema_FAQ {

	/**
	 * Get FAQ field definitions for form builder
	 *
	 * @return array Field definitions for FAQ section
	 */
	public static function get_field_definitions() {
		$fields = array();

		// Add fields for up to 5 FAQ items
		for ( $i = 1; $i <= 5; $i++ ) {
			$fields[] = array(
				'section'   => 'faq_schema',
				'name'      => 'faq_question_' . $i,
				'label'     => sprintf( __( 'Question %d', 'bw-schema' ), $i ),
				'type'      => 'text',
				'help'      => __( 'Frequently asked question (e.g., "What are your hours?")', 'bw-schema' ),
				'sanitize'  => 'sanitize_text_field',
			);

			$fields[] = array(
				'section'   => 'faq_schema',
				'name'      => 'faq_answer_' . $i,
				'label'     => sprintf( __( 'Answer %d', 'bw-schema' ), $i ),
				'type'      => 'textarea',
				'help'      => __( 'Answer to the question (supports basic text)', 'bw-schema' ),
				'sanitize'  => 'sanitize_textarea_field',
				'rows'      => 3,
			);
		}

		return $fields;
	}

	/**
	 * Format FAQs for schema.org FAQPage
	 *
	 * @param array $org_data Organization data
	 * @return array FAQPage schema or empty
	 */
	public static function format_for_schema( $org_data ) {
		$faqs = array();

		// Collect all FAQ items
		for ( $i = 1; $i <= 5; $i++ ) {
			$question_key = 'faq_question_' . $i;
			$answer_key = 'faq_answer_' . $i;

			if ( ! empty( $org_data[ $question_key ] ) && ! empty( $org_data[ $answer_key ] ) ) {
				$faqs[] = array(
					'@type'          => 'Question',
					'name'           => $org_data[ $question_key ],
					'acceptedAnswer' => array(
						'@type' => 'Answer',
						'text'  => $org_data[ $answer_key ],
					),
				);
			}
		}

		// Return FAQPage schema if we have FAQs
		if ( ! empty( $faqs ) ) {
			return array(
				'@type'   => 'FAQPage',
				'mainEntity' => $faqs,
			);
		}

		return array();
	}

	/**
	 * Get FAQ count
	 *
	 * @param array $org_data Organization data
	 * @return int Number of FAQs configured
	 */
	public static function count_faqs( $org_data ) {
		$count = 0;
		for ( $i = 1; $i <= 5; $i++ ) {
			if ( ! empty( $org_data[ 'faq_question_' . $i ] ) ) {
				$count++;
			}
		}
		return $count;
	}
}
