<?php
/**
 * Business logic service for Organization schema data
 *
 * Handles all organization-related CRUD operations, validation, and field definitions.
 * No UI logic here — this is pure business logic for settings management.
 *
 * @package BW_Babel
 * @since 3.0.0-babel
 */

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

class BW_Babel_Service_Organization {

	/**
	 * Prefix for all options (will be bw_babel_* in v3.0.0+)
	 * For now, keeps backward compatibility with bw_schema_*
	 *
	 * @var string
	 */
	const PREFIX = 'bw_schema_'; // TODO: Switch to 'bw_babel_' at v3.0.0-babel release

	/**
	 * Get all organization data from options
	 *
	 * Returns a complete organization record with defaults applied.
	 *
	 * @return array Organization data (name, url, logo, type, description, etc.)
	 */
	public static function get() {
		return wp_parse_args(
			get_option( self::PREFIX . 'organization', array() ),
			self::get_defaults()
		);
	}

	/**
	 * Get organization schema defaults
	 *
	 * @return array Default values for all organization fields
	 */
	public static function get_defaults() {
		return array(
			'name'           => get_bloginfo( 'name' ),
			'url'            => home_url( '/' ),
			'logo'           => '',
			'telephone'      => '',
			'email'          => get_option( 'admin_email' ),
			'slogan'         => '',
			'alternateName'  => '',
			'legalName'      => '',
			'description'    => get_bloginfo( 'description' ),
			'sameAs'         => array(),
			'contactPoint'   => array(),
		);
	}

	/**
	 * Save organization data
	 *
	 * Validates input and saves to options. Returns error if validation fails.
	 *
	 * @param array $data Organization data to save
	 * @return array|WP_Error Array with 'success' => true on success, WP_Error on failure
	 */
	public static function save( $data ) {
		// Validate first
		$validation = self::validate( $data );
		if ( is_wp_error( $validation ) ) {
			return $validation;
		}

		// Sanitize
		$sanitized = self::sanitize( $data );

		// Save to options
		update_option( self::PREFIX . 'organization', $sanitized );

		// Clear related caches
		if ( class_exists( 'BW_Schema_Cache' ) ) {
			BW_Schema_Cache::clear_all();
		}

		return array( 'success' => true );
	}

	/**
	 * Validate organization data
	 *
	 * @param array $data Data to validate
	 * @return bool|WP_Error True if valid, WP_Error if not
	 */
	public static function validate( $data ) {
		// Organization name is required
		if ( empty( $data['name'] ) ) {
			return new WP_Error(
				'missing_org_name',
				__( 'Organization name is required.', 'bw-babel' )
			);
		}

		// URL must be valid
		if ( ! empty( $data['url'] ) && ! filter_var( $data['url'], FILTER_VALIDATE_URL ) ) {
			return new WP_Error(
				'invalid_url',
				__( 'Organization URL must be a valid URL.', 'bw-babel' )
			);
		}

		// Email must be valid
		if ( ! empty( $data['email'] ) && ! is_email( $data['email'] ) ) {
			return new WP_Error(
				'invalid_email',
				__( 'Organization email must be a valid email address.', 'bw-babel' )
			);
		}

		return true;
	}

	/**
	 * Sanitize organization data
	 *
	 * Applies WordPress sanitization functions to each field.
	 *
	 * @param array $data Data to sanitize
	 * @return array Sanitized data
	 */
	public static function sanitize( $data ) {
		$data = wp_parse_args( $data, self::get_defaults() );

		return array(
			'name'           => sanitize_text_field( $data['name'] ?? '' ),
			'url'            => esc_url_raw( $data['url'] ?? '' ),
			'logo'           => esc_url_raw( $data['logo'] ?? '' ),
			'telephone'      => sanitize_text_field( $data['telephone'] ?? '' ),
			'email'          => sanitize_email( $data['email'] ?? '' ),
			'slogan'         => sanitize_text_field( $data['slogan'] ?? '' ),
			'alternateName'  => sanitize_text_field( $data['alternateName'] ?? '' ),
			'legalName'      => sanitize_text_field( $data['legalName'] ?? '' ),
			'description'    => wp_kses_post( $data['description'] ?? '' ),
			'sameAs'         => is_array( $data['sameAs'] ?? array() ) ? array_map( 'esc_url_raw', $data['sameAs'] ) : array(),
			'contactPoint'   => is_array( $data['contactPoint'] ?? array() ) ? $data['contactPoint'] : array(),
		);
	}

	/**
	 * Get field definitions for form builder
	 *
	 * Returns an array of field definitions that the form builder can use
	 * to render the organization settings form. Each field includes validation,
	 * sanitization, help text, and metadata.
	 *
	 * @return array Array of field definitions
	 */
	public static function get_field_definitions() {
		return array(
			// Basic Identity Section
			array(
				'section'   => 'basic_identity',
				'name'      => 'org_name',
				'label'     => __( 'Organization Name', 'bw-babel' ),
				'type'      => 'text',
				'required'  => true,
				'help'      => __( 'Your official organization name as it should appear in schema.', 'bw-babel' ),
				'sanitize'  => 'sanitize_text_field',
				'validate'  => 'required',
				'map_to'    => 'name',
			),
			array(
				'section'   => 'basic_identity',
				'name'      => 'org_alternate_name',
				'label'     => __( 'Alternate / Brand Name', 'bw-babel' ),
				'type'      => 'text',
				'help'      => __( 'A.k.a., DBA, or brand name (e.g., legal name "Acme Corp" but commonly known as "Acme").', 'bw-babel' ),
				'sanitize'  => 'sanitize_text_field',
				'map_to'    => 'alternateName',
			),
			array(
				'section'   => 'basic_identity',
				'name'      => 'org_legal_name',
				'label'     => __( 'Legal Name', 'bw-babel' ),
				'type'      => 'text',
				'help'      => __( 'The legal registered name of your organization (if different from brand name).', 'bw-babel' ),
				'sanitize'  => 'sanitize_text_field',
				'map_to'    => 'legalName',
			),
			array(
				'section'   => 'basic_identity',
				'name'      => 'org_url',
				'label'     => __( 'Website URL', 'bw-babel' ),
				'type'      => 'url',
				'required'  => true,
				'help'      => __( 'Your organization\'s main website URL.', 'bw-babel' ),
				'sanitize'  => 'esc_url_raw',
				'validate'  => array( 'required', 'url' ),
				'map_to'    => 'url',
			),
			array(
				'section'   => 'basic_identity',
				'name'      => 'org_slogan',
				'label'     => __( 'Slogan', 'bw-babel' ),
				'type'      => 'text',
				'help'      => __( 'A catchy phrase or tagline for your organization.', 'bw-babel' ),
				'sanitize'  => 'sanitize_text_field',
				'map_to'    => 'slogan',
			),

			// Contact Section
			array(
				'section'   => 'contact',
				'name'      => 'org_telephone',
				'label'     => __( 'Phone Number', 'bw-babel' ),
				'type'      => 'tel',
				'help'      => __( 'Primary phone number in international format (e.g., +1-201-555-0123).', 'bw-babel' ),
				'sanitize'  => 'sanitize_text_field',
				'map_to'    => 'telephone',
			),
			array(
				'section'   => 'contact',
				'name'      => 'org_email',
				'label'     => __( 'Email Address', 'bw-babel' ),
				'type'      => 'email',
				'help'      => __( 'General contact email for your organization.', 'bw-babel' ),
				'sanitize'  => 'sanitize_email',
				'validate'  => 'email',
				'map_to'    => 'email',
			),

			// Logo & Branding
			array(
				'section'   => 'branding',
				'name'      => 'org_logo',
				'label'     => __( 'Logo URL', 'bw-babel' ),
				'type'      => 'url',
				'help'      => __( 'URL to your organization logo. Renders as a rich ImageObject (width/height auto-detected if in your media library).', 'bw-babel' ),
				'sanitize'  => 'esc_url_raw',
				'validate'  => array( 'url' ),
				'map_to'    => 'logo',
			),

			// Description
			array(
				'section'   => 'description',
				'name'      => 'org_description',
				'label'     => __( 'Description', 'bw-babel' ),
				'type'      => 'textarea',
				'rows'      => 5,
				'help'      => __( 'A comprehensive description of your organization. Appears as the description field in schema.', 'bw-babel' ),
				'sanitize'  => 'wp_kses_post',
				'map_to'    => 'description',
			),
		);
	}

	/**
	 * Get business type options
	 *
	 * Used for categorizing organizations by industry/type.
	 *
	 * @return array Key => Label pairs
	 */
	public static function get_business_types() {
		return array(
			'professional' => __( 'Professional Services (Consulting, Agency, Recruiting, etc.)', 'bw-babel' ),
			'medical'      => __( 'Medical / Healthcare', 'bw-babel' ),
			'hospitality'  => __( 'Hospitality (Hotel, Restaurant)', 'bw-babel' ),
			'education'    => __( 'Educational Institution', 'bw-babel' ),
			'ecommerce'    => __( 'E-commerce / Online Store', 'bw-babel' ),
			'technology'   => __( 'Technology / Software', 'bw-babel' ),
			'realestate'   => __( 'Real Estate', 'bw-babel' ),
			'financial'    => __( 'Financial Services', 'bw-babel' ),
			'media'        => __( 'Media / Publishing', 'bw-babel' ),
			'nonprofit'    => __( 'Non-Profit Organization', 'bw-babel' ),
			'government'   => __( 'Government Agency', 'bw-babel' ),
			'personal'     => __( 'Personal / Individual', 'bw-babel' ),
		);
	}

	/**
	 * Get business type for current organization
	 *
	 * @return string Current business type selection
	 */
	public static function get_business_type() {
		return get_option( self::PREFIX . 'business_type', '' );
	}

	/**
	 * Set business type
	 *
	 * @param string $business_type Business type key
	 * @return bool Success
	 */
	public static function set_business_type( $business_type ) {
		if ( ! array_key_exists( $business_type, self::get_business_types() ) ) {
			return false;
		}

		update_option( self::PREFIX . 'business_type', $business_type );

		// Clear caches
		if ( class_exists( 'BW_Schema_Cache' ) ) {
			BW_Schema_Cache::clear_all();
		}

		return true;
	}
}
