<?php
/**
 * Schema Base
 *
 * Abstract base class for all schema types.
 * Child classes implement get() (field definitions) and schema_data()
 * (configuration with show_on rules).
 *
 * @package SEOvaultSEO\Schema
 */

namespace SEOvaultSEO\Schema;

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

abstract class SchemaBase {

	/**
	 * Get schema field definitions.
	 *
	 * @return array
	 */
	abstract public function get();

	/**
	 * Get schema configuration (title, type, show_on, fields).
	 *
	 * @return array
	 */
	abstract public function schema_data();

	/**
	 * Parse fields into a flat key => value array.
	 *
	 * @param array $fields Field definitions.
	 * @return array
	 */
	protected function parse_fields( $fields ) {
		$parsed = array();
		foreach ( $fields as $field ) {
			if ( empty( $field['id'] ) || ( empty( $field['required'] ) && empty( $field['show'] ) ) ) {
				continue;
			}
			if ( isset( $field['default'] ) && false === $field['default'] ) {
				continue;
			}

			$type = $field['type'] ?? 'Text';
			if ( 'Group' === $type && isset( $field['fields'] ) ) {
				$value = $this->parse_group( $field );
			} else {
				$value = $field['std'] ?? '';
			}

			$parsed[ $field['id'] ] = $value;
		}
		return $parsed;
	}

	/**
	 * Parse a group field recursively.
	 *
	 * @param array $field Group field definition.
	 * @return array
	 */
	protected function parse_group( $field ) {
		$group_fields = $this->parse_fields( $field['fields'] );
		if ( 1 === count( $group_fields ) && isset( $group_fields['@type'] ) ) {
			return array();
		}
		if ( ! empty( $field['cloneable'] ) ) {
			return array( $group_fields );
		}
		return $group_fields;
	}
}
