<?php
/**
 * Frontend Agent Rules Admin Settings
 *
 * Custom business instructions for the assistant (system-level guidance).
 *
 * @package Niwa_AI
 * @since   0.2.2
 */

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

class Niwa_AI_Agent_Mode_Settings {

	const OPTION_KEY = Niwa_AI_Constants::OPT_AGENT_PROFILE;

	/**
	 * Register hooks.
	 */
	public function register_hooks() {
		add_action( 'admin_menu', array( $this, 'add_submenu' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
	}

	/**
	 * Add submenu page under Niwa AI.
	 */
	public function add_submenu() {
		add_submenu_page(
			'niwa-ai',
			__( 'Frontend Agent Rules', 'niwa-ai' ),
			__( 'Frontend Agent Rules', 'niwa-ai' ),
			'manage_options',
			'niwa-ai-agent-mode',
			array( $this, 'render_page' )
		);
	}

	/**
	 * Register settings.
	 */
	public function register_settings() {
		register_setting( 'niwa_ai_agent_mode_group', self::OPTION_KEY, array( $this, 'sanitize' ) );
	}

	/**
	 * Sanitize settings.
	 *
	 * @param mixed $input Raw input.
	 * @return array
	 */
	public function sanitize( $input ) {
		$existing = get_option( self::OPTION_KEY, array() );
		$out      = is_array( $existing ) ? $existing : array();

		if ( ! is_array( $input ) ) {
			return $out;
		}

		$fields = $this->get_fields();
		foreach ( $fields as $key => $meta ) {
			if ( ! array_key_exists( $key, $input ) ) {
				continue;
			}

			$value = $input[ $key ];
			if ( 'text' === $meta['type'] ) {
				$out[ $key ] = sanitize_text_field( $value );
			} else {
				$out[ $key ] = wp_kses_post( $value );
			}
		}

		return $out;
	}

	/**
	 * Render admin page.
	 */
	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$profile = $this->get_profile();
		$fields  = $this->get_fields();

		/* ── Card definitions: group keys → card meta ── */
		$cards = array(
			'business_identity' => array(
				'title' => __( 'Business Identity', 'niwa-ai' ),
				'icon'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="21" x2="9" y2="9"/><line x1="15" y1="21" x2="15" y2="9"/><line x1="3" y1="9" x2="21" y2="9"/></svg>',
				'keys'  => array( 'company_name', 'about', 'products_services' ),
			),
			'knowledge_base'    => array(
				'title' => __( 'Knowledge Base', 'niwa-ai' ),
				'icon'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>',
				'keys'  => array( 'faq', 'policies' ),
			),
			'communication'     => array(
				'title' => __( 'Communication', 'niwa-ai' ),
				'icon'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',
				'keys'  => array( 'tone', 'dos' ),
			),
			'sales_strategy'    => array(
				'title' => __( 'Sales Strategy', 'niwa-ai' ),
				'icon'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>',
				'keys'  => array( 'coupon_rules', 'bundle_rules' ),
			),
			'support'           => array(
				'title' => __( 'Support', 'niwa-ai' ),
				'icon'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 18v-6a9 9 0 0 1 18 0v6"/><path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"/></svg>',
				'keys'  => array( 'human_handoff', 'human_hook_hours' ),
			),
			'additional'        => array(
				'title' => __( 'Additional', 'niwa-ai' ),
				'icon'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>',
				'keys'  => array( 'extra' ),
			),
		);

		/* ── Page wrapper ── */
		echo '<div class="wrap niwa-wrap">';

		/* ── Page header ── */
		echo '<div class="niwa-page-header">';
		echo '<div class="niwa-page-header__icon">';
		echo '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a7 7 0 0 1 7 7c0 2.38-1.19 4.47-3 5.74V17a2 2 0 0 1-2 2H10a2 2 0 0 1-2-2v-2.26C6.19 13.47 5 11.38 5 9a7 7 0 0 1 7-7z"/><line x1="9" y1="22" x2="15" y2="22"/><line x1="12" y1="17" x2="12" y2="22"/><circle cx="12" cy="9" r="2"/></svg>';
		echo '</div>';
		echo '<div class="niwa-page-header__text">';
		echo '<h1 class="niwa-page-header__title">' . esc_html__( 'Frontend Agent Rules', 'niwa-ai' ) . '</h1>';
		echo '<p class="niwa-page-header__subtitle">' . esc_html__( 'Custom business instructions for the AI assistant — injected into system-level guidance.', 'niwa-ai' ) . '</p>';
		echo '</div>';
		echo '</div>';

		/* ── Single form wrapping all cards ── */
		echo '<form method="post" action="options.php">';
		settings_fields( 'niwa_ai_agent_mode_group' );

		$card_keys  = array_keys( $cards );
		$last_card  = end( $card_keys );

		foreach ( $cards as $card_id => $card ) {
			echo '<div class="niwa-card">';

			/* Card header */
			echo '<div class="niwa-card__header">';
			echo '<div class="niwa-card__icon">' . $card['icon'] . '</div>';
			echo '<h2 class="niwa-card__title">' . esc_html( $card['title'] ) . '</h2>';
			echo '</div>';

			/* Card body — render each field in this group */
			echo '<div class="niwa-card__body">';

			foreach ( $card['keys'] as $key ) {
				if ( ! isset( $fields[ $key ] ) ) {
					continue;
				}

				$meta  = $fields[ $key ];
				$name  = self::OPTION_KEY . '[' . $key . ']';
				$label = isset( $meta['label'] ) ? (string) $meta['label'] : $key;
				$type  = isset( $meta['type'] ) ? (string) $meta['type'] : 'textarea';
				$help  = isset( $meta['help'] ) ? (string) $meta['help'] : '';
				$value = isset( $profile[ $key ] ) ? (string) $profile[ $key ] : '';
				$id    = 'niwa-agent-' . $key;

				echo '<div class="niwa-field">';
				echo '<label class="niwa-field__label" for="' . esc_attr( $id ) . '">' . esc_html( $label ) . '</label>';

				if ( '' !== $help ) {
					echo '<span class="niwa-field__hint">' . esc_html( $help ) . '</span>';
				}

				if ( 'text' === $type ) {
					echo '<input id="' . esc_attr( $id ) . '" type="text" name="' . esc_attr( $name ) . '" value="' . esc_attr( $value ) . '" class="niwa-input--wide" />';
				} else {
					echo '<textarea id="' . esc_attr( $id ) . '" name="' . esc_attr( $name ) . '" rows="4" class="niwa-input--wide" style="max-width:100%;">' . esc_textarea( $value ) . '</textarea>';
				}

				echo '</div>';
			}

			echo '</div>'; // .niwa-card__body

			/* Submit button in the last card's footer */
			if ( $card_id === $last_card ) {
				echo '<div class="niwa-card__footer">';
				submit_button( __( 'Save Frontend Agent Rules', 'niwa-ai' ), 'primary niwa-btn niwa-btn--primary', 'submit', false );
				echo '</div>';
			}

			echo '</div>'; // .niwa-card
		}

		echo '</form>';
		echo '</div>'; // .wrap .niwa-wrap
	}

	/**
	 * Get profile values.
	 *
	 * On first call after upgrade the legacy option is migrated into the
	 * current key and deleted so no runtime fallback remains.
	 *
	 * @return array
	 */
	private function get_profile() {
		$profile = get_option( self::OPTION_KEY, array() );

		if ( ( ! is_array( $profile ) || empty( $profile ) ) && false !== get_option( Niwa_AI_Constants::LEGACY_OPT_AGENT_PROFILE ) ) {
			$legacy = get_option( Niwa_AI_Constants::LEGACY_OPT_AGENT_PROFILE, array() );
			if ( is_array( $legacy ) && ! empty( $legacy ) ) {
				update_option( self::OPTION_KEY, $legacy );
				$profile = $legacy;
			}
			delete_option( Niwa_AI_Constants::LEGACY_OPT_AGENT_PROFILE );
		}

		if ( ! is_array( $profile ) ) {
			$profile = array();
		}

		return wp_parse_args( $profile, $this->get_default_profile() );
	}

	/**
	 * Default empty profile.
	 *
	 * @return array
	 */
	private function get_default_profile() {
		$defaults = array();
		foreach ( $this->get_fields() as $key => $meta ) {
			$defaults[ $key ] = '';
		}
		return $defaults;
	}

	/**
	 * Agent mode fields.
	 *
	 * @return array
	 */
	private function get_fields() {
		return array(
			'company_name'    => array(
				'label' => 'Company Name',
				'type'  => 'text',
				'help'  => 'Business/brand name used by the assistant.',
			),
			'about'           => array(
				'label' => 'About Business',
				'type'  => 'textarea',
				'help'  => 'Short brand context and value proposition.',
			),
			'products_services' => array(
				'label' => 'Products / Services',
				'type'  => 'textarea',
				'help'  => 'Key offerings and differentiators.',
			),
			'faq'             => array(
				'label' => 'FAQ',
				'type'  => 'textarea',
				'help'  => 'Q/A facts the assistant should follow strictly.',
			),
			'policies'        => array(
				'label' => 'Policies',
				'type'  => 'textarea',
				'help'  => 'Shipping, returns, payment, support policy details.',
			),
			'tone'            => array(
				'label' => 'Tone / Style',
				'type'  => 'text',
				'help'  => 'How the assistant should communicate.',
			),
			'dos'             => array(
				'label' => 'DO / DON\'T Rules',
				'type'  => 'textarea',
				'help'  => 'Behavior constraints and mandatory response rules.',
			),
			'coupon_rules'    => array(
				'label' => 'Coupon Rules',
				'type'  => 'textarea',
				'help'  => 'When and how coupons should be offered.',
			),
			'bundle_rules'    => array(
				'label' => 'Bundle Rules',
				'type'  => 'textarea',
				'help'  => 'Cross-sell / bundle strategy and limits.',
			),
			'human_handoff'   => array(
				'label' => 'Human Handoff Rules',
				'type'  => 'textarea',
				'help'  => 'Escalation conditions to human support.',
			),
			'human_hook_hours' => array(
				'label' => 'Human Support Hours',
				'type'  => 'text',
				'help'  => 'Working hours for human support team.',
			),
			'extra'           => array(
				'label' => 'Additional Instructions',
				'type'  => 'textarea',
				'help'  => 'Any extra priorities, CTAs, or business-specific notes.',
			),
		);
	}
}
